xref: /freebsd/contrib/llvm-project/clang/lib/AST/ExprConstant.cpp (revision 9e5787d2284e187abb5b654d924394a65772e004)
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 "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/FixedPoint.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APInt;
67 using llvm::APSInt;
68 using llvm::APFloat;
69 using llvm::Optional;
70 
71 namespace {
72   struct LValue;
73   class CallStackFrame;
74   class EvalInfo;
75 
76   using SourceLocExprScopeGuard =
77       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
78 
79   static QualType getType(APValue::LValueBase B) {
80     if (!B) return QualType();
81     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
82       // FIXME: It's unclear where we're supposed to take the type from, and
83       // this actually matters for arrays of unknown bound. Eg:
84       //
85       // extern int arr[]; void f() { extern int arr[3]; };
86       // constexpr int *p = &arr[1]; // valid?
87       //
88       // For now, we take the array bound from the most recent declaration.
89       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
90            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
91         QualType T = Redecl->getType();
92         if (!T->isIncompleteArrayType())
93           return T;
94       }
95       return D->getType();
96     }
97 
98     if (B.is<TypeInfoLValue>())
99       return B.getTypeInfoType();
100 
101     if (B.is<DynamicAllocLValue>())
102       return B.getDynamicAllocType();
103 
104     const Expr *Base = B.get<const Expr*>();
105 
106     // For a materialized temporary, the type of the temporary we materialized
107     // may not be the type of the expression.
108     if (const MaterializeTemporaryExpr *MTE =
109             dyn_cast<MaterializeTemporaryExpr>(Base)) {
110       SmallVector<const Expr *, 2> CommaLHSs;
111       SmallVector<SubobjectAdjustment, 2> Adjustments;
112       const Expr *Temp = MTE->getSubExpr();
113       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
114                                                                Adjustments);
115       // Keep any cv-qualifiers from the reference if we generated a temporary
116       // for it directly. Otherwise use the type after adjustment.
117       if (!Adjustments.empty())
118         return Inner->getType();
119     }
120 
121     return Base->getType();
122   }
123 
124   /// Get an LValue path entry, which is known to not be an array index, as a
125   /// field declaration.
126   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
127     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
128   }
129   /// Get an LValue path entry, which is known to not be an array index, as a
130   /// base class declaration.
131   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
132     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
133   }
134   /// Determine whether this LValue path entry for a base class names a virtual
135   /// base class.
136   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
137     return E.getAsBaseOrMember().getInt();
138   }
139 
140   /// Given an expression, determine the type used to store the result of
141   /// evaluating that expression.
142   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
143     if (E->isRValue())
144       return E->getType();
145     return Ctx.getLValueReferenceType(E->getType());
146   }
147 
148   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
149   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
150     const FunctionDecl *Callee = CE->getDirectCallee();
151     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
152   }
153 
154   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
155   /// This will look through a single cast.
156   ///
157   /// Returns null if we couldn't unwrap a function with alloc_size.
158   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
159     if (!E->getType()->isPointerType())
160       return nullptr;
161 
162     E = E->IgnoreParens();
163     // If we're doing a variable assignment from e.g. malloc(N), there will
164     // probably be a cast of some kind. In exotic cases, we might also see a
165     // top-level ExprWithCleanups. Ignore them either way.
166     if (const auto *FE = dyn_cast<FullExpr>(E))
167       E = FE->getSubExpr()->IgnoreParens();
168 
169     if (const auto *Cast = dyn_cast<CastExpr>(E))
170       E = Cast->getSubExpr()->IgnoreParens();
171 
172     if (const auto *CE = dyn_cast<CallExpr>(E))
173       return getAllocSizeAttr(CE) ? CE : nullptr;
174     return nullptr;
175   }
176 
177   /// Determines whether or not the given Base contains a call to a function
178   /// with the alloc_size attribute.
179   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
180     const auto *E = Base.dyn_cast<const Expr *>();
181     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
182   }
183 
184   /// The bound to claim that an array of unknown bound has.
185   /// The value in MostDerivedArraySize is undefined in this case. So, set it
186   /// to an arbitrary value that's likely to loudly break things if it's used.
187   static const uint64_t AssumedSizeForUnsizedArray =
188       std::numeric_limits<uint64_t>::max() / 2;
189 
190   /// Determines if an LValue with the given LValueBase will have an unsized
191   /// array in its designator.
192   /// Find the path length and type of the most-derived subobject in the given
193   /// path, and find the size of the containing array, if any.
194   static unsigned
195   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
196                            ArrayRef<APValue::LValuePathEntry> Path,
197                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
198                            bool &FirstEntryIsUnsizedArray) {
199     // This only accepts LValueBases from APValues, and APValues don't support
200     // arrays that lack size info.
201     assert(!isBaseAnAllocSizeCall(Base) &&
202            "Unsized arrays shouldn't appear here");
203     unsigned MostDerivedLength = 0;
204     Type = getType(Base);
205 
206     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
207       if (Type->isArrayType()) {
208         const ArrayType *AT = Ctx.getAsArrayType(Type);
209         Type = AT->getElementType();
210         MostDerivedLength = I + 1;
211         IsArray = true;
212 
213         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
214           ArraySize = CAT->getSize().getZExtValue();
215         } else {
216           assert(I == 0 && "unexpected unsized array designator");
217           FirstEntryIsUnsizedArray = true;
218           ArraySize = AssumedSizeForUnsizedArray;
219         }
220       } else if (Type->isAnyComplexType()) {
221         const ComplexType *CT = Type->castAs<ComplexType>();
222         Type = CT->getElementType();
223         ArraySize = 2;
224         MostDerivedLength = I + 1;
225         IsArray = true;
226       } else if (const FieldDecl *FD = getAsField(Path[I])) {
227         Type = FD->getType();
228         ArraySize = 0;
229         MostDerivedLength = I + 1;
230         IsArray = false;
231       } else {
232         // Path[I] describes a base class.
233         ArraySize = 0;
234         IsArray = false;
235       }
236     }
237     return MostDerivedLength;
238   }
239 
240   /// A path from a glvalue to a subobject of that glvalue.
241   struct SubobjectDesignator {
242     /// True if the subobject was named in a manner not supported by C++11. Such
243     /// lvalues can still be folded, but they are not core constant expressions
244     /// and we cannot perform lvalue-to-rvalue conversions on them.
245     unsigned Invalid : 1;
246 
247     /// Is this a pointer one past the end of an object?
248     unsigned IsOnePastTheEnd : 1;
249 
250     /// Indicator of whether the first entry is an unsized array.
251     unsigned FirstEntryIsAnUnsizedArray : 1;
252 
253     /// Indicator of whether the most-derived object is an array element.
254     unsigned MostDerivedIsArrayElement : 1;
255 
256     /// The length of the path to the most-derived object of which this is a
257     /// subobject.
258     unsigned MostDerivedPathLength : 28;
259 
260     /// The size of the array of which the most-derived object is an element.
261     /// This will always be 0 if the most-derived object is not an array
262     /// element. 0 is not an indicator of whether or not the most-derived object
263     /// is an array, however, because 0-length arrays are allowed.
264     ///
265     /// If the current array is an unsized array, the value of this is
266     /// undefined.
267     uint64_t MostDerivedArraySize;
268 
269     /// The type of the most derived object referred to by this address.
270     QualType MostDerivedType;
271 
272     typedef APValue::LValuePathEntry PathEntry;
273 
274     /// The entries on the path from the glvalue to the designated subobject.
275     SmallVector<PathEntry, 8> Entries;
276 
277     SubobjectDesignator() : Invalid(true) {}
278 
279     explicit SubobjectDesignator(QualType T)
280         : Invalid(false), IsOnePastTheEnd(false),
281           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
282           MostDerivedPathLength(0), MostDerivedArraySize(0),
283           MostDerivedType(T) {}
284 
285     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
286         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
287           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
288           MostDerivedPathLength(0), MostDerivedArraySize(0) {
289       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
290       if (!Invalid) {
291         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
292         ArrayRef<PathEntry> VEntries = V.getLValuePath();
293         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
294         if (V.getLValueBase()) {
295           bool IsArray = false;
296           bool FirstIsUnsizedArray = false;
297           MostDerivedPathLength = findMostDerivedSubobject(
298               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
299               MostDerivedType, IsArray, FirstIsUnsizedArray);
300           MostDerivedIsArrayElement = IsArray;
301           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
302         }
303       }
304     }
305 
306     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
307                   unsigned NewLength) {
308       if (Invalid)
309         return;
310 
311       assert(Base && "cannot truncate path for null pointer");
312       assert(NewLength <= Entries.size() && "not a truncation");
313 
314       if (NewLength == Entries.size())
315         return;
316       Entries.resize(NewLength);
317 
318       bool IsArray = false;
319       bool FirstIsUnsizedArray = false;
320       MostDerivedPathLength = findMostDerivedSubobject(
321           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
322           FirstIsUnsizedArray);
323       MostDerivedIsArrayElement = IsArray;
324       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
325     }
326 
327     void setInvalid() {
328       Invalid = true;
329       Entries.clear();
330     }
331 
332     /// Determine whether the most derived subobject is an array without a
333     /// known bound.
334     bool isMostDerivedAnUnsizedArray() const {
335       assert(!Invalid && "Calling this makes no sense on invalid designators");
336       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
337     }
338 
339     /// Determine what the most derived array's size is. Results in an assertion
340     /// failure if the most derived array lacks a size.
341     uint64_t getMostDerivedArraySize() const {
342       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
343       return MostDerivedArraySize;
344     }
345 
346     /// Determine whether this is a one-past-the-end pointer.
347     bool isOnePastTheEnd() const {
348       assert(!Invalid);
349       if (IsOnePastTheEnd)
350         return true;
351       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
352           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
353               MostDerivedArraySize)
354         return true;
355       return false;
356     }
357 
358     /// Get the range of valid index adjustments in the form
359     ///   {maximum value that can be subtracted from this pointer,
360     ///    maximum value that can be added to this pointer}
361     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
362       if (Invalid || isMostDerivedAnUnsizedArray())
363         return {0, 0};
364 
365       // [expr.add]p4: For the purposes of these operators, a pointer to a
366       // nonarray object behaves the same as a pointer to the first element of
367       // an array of length one with the type of the object as its element type.
368       bool IsArray = MostDerivedPathLength == Entries.size() &&
369                      MostDerivedIsArrayElement;
370       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
371                                     : (uint64_t)IsOnePastTheEnd;
372       uint64_t ArraySize =
373           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
374       return {ArrayIndex, ArraySize - ArrayIndex};
375     }
376 
377     /// Check that this refers to a valid subobject.
378     bool isValidSubobject() const {
379       if (Invalid)
380         return false;
381       return !isOnePastTheEnd();
382     }
383     /// Check that this refers to a valid subobject, and if not, produce a
384     /// relevant diagnostic and set the designator as invalid.
385     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
386 
387     /// Get the type of the designated object.
388     QualType getType(ASTContext &Ctx) const {
389       assert(!Invalid && "invalid designator has no subobject type");
390       return MostDerivedPathLength == Entries.size()
391                  ? MostDerivedType
392                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
393     }
394 
395     /// Update this designator to refer to the first element within this array.
396     void addArrayUnchecked(const ConstantArrayType *CAT) {
397       Entries.push_back(PathEntry::ArrayIndex(0));
398 
399       // This is a most-derived object.
400       MostDerivedType = CAT->getElementType();
401       MostDerivedIsArrayElement = true;
402       MostDerivedArraySize = CAT->getSize().getZExtValue();
403       MostDerivedPathLength = Entries.size();
404     }
405     /// Update this designator to refer to the first element within the array of
406     /// elements of type T. This is an array of unknown size.
407     void addUnsizedArrayUnchecked(QualType ElemTy) {
408       Entries.push_back(PathEntry::ArrayIndex(0));
409 
410       MostDerivedType = ElemTy;
411       MostDerivedIsArrayElement = true;
412       // The value in MostDerivedArraySize is undefined in this case. So, set it
413       // to an arbitrary value that's likely to loudly break things if it's
414       // used.
415       MostDerivedArraySize = AssumedSizeForUnsizedArray;
416       MostDerivedPathLength = Entries.size();
417     }
418     /// Update this designator to refer to the given base or member of this
419     /// object.
420     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
421       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
422 
423       // If this isn't a base class, it's a new most-derived object.
424       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
425         MostDerivedType = FD->getType();
426         MostDerivedIsArrayElement = false;
427         MostDerivedArraySize = 0;
428         MostDerivedPathLength = Entries.size();
429       }
430     }
431     /// Update this designator to refer to the given complex component.
432     void addComplexUnchecked(QualType EltTy, bool Imag) {
433       Entries.push_back(PathEntry::ArrayIndex(Imag));
434 
435       // This is technically a most-derived object, though in practice this
436       // is unlikely to matter.
437       MostDerivedType = EltTy;
438       MostDerivedIsArrayElement = true;
439       MostDerivedArraySize = 2;
440       MostDerivedPathLength = Entries.size();
441     }
442     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
443     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
444                                    const APSInt &N);
445     /// Add N to the address of this subobject.
446     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
447       if (Invalid || !N) return;
448       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
449       if (isMostDerivedAnUnsizedArray()) {
450         diagnoseUnsizedArrayPointerArithmetic(Info, E);
451         // Can't verify -- trust that the user is doing the right thing (or if
452         // not, trust that the caller will catch the bad behavior).
453         // FIXME: Should we reject if this overflows, at least?
454         Entries.back() = PathEntry::ArrayIndex(
455             Entries.back().getAsArrayIndex() + TruncatedN);
456         return;
457       }
458 
459       // [expr.add]p4: For the purposes of these operators, a pointer to a
460       // nonarray object behaves the same as a pointer to the first element of
461       // an array of length one with the type of the object as its element type.
462       bool IsArray = MostDerivedPathLength == Entries.size() &&
463                      MostDerivedIsArrayElement;
464       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
465                                     : (uint64_t)IsOnePastTheEnd;
466       uint64_t ArraySize =
467           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
468 
469       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
470         // Calculate the actual index in a wide enough type, so we can include
471         // it in the note.
472         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
473         (llvm::APInt&)N += ArrayIndex;
474         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
475         diagnosePointerArithmetic(Info, E, N);
476         setInvalid();
477         return;
478       }
479 
480       ArrayIndex += TruncatedN;
481       assert(ArrayIndex <= ArraySize &&
482              "bounds check succeeded for out-of-bounds index");
483 
484       if (IsArray)
485         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
486       else
487         IsOnePastTheEnd = (ArrayIndex != 0);
488     }
489   };
490 
491   /// A stack frame in the constexpr call stack.
492   class CallStackFrame : public interp::Frame {
493   public:
494     EvalInfo &Info;
495 
496     /// Parent - The caller of this stack frame.
497     CallStackFrame *Caller;
498 
499     /// Callee - The function which was called.
500     const FunctionDecl *Callee;
501 
502     /// This - The binding for the this pointer in this call, if any.
503     const LValue *This;
504 
505     /// Arguments - Parameter bindings for this function call, indexed by
506     /// parameters' function scope indices.
507     APValue *Arguments;
508 
509     /// Source location information about the default argument or default
510     /// initializer expression we're evaluating, if any.
511     CurrentSourceLocExprScope CurSourceLocExprScope;
512 
513     // Note that we intentionally use std::map here so that references to
514     // values are stable.
515     typedef std::pair<const void *, unsigned> MapKeyTy;
516     typedef std::map<MapKeyTy, APValue> MapTy;
517     /// Temporaries - Temporary lvalues materialized within this stack frame.
518     MapTy Temporaries;
519 
520     /// CallLoc - The location of the call expression for this call.
521     SourceLocation CallLoc;
522 
523     /// Index - The call index of this call.
524     unsigned Index;
525 
526     /// The stack of integers for tracking version numbers for temporaries.
527     SmallVector<unsigned, 2> TempVersionStack = {1};
528     unsigned CurTempVersion = TempVersionStack.back();
529 
530     unsigned getTempVersion() const { return TempVersionStack.back(); }
531 
532     void pushTempVersion() {
533       TempVersionStack.push_back(++CurTempVersion);
534     }
535 
536     void popTempVersion() {
537       TempVersionStack.pop_back();
538     }
539 
540     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
541     // on the overall stack usage of deeply-recursing constexpr evaluations.
542     // (We should cache this map rather than recomputing it repeatedly.)
543     // But let's try this and see how it goes; we can look into caching the map
544     // as a later change.
545 
546     /// LambdaCaptureFields - Mapping from captured variables/this to
547     /// corresponding data members in the closure class.
548     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
549     FieldDecl *LambdaThisCaptureField;
550 
551     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
552                    const FunctionDecl *Callee, const LValue *This,
553                    APValue *Arguments);
554     ~CallStackFrame();
555 
556     // Return the temporary for Key whose version number is Version.
557     APValue *getTemporary(const void *Key, unsigned Version) {
558       MapKeyTy KV(Key, Version);
559       auto LB = Temporaries.lower_bound(KV);
560       if (LB != Temporaries.end() && LB->first == KV)
561         return &LB->second;
562       // Pair (Key,Version) wasn't found in the map. Check that no elements
563       // in the map have 'Key' as their key.
564       assert((LB == Temporaries.end() || LB->first.first != Key) &&
565              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
566              "Element with key 'Key' found in map");
567       return nullptr;
568     }
569 
570     // Return the current temporary for Key in the map.
571     APValue *getCurrentTemporary(const void *Key) {
572       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
573       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
574         return &std::prev(UB)->second;
575       return nullptr;
576     }
577 
578     // Return the version number of the current temporary for Key.
579     unsigned getCurrentTemporaryVersion(const void *Key) const {
580       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
581       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
582         return std::prev(UB)->first.second;
583       return 0;
584     }
585 
586     /// Allocate storage for an object of type T in this stack frame.
587     /// Populates LV with a handle to the created object. Key identifies
588     /// the temporary within the stack frame, and must not be reused without
589     /// bumping the temporary version number.
590     template<typename KeyT>
591     APValue &createTemporary(const KeyT *Key, QualType T,
592                              bool IsLifetimeExtended, LValue &LV);
593 
594     void describe(llvm::raw_ostream &OS) override;
595 
596     Frame *getCaller() const override { return Caller; }
597     SourceLocation getCallLocation() const override { return CallLoc; }
598     const FunctionDecl *getCallee() const override { return Callee; }
599 
600     bool isStdFunction() const {
601       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
602         if (DC->isStdNamespace())
603           return true;
604       return false;
605     }
606   };
607 
608   /// Temporarily override 'this'.
609   class ThisOverrideRAII {
610   public:
611     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
612         : Frame(Frame), OldThis(Frame.This) {
613       if (Enable)
614         Frame.This = NewThis;
615     }
616     ~ThisOverrideRAII() {
617       Frame.This = OldThis;
618     }
619   private:
620     CallStackFrame &Frame;
621     const LValue *OldThis;
622   };
623 }
624 
625 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
626                               const LValue &This, QualType ThisType);
627 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
628                               APValue::LValueBase LVBase, APValue &Value,
629                               QualType T);
630 
631 namespace {
632   /// A cleanup, and a flag indicating whether it is lifetime-extended.
633   class Cleanup {
634     llvm::PointerIntPair<APValue*, 1, bool> Value;
635     APValue::LValueBase Base;
636     QualType T;
637 
638   public:
639     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
640             bool IsLifetimeExtended)
641         : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
642 
643     bool isLifetimeExtended() const { return Value.getInt(); }
644     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
645       if (RunDestructors) {
646         SourceLocation Loc;
647         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
648           Loc = VD->getLocation();
649         else if (const Expr *E = Base.dyn_cast<const Expr*>())
650           Loc = E->getExprLoc();
651         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
652       }
653       *Value.getPointer() = APValue();
654       return true;
655     }
656 
657     bool hasSideEffect() {
658       return T.isDestructedType();
659     }
660   };
661 
662   /// A reference to an object whose construction we are currently evaluating.
663   struct ObjectUnderConstruction {
664     APValue::LValueBase Base;
665     ArrayRef<APValue::LValuePathEntry> Path;
666     friend bool operator==(const ObjectUnderConstruction &LHS,
667                            const ObjectUnderConstruction &RHS) {
668       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
669     }
670     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
671       return llvm::hash_combine(Obj.Base, Obj.Path);
672     }
673   };
674   enum class ConstructionPhase {
675     None,
676     Bases,
677     AfterBases,
678     AfterFields,
679     Destroying,
680     DestroyingBases
681   };
682 }
683 
684 namespace llvm {
685 template<> struct DenseMapInfo<ObjectUnderConstruction> {
686   using Base = DenseMapInfo<APValue::LValueBase>;
687   static ObjectUnderConstruction getEmptyKey() {
688     return {Base::getEmptyKey(), {}}; }
689   static ObjectUnderConstruction getTombstoneKey() {
690     return {Base::getTombstoneKey(), {}};
691   }
692   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
693     return hash_value(Object);
694   }
695   static bool isEqual(const ObjectUnderConstruction &LHS,
696                       const ObjectUnderConstruction &RHS) {
697     return LHS == RHS;
698   }
699 };
700 }
701 
702 namespace {
703   /// A dynamically-allocated heap object.
704   struct DynAlloc {
705     /// The value of this heap-allocated object.
706     APValue Value;
707     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
708     /// or a CallExpr (the latter is for direct calls to operator new inside
709     /// std::allocator<T>::allocate).
710     const Expr *AllocExpr = nullptr;
711 
712     enum Kind {
713       New,
714       ArrayNew,
715       StdAllocator
716     };
717 
718     /// Get the kind of the allocation. This must match between allocation
719     /// and deallocation.
720     Kind getKind() const {
721       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
722         return NE->isArray() ? ArrayNew : New;
723       assert(isa<CallExpr>(AllocExpr));
724       return StdAllocator;
725     }
726   };
727 
728   struct DynAllocOrder {
729     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
730       return L.getIndex() < R.getIndex();
731     }
732   };
733 
734   /// EvalInfo - This is a private struct used by the evaluator to capture
735   /// information about a subexpression as it is folded.  It retains information
736   /// about the AST context, but also maintains information about the folded
737   /// expression.
738   ///
739   /// If an expression could be evaluated, it is still possible it is not a C
740   /// "integer constant expression" or constant expression.  If not, this struct
741   /// captures information about how and why not.
742   ///
743   /// One bit of information passed *into* the request for constant folding
744   /// indicates whether the subexpression is "evaluated" or not according to C
745   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
746   /// evaluate the expression regardless of what the RHS is, but C only allows
747   /// certain things in certain situations.
748   class EvalInfo : public interp::State {
749   public:
750     ASTContext &Ctx;
751 
752     /// EvalStatus - Contains information about the evaluation.
753     Expr::EvalStatus &EvalStatus;
754 
755     /// CurrentCall - The top of the constexpr call stack.
756     CallStackFrame *CurrentCall;
757 
758     /// CallStackDepth - The number of calls in the call stack right now.
759     unsigned CallStackDepth;
760 
761     /// NextCallIndex - The next call index to assign.
762     unsigned NextCallIndex;
763 
764     /// StepsLeft - The remaining number of evaluation steps we're permitted
765     /// to perform. This is essentially a limit for the number of statements
766     /// we will evaluate.
767     unsigned StepsLeft;
768 
769     /// Enable the experimental new constant interpreter. If an expression is
770     /// not supported by the interpreter, an error is triggered.
771     bool EnableNewConstInterp;
772 
773     /// BottomFrame - The frame in which evaluation started. This must be
774     /// initialized after CurrentCall and CallStackDepth.
775     CallStackFrame BottomFrame;
776 
777     /// A stack of values whose lifetimes end at the end of some surrounding
778     /// evaluation frame.
779     llvm::SmallVector<Cleanup, 16> CleanupStack;
780 
781     /// EvaluatingDecl - This is the declaration whose initializer is being
782     /// evaluated, if any.
783     APValue::LValueBase EvaluatingDecl;
784 
785     enum class EvaluatingDeclKind {
786       None,
787       /// We're evaluating the construction of EvaluatingDecl.
788       Ctor,
789       /// We're evaluating the destruction of EvaluatingDecl.
790       Dtor,
791     };
792     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
793 
794     /// EvaluatingDeclValue - This is the value being constructed for the
795     /// declaration whose initializer is being evaluated, if any.
796     APValue *EvaluatingDeclValue;
797 
798     /// Set of objects that are currently being constructed.
799     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
800         ObjectsUnderConstruction;
801 
802     /// Current heap allocations, along with the location where each was
803     /// allocated. We use std::map here because we need stable addresses
804     /// for the stored APValues.
805     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
806 
807     /// The number of heap allocations performed so far in this evaluation.
808     unsigned NumHeapAllocs = 0;
809 
810     struct EvaluatingConstructorRAII {
811       EvalInfo &EI;
812       ObjectUnderConstruction Object;
813       bool DidInsert;
814       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
815                                 bool HasBases)
816           : EI(EI), Object(Object) {
817         DidInsert =
818             EI.ObjectsUnderConstruction
819                 .insert({Object, HasBases ? ConstructionPhase::Bases
820                                           : ConstructionPhase::AfterBases})
821                 .second;
822       }
823       void finishedConstructingBases() {
824         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
825       }
826       void finishedConstructingFields() {
827         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
828       }
829       ~EvaluatingConstructorRAII() {
830         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
831       }
832     };
833 
834     struct EvaluatingDestructorRAII {
835       EvalInfo &EI;
836       ObjectUnderConstruction Object;
837       bool DidInsert;
838       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
839           : EI(EI), Object(Object) {
840         DidInsert = EI.ObjectsUnderConstruction
841                         .insert({Object, ConstructionPhase::Destroying})
842                         .second;
843       }
844       void startedDestroyingBases() {
845         EI.ObjectsUnderConstruction[Object] =
846             ConstructionPhase::DestroyingBases;
847       }
848       ~EvaluatingDestructorRAII() {
849         if (DidInsert)
850           EI.ObjectsUnderConstruction.erase(Object);
851       }
852     };
853 
854     ConstructionPhase
855     isEvaluatingCtorDtor(APValue::LValueBase Base,
856                          ArrayRef<APValue::LValuePathEntry> Path) {
857       return ObjectsUnderConstruction.lookup({Base, Path});
858     }
859 
860     /// If we're currently speculatively evaluating, the outermost call stack
861     /// depth at which we can mutate state, otherwise 0.
862     unsigned SpeculativeEvaluationDepth = 0;
863 
864     /// The current array initialization index, if we're performing array
865     /// initialization.
866     uint64_t ArrayInitIndex = -1;
867 
868     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
869     /// notes attached to it will also be stored, otherwise they will not be.
870     bool HasActiveDiagnostic;
871 
872     /// Have we emitted a diagnostic explaining why we couldn't constant
873     /// fold (not just why it's not strictly a constant expression)?
874     bool HasFoldFailureDiagnostic;
875 
876     /// Whether or not we're in a context where the front end requires a
877     /// constant value.
878     bool InConstantContext;
879 
880     /// Whether we're checking that an expression is a potential constant
881     /// expression. If so, do not fail on constructs that could become constant
882     /// later on (such as a use of an undefined global).
883     bool CheckingPotentialConstantExpression = false;
884 
885     /// Whether we're checking for an expression that has undefined behavior.
886     /// If so, we will produce warnings if we encounter an operation that is
887     /// always undefined.
888     bool CheckingForUndefinedBehavior = false;
889 
890     enum EvaluationMode {
891       /// Evaluate as a constant expression. Stop if we find that the expression
892       /// is not a constant expression.
893       EM_ConstantExpression,
894 
895       /// Evaluate as a constant expression. Stop if we find that the expression
896       /// is not a constant expression. Some expressions can be retried in the
897       /// optimizer if we don't constant fold them here, but in an unevaluated
898       /// context we try to fold them immediately since the optimizer never
899       /// gets a chance to look at it.
900       EM_ConstantExpressionUnevaluated,
901 
902       /// Fold the expression to a constant. Stop if we hit a side-effect that
903       /// we can't model.
904       EM_ConstantFold,
905 
906       /// Evaluate in any way we know how. Don't worry about side-effects that
907       /// can't be modeled.
908       EM_IgnoreSideEffects,
909     } EvalMode;
910 
911     /// Are we checking whether the expression is a potential constant
912     /// expression?
913     bool checkingPotentialConstantExpression() const override  {
914       return CheckingPotentialConstantExpression;
915     }
916 
917     /// Are we checking an expression for overflow?
918     // FIXME: We should check for any kind of undefined or suspicious behavior
919     // in such constructs, not just overflow.
920     bool checkingForUndefinedBehavior() const override {
921       return CheckingForUndefinedBehavior;
922     }
923 
924     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
925         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
926           CallStackDepth(0), NextCallIndex(1),
927           StepsLeft(C.getLangOpts().ConstexprStepLimit),
928           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
929           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
930           EvaluatingDecl((const ValueDecl *)nullptr),
931           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
932           HasFoldFailureDiagnostic(false), InConstantContext(false),
933           EvalMode(Mode) {}
934 
935     ~EvalInfo() {
936       discardCleanups();
937     }
938 
939     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
940                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
941       EvaluatingDecl = Base;
942       IsEvaluatingDecl = EDK;
943       EvaluatingDeclValue = &Value;
944     }
945 
946     bool CheckCallLimit(SourceLocation Loc) {
947       // Don't perform any constexpr calls (other than the call we're checking)
948       // when checking a potential constant expression.
949       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
950         return false;
951       if (NextCallIndex == 0) {
952         // NextCallIndex has wrapped around.
953         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
954         return false;
955       }
956       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
957         return true;
958       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
959         << getLangOpts().ConstexprCallDepth;
960       return false;
961     }
962 
963     std::pair<CallStackFrame *, unsigned>
964     getCallFrameAndDepth(unsigned CallIndex) {
965       assert(CallIndex && "no call index in getCallFrameAndDepth");
966       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
967       // be null in this loop.
968       unsigned Depth = CallStackDepth;
969       CallStackFrame *Frame = CurrentCall;
970       while (Frame->Index > CallIndex) {
971         Frame = Frame->Caller;
972         --Depth;
973       }
974       if (Frame->Index == CallIndex)
975         return {Frame, Depth};
976       return {nullptr, 0};
977     }
978 
979     bool nextStep(const Stmt *S) {
980       if (!StepsLeft) {
981         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
982         return false;
983       }
984       --StepsLeft;
985       return true;
986     }
987 
988     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
989 
990     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
991       Optional<DynAlloc*> Result;
992       auto It = HeapAllocs.find(DA);
993       if (It != HeapAllocs.end())
994         Result = &It->second;
995       return Result;
996     }
997 
998     /// Information about a stack frame for std::allocator<T>::[de]allocate.
999     struct StdAllocatorCaller {
1000       unsigned FrameIndex;
1001       QualType ElemType;
1002       explicit operator bool() const { return FrameIndex != 0; };
1003     };
1004 
1005     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1006       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1007            Call = Call->Caller) {
1008         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1009         if (!MD)
1010           continue;
1011         const IdentifierInfo *FnII = MD->getIdentifier();
1012         if (!FnII || !FnII->isStr(FnName))
1013           continue;
1014 
1015         const auto *CTSD =
1016             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1017         if (!CTSD)
1018           continue;
1019 
1020         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1021         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1022         if (CTSD->isInStdNamespace() && ClassII &&
1023             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1024             TAL[0].getKind() == TemplateArgument::Type)
1025           return {Call->Index, TAL[0].getAsType()};
1026       }
1027 
1028       return {};
1029     }
1030 
1031     void performLifetimeExtension() {
1032       // Disable the cleanups for lifetime-extended temporaries.
1033       CleanupStack.erase(
1034           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1035                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1036           CleanupStack.end());
1037      }
1038 
1039     /// Throw away any remaining cleanups at the end of evaluation. If any
1040     /// cleanups would have had a side-effect, note that as an unmodeled
1041     /// side-effect and return false. Otherwise, return true.
1042     bool discardCleanups() {
1043       for (Cleanup &C : CleanupStack) {
1044         if (C.hasSideEffect() && !noteSideEffect()) {
1045           CleanupStack.clear();
1046           return false;
1047         }
1048       }
1049       CleanupStack.clear();
1050       return true;
1051     }
1052 
1053   private:
1054     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1055     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1056 
1057     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1058     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1059 
1060     void setFoldFailureDiagnostic(bool Flag) override {
1061       HasFoldFailureDiagnostic = Flag;
1062     }
1063 
1064     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1065 
1066     ASTContext &getCtx() const override { return Ctx; }
1067 
1068     // If we have a prior diagnostic, it will be noting that the expression
1069     // isn't a constant expression. This diagnostic is more important,
1070     // unless we require this evaluation to produce a constant expression.
1071     //
1072     // FIXME: We might want to show both diagnostics to the user in
1073     // EM_ConstantFold mode.
1074     bool hasPriorDiagnostic() override {
1075       if (!EvalStatus.Diag->empty()) {
1076         switch (EvalMode) {
1077         case EM_ConstantFold:
1078         case EM_IgnoreSideEffects:
1079           if (!HasFoldFailureDiagnostic)
1080             break;
1081           // We've already failed to fold something. Keep that diagnostic.
1082           LLVM_FALLTHROUGH;
1083         case EM_ConstantExpression:
1084         case EM_ConstantExpressionUnevaluated:
1085           setActiveDiagnostic(false);
1086           return true;
1087         }
1088       }
1089       return false;
1090     }
1091 
1092     unsigned getCallStackDepth() override { return CallStackDepth; }
1093 
1094   public:
1095     /// Should we continue evaluation after encountering a side-effect that we
1096     /// couldn't model?
1097     bool keepEvaluatingAfterSideEffect() {
1098       switch (EvalMode) {
1099       case EM_IgnoreSideEffects:
1100         return true;
1101 
1102       case EM_ConstantExpression:
1103       case EM_ConstantExpressionUnevaluated:
1104       case EM_ConstantFold:
1105         // By default, assume any side effect might be valid in some other
1106         // evaluation of this expression from a different context.
1107         return checkingPotentialConstantExpression() ||
1108                checkingForUndefinedBehavior();
1109       }
1110       llvm_unreachable("Missed EvalMode case");
1111     }
1112 
1113     /// Note that we have had a side-effect, and determine whether we should
1114     /// keep evaluating.
1115     bool noteSideEffect() {
1116       EvalStatus.HasSideEffects = true;
1117       return keepEvaluatingAfterSideEffect();
1118     }
1119 
1120     /// Should we continue evaluation after encountering undefined behavior?
1121     bool keepEvaluatingAfterUndefinedBehavior() {
1122       switch (EvalMode) {
1123       case EM_IgnoreSideEffects:
1124       case EM_ConstantFold:
1125         return true;
1126 
1127       case EM_ConstantExpression:
1128       case EM_ConstantExpressionUnevaluated:
1129         return checkingForUndefinedBehavior();
1130       }
1131       llvm_unreachable("Missed EvalMode case");
1132     }
1133 
1134     /// Note that we hit something that was technically undefined behavior, but
1135     /// that we can evaluate past it (such as signed overflow or floating-point
1136     /// division by zero.)
1137     bool noteUndefinedBehavior() override {
1138       EvalStatus.HasUndefinedBehavior = true;
1139       return keepEvaluatingAfterUndefinedBehavior();
1140     }
1141 
1142     /// Should we continue evaluation as much as possible after encountering a
1143     /// construct which can't be reduced to a value?
1144     bool keepEvaluatingAfterFailure() const override {
1145       if (!StepsLeft)
1146         return false;
1147 
1148       switch (EvalMode) {
1149       case EM_ConstantExpression:
1150       case EM_ConstantExpressionUnevaluated:
1151       case EM_ConstantFold:
1152       case EM_IgnoreSideEffects:
1153         return checkingPotentialConstantExpression() ||
1154                checkingForUndefinedBehavior();
1155       }
1156       llvm_unreachable("Missed EvalMode case");
1157     }
1158 
1159     /// Notes that we failed to evaluate an expression that other expressions
1160     /// directly depend on, and determine if we should keep evaluating. This
1161     /// should only be called if we actually intend to keep evaluating.
1162     ///
1163     /// Call noteSideEffect() instead if we may be able to ignore the value that
1164     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1165     ///
1166     /// (Foo(), 1)      // use noteSideEffect
1167     /// (Foo() || true) // use noteSideEffect
1168     /// Foo() + 1       // use noteFailure
1169     LLVM_NODISCARD bool noteFailure() {
1170       // Failure when evaluating some expression often means there is some
1171       // subexpression whose evaluation was skipped. Therefore, (because we
1172       // don't track whether we skipped an expression when unwinding after an
1173       // evaluation failure) every evaluation failure that bubbles up from a
1174       // subexpression implies that a side-effect has potentially happened. We
1175       // skip setting the HasSideEffects flag to true until we decide to
1176       // continue evaluating after that point, which happens here.
1177       bool KeepGoing = keepEvaluatingAfterFailure();
1178       EvalStatus.HasSideEffects |= KeepGoing;
1179       return KeepGoing;
1180     }
1181 
1182     class ArrayInitLoopIndex {
1183       EvalInfo &Info;
1184       uint64_t OuterIndex;
1185 
1186     public:
1187       ArrayInitLoopIndex(EvalInfo &Info)
1188           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1189         Info.ArrayInitIndex = 0;
1190       }
1191       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1192 
1193       operator uint64_t&() { return Info.ArrayInitIndex; }
1194     };
1195   };
1196 
1197   /// Object used to treat all foldable expressions as constant expressions.
1198   struct FoldConstant {
1199     EvalInfo &Info;
1200     bool Enabled;
1201     bool HadNoPriorDiags;
1202     EvalInfo::EvaluationMode OldMode;
1203 
1204     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1205       : Info(Info),
1206         Enabled(Enabled),
1207         HadNoPriorDiags(Info.EvalStatus.Diag &&
1208                         Info.EvalStatus.Diag->empty() &&
1209                         !Info.EvalStatus.HasSideEffects),
1210         OldMode(Info.EvalMode) {
1211       if (Enabled)
1212         Info.EvalMode = EvalInfo::EM_ConstantFold;
1213     }
1214     void keepDiagnostics() { Enabled = false; }
1215     ~FoldConstant() {
1216       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1217           !Info.EvalStatus.HasSideEffects)
1218         Info.EvalStatus.Diag->clear();
1219       Info.EvalMode = OldMode;
1220     }
1221   };
1222 
1223   /// RAII object used to set the current evaluation mode to ignore
1224   /// side-effects.
1225   struct IgnoreSideEffectsRAII {
1226     EvalInfo &Info;
1227     EvalInfo::EvaluationMode OldMode;
1228     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1229         : Info(Info), OldMode(Info.EvalMode) {
1230       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1231     }
1232 
1233     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1234   };
1235 
1236   /// RAII object used to optionally suppress diagnostics and side-effects from
1237   /// a speculative evaluation.
1238   class SpeculativeEvaluationRAII {
1239     EvalInfo *Info = nullptr;
1240     Expr::EvalStatus OldStatus;
1241     unsigned OldSpeculativeEvaluationDepth;
1242 
1243     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1244       Info = Other.Info;
1245       OldStatus = Other.OldStatus;
1246       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1247       Other.Info = nullptr;
1248     }
1249 
1250     void maybeRestoreState() {
1251       if (!Info)
1252         return;
1253 
1254       Info->EvalStatus = OldStatus;
1255       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1256     }
1257 
1258   public:
1259     SpeculativeEvaluationRAII() = default;
1260 
1261     SpeculativeEvaluationRAII(
1262         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1263         : Info(&Info), OldStatus(Info.EvalStatus),
1264           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1265       Info.EvalStatus.Diag = NewDiag;
1266       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1267     }
1268 
1269     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1270     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1271       moveFromAndCancel(std::move(Other));
1272     }
1273 
1274     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1275       maybeRestoreState();
1276       moveFromAndCancel(std::move(Other));
1277       return *this;
1278     }
1279 
1280     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1281   };
1282 
1283   /// RAII object wrapping a full-expression or block scope, and handling
1284   /// the ending of the lifetime of temporaries created within it.
1285   template<bool IsFullExpression>
1286   class ScopeRAII {
1287     EvalInfo &Info;
1288     unsigned OldStackSize;
1289   public:
1290     ScopeRAII(EvalInfo &Info)
1291         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1292       // Push a new temporary version. This is needed to distinguish between
1293       // temporaries created in different iterations of a loop.
1294       Info.CurrentCall->pushTempVersion();
1295     }
1296     bool destroy(bool RunDestructors = true) {
1297       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1298       OldStackSize = -1U;
1299       return OK;
1300     }
1301     ~ScopeRAII() {
1302       if (OldStackSize != -1U)
1303         destroy(false);
1304       // Body moved to a static method to encourage the compiler to inline away
1305       // instances of this class.
1306       Info.CurrentCall->popTempVersion();
1307     }
1308   private:
1309     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1310                         unsigned OldStackSize) {
1311       assert(OldStackSize <= Info.CleanupStack.size() &&
1312              "running cleanups out of order?");
1313 
1314       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1315       // for a full-expression scope.
1316       bool Success = true;
1317       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1318         if (!(IsFullExpression &&
1319               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1320           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1321             Success = false;
1322             break;
1323           }
1324         }
1325       }
1326 
1327       // Compact lifetime-extended cleanups.
1328       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1329       if (IsFullExpression)
1330         NewEnd =
1331             std::remove_if(NewEnd, Info.CleanupStack.end(),
1332                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1333       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1334       return Success;
1335     }
1336   };
1337   typedef ScopeRAII<false> BlockScopeRAII;
1338   typedef ScopeRAII<true> FullExpressionRAII;
1339 }
1340 
1341 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1342                                          CheckSubobjectKind CSK) {
1343   if (Invalid)
1344     return false;
1345   if (isOnePastTheEnd()) {
1346     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1347       << CSK;
1348     setInvalid();
1349     return false;
1350   }
1351   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1352   // must actually be at least one array element; even a VLA cannot have a
1353   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1354   return true;
1355 }
1356 
1357 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1358                                                                 const Expr *E) {
1359   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1360   // Do not set the designator as invalid: we can represent this situation,
1361   // and correct handling of __builtin_object_size requires us to do so.
1362 }
1363 
1364 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1365                                                     const Expr *E,
1366                                                     const APSInt &N) {
1367   // If we're complaining, we must be able to statically determine the size of
1368   // the most derived array.
1369   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1370     Info.CCEDiag(E, diag::note_constexpr_array_index)
1371       << N << /*array*/ 0
1372       << static_cast<unsigned>(getMostDerivedArraySize());
1373   else
1374     Info.CCEDiag(E, diag::note_constexpr_array_index)
1375       << N << /*non-array*/ 1;
1376   setInvalid();
1377 }
1378 
1379 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1380                                const FunctionDecl *Callee, const LValue *This,
1381                                APValue *Arguments)
1382     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1383       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1384   Info.CurrentCall = this;
1385   ++Info.CallStackDepth;
1386 }
1387 
1388 CallStackFrame::~CallStackFrame() {
1389   assert(Info.CurrentCall == this && "calls retired out of order");
1390   --Info.CallStackDepth;
1391   Info.CurrentCall = Caller;
1392 }
1393 
1394 static bool isRead(AccessKinds AK) {
1395   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1396 }
1397 
1398 static bool isModification(AccessKinds AK) {
1399   switch (AK) {
1400   case AK_Read:
1401   case AK_ReadObjectRepresentation:
1402   case AK_MemberCall:
1403   case AK_DynamicCast:
1404   case AK_TypeId:
1405     return false;
1406   case AK_Assign:
1407   case AK_Increment:
1408   case AK_Decrement:
1409   case AK_Construct:
1410   case AK_Destroy:
1411     return true;
1412   }
1413   llvm_unreachable("unknown access kind");
1414 }
1415 
1416 static bool isAnyAccess(AccessKinds AK) {
1417   return isRead(AK) || isModification(AK);
1418 }
1419 
1420 /// Is this an access per the C++ definition?
1421 static bool isFormalAccess(AccessKinds AK) {
1422   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1423 }
1424 
1425 /// Is this kind of axcess valid on an indeterminate object value?
1426 static bool isValidIndeterminateAccess(AccessKinds AK) {
1427   switch (AK) {
1428   case AK_Read:
1429   case AK_Increment:
1430   case AK_Decrement:
1431     // These need the object's value.
1432     return false;
1433 
1434   case AK_ReadObjectRepresentation:
1435   case AK_Assign:
1436   case AK_Construct:
1437   case AK_Destroy:
1438     // Construction and destruction don't need the value.
1439     return true;
1440 
1441   case AK_MemberCall:
1442   case AK_DynamicCast:
1443   case AK_TypeId:
1444     // These aren't really meaningful on scalars.
1445     return true;
1446   }
1447   llvm_unreachable("unknown access kind");
1448 }
1449 
1450 namespace {
1451   struct ComplexValue {
1452   private:
1453     bool IsInt;
1454 
1455   public:
1456     APSInt IntReal, IntImag;
1457     APFloat FloatReal, FloatImag;
1458 
1459     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1460 
1461     void makeComplexFloat() { IsInt = false; }
1462     bool isComplexFloat() const { return !IsInt; }
1463     APFloat &getComplexFloatReal() { return FloatReal; }
1464     APFloat &getComplexFloatImag() { return FloatImag; }
1465 
1466     void makeComplexInt() { IsInt = true; }
1467     bool isComplexInt() const { return IsInt; }
1468     APSInt &getComplexIntReal() { return IntReal; }
1469     APSInt &getComplexIntImag() { return IntImag; }
1470 
1471     void moveInto(APValue &v) const {
1472       if (isComplexFloat())
1473         v = APValue(FloatReal, FloatImag);
1474       else
1475         v = APValue(IntReal, IntImag);
1476     }
1477     void setFrom(const APValue &v) {
1478       assert(v.isComplexFloat() || v.isComplexInt());
1479       if (v.isComplexFloat()) {
1480         makeComplexFloat();
1481         FloatReal = v.getComplexFloatReal();
1482         FloatImag = v.getComplexFloatImag();
1483       } else {
1484         makeComplexInt();
1485         IntReal = v.getComplexIntReal();
1486         IntImag = v.getComplexIntImag();
1487       }
1488     }
1489   };
1490 
1491   struct LValue {
1492     APValue::LValueBase Base;
1493     CharUnits Offset;
1494     SubobjectDesignator Designator;
1495     bool IsNullPtr : 1;
1496     bool InvalidBase : 1;
1497 
1498     const APValue::LValueBase getLValueBase() const { return Base; }
1499     CharUnits &getLValueOffset() { return Offset; }
1500     const CharUnits &getLValueOffset() const { return Offset; }
1501     SubobjectDesignator &getLValueDesignator() { return Designator; }
1502     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1503     bool isNullPointer() const { return IsNullPtr;}
1504 
1505     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1506     unsigned getLValueVersion() const { return Base.getVersion(); }
1507 
1508     void moveInto(APValue &V) const {
1509       if (Designator.Invalid)
1510         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1511       else {
1512         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1513         V = APValue(Base, Offset, Designator.Entries,
1514                     Designator.IsOnePastTheEnd, IsNullPtr);
1515       }
1516     }
1517     void setFrom(ASTContext &Ctx, const APValue &V) {
1518       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1519       Base = V.getLValueBase();
1520       Offset = V.getLValueOffset();
1521       InvalidBase = false;
1522       Designator = SubobjectDesignator(Ctx, V);
1523       IsNullPtr = V.isNullPointer();
1524     }
1525 
1526     void set(APValue::LValueBase B, bool BInvalid = false) {
1527 #ifndef NDEBUG
1528       // We only allow a few types of invalid bases. Enforce that here.
1529       if (BInvalid) {
1530         const auto *E = B.get<const Expr *>();
1531         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1532                "Unexpected type of invalid base");
1533       }
1534 #endif
1535 
1536       Base = B;
1537       Offset = CharUnits::fromQuantity(0);
1538       InvalidBase = BInvalid;
1539       Designator = SubobjectDesignator(getType(B));
1540       IsNullPtr = false;
1541     }
1542 
1543     void setNull(ASTContext &Ctx, QualType PointerTy) {
1544       Base = (Expr *)nullptr;
1545       Offset =
1546           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1547       InvalidBase = false;
1548       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1549       IsNullPtr = true;
1550     }
1551 
1552     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1553       set(B, true);
1554     }
1555 
1556     std::string toString(ASTContext &Ctx, QualType T) const {
1557       APValue Printable;
1558       moveInto(Printable);
1559       return Printable.getAsString(Ctx, T);
1560     }
1561 
1562   private:
1563     // Check that this LValue is not based on a null pointer. If it is, produce
1564     // a diagnostic and mark the designator as invalid.
1565     template <typename GenDiagType>
1566     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1567       if (Designator.Invalid)
1568         return false;
1569       if (IsNullPtr) {
1570         GenDiag();
1571         Designator.setInvalid();
1572         return false;
1573       }
1574       return true;
1575     }
1576 
1577   public:
1578     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1579                           CheckSubobjectKind CSK) {
1580       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1581         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1582       });
1583     }
1584 
1585     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1586                                        AccessKinds AK) {
1587       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1588         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1589       });
1590     }
1591 
1592     // Check this LValue refers to an object. If not, set the designator to be
1593     // invalid and emit a diagnostic.
1594     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1595       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1596              Designator.checkSubobject(Info, E, CSK);
1597     }
1598 
1599     void addDecl(EvalInfo &Info, const Expr *E,
1600                  const Decl *D, bool Virtual = false) {
1601       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1602         Designator.addDeclUnchecked(D, Virtual);
1603     }
1604     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1605       if (!Designator.Entries.empty()) {
1606         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1607         Designator.setInvalid();
1608         return;
1609       }
1610       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1611         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1612         Designator.FirstEntryIsAnUnsizedArray = true;
1613         Designator.addUnsizedArrayUnchecked(ElemTy);
1614       }
1615     }
1616     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1617       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1618         Designator.addArrayUnchecked(CAT);
1619     }
1620     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1621       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1622         Designator.addComplexUnchecked(EltTy, Imag);
1623     }
1624     void clearIsNullPointer() {
1625       IsNullPtr = false;
1626     }
1627     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1628                               const APSInt &Index, CharUnits ElementSize) {
1629       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1630       // but we're not required to diagnose it and it's valid in C++.)
1631       if (!Index)
1632         return;
1633 
1634       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1635       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1636       // offsets.
1637       uint64_t Offset64 = Offset.getQuantity();
1638       uint64_t ElemSize64 = ElementSize.getQuantity();
1639       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1640       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1641 
1642       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1643         Designator.adjustIndex(Info, E, Index);
1644       clearIsNullPointer();
1645     }
1646     void adjustOffset(CharUnits N) {
1647       Offset += N;
1648       if (N.getQuantity())
1649         clearIsNullPointer();
1650     }
1651   };
1652 
1653   struct MemberPtr {
1654     MemberPtr() {}
1655     explicit MemberPtr(const ValueDecl *Decl) :
1656       DeclAndIsDerivedMember(Decl, false), Path() {}
1657 
1658     /// The member or (direct or indirect) field referred to by this member
1659     /// pointer, or 0 if this is a null member pointer.
1660     const ValueDecl *getDecl() const {
1661       return DeclAndIsDerivedMember.getPointer();
1662     }
1663     /// Is this actually a member of some type derived from the relevant class?
1664     bool isDerivedMember() const {
1665       return DeclAndIsDerivedMember.getInt();
1666     }
1667     /// Get the class which the declaration actually lives in.
1668     const CXXRecordDecl *getContainingRecord() const {
1669       return cast<CXXRecordDecl>(
1670           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1671     }
1672 
1673     void moveInto(APValue &V) const {
1674       V = APValue(getDecl(), isDerivedMember(), Path);
1675     }
1676     void setFrom(const APValue &V) {
1677       assert(V.isMemberPointer());
1678       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1679       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1680       Path.clear();
1681       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1682       Path.insert(Path.end(), P.begin(), P.end());
1683     }
1684 
1685     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1686     /// whether the member is a member of some class derived from the class type
1687     /// of the member pointer.
1688     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1689     /// Path - The path of base/derived classes from the member declaration's
1690     /// class (exclusive) to the class type of the member pointer (inclusive).
1691     SmallVector<const CXXRecordDecl*, 4> Path;
1692 
1693     /// Perform a cast towards the class of the Decl (either up or down the
1694     /// hierarchy).
1695     bool castBack(const CXXRecordDecl *Class) {
1696       assert(!Path.empty());
1697       const CXXRecordDecl *Expected;
1698       if (Path.size() >= 2)
1699         Expected = Path[Path.size() - 2];
1700       else
1701         Expected = getContainingRecord();
1702       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1703         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1704         // if B does not contain the original member and is not a base or
1705         // derived class of the class containing the original member, the result
1706         // of the cast is undefined.
1707         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1708         // (D::*). We consider that to be a language defect.
1709         return false;
1710       }
1711       Path.pop_back();
1712       return true;
1713     }
1714     /// Perform a base-to-derived member pointer cast.
1715     bool castToDerived(const CXXRecordDecl *Derived) {
1716       if (!getDecl())
1717         return true;
1718       if (!isDerivedMember()) {
1719         Path.push_back(Derived);
1720         return true;
1721       }
1722       if (!castBack(Derived))
1723         return false;
1724       if (Path.empty())
1725         DeclAndIsDerivedMember.setInt(false);
1726       return true;
1727     }
1728     /// Perform a derived-to-base member pointer cast.
1729     bool castToBase(const CXXRecordDecl *Base) {
1730       if (!getDecl())
1731         return true;
1732       if (Path.empty())
1733         DeclAndIsDerivedMember.setInt(true);
1734       if (isDerivedMember()) {
1735         Path.push_back(Base);
1736         return true;
1737       }
1738       return castBack(Base);
1739     }
1740   };
1741 
1742   /// Compare two member pointers, which are assumed to be of the same type.
1743   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1744     if (!LHS.getDecl() || !RHS.getDecl())
1745       return !LHS.getDecl() && !RHS.getDecl();
1746     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1747       return false;
1748     return LHS.Path == RHS.Path;
1749   }
1750 }
1751 
1752 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1753 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1754                             const LValue &This, const Expr *E,
1755                             bool AllowNonLiteralTypes = false);
1756 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1757                            bool InvalidBaseOK = false);
1758 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1759                             bool InvalidBaseOK = false);
1760 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1761                                   EvalInfo &Info);
1762 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1763 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1764 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1765                                     EvalInfo &Info);
1766 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1767 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1768 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1769                            EvalInfo &Info);
1770 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1771 
1772 /// Evaluate an integer or fixed point expression into an APResult.
1773 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1774                                         EvalInfo &Info);
1775 
1776 /// Evaluate only a fixed point expression into an APResult.
1777 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1778                                EvalInfo &Info);
1779 
1780 //===----------------------------------------------------------------------===//
1781 // Misc utilities
1782 //===----------------------------------------------------------------------===//
1783 
1784 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1785 /// preserving its value (by extending by up to one bit as needed).
1786 static void negateAsSigned(APSInt &Int) {
1787   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1788     Int = Int.extend(Int.getBitWidth() + 1);
1789     Int.setIsSigned(true);
1790   }
1791   Int = -Int;
1792 }
1793 
1794 template<typename KeyT>
1795 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1796                                          bool IsLifetimeExtended, LValue &LV) {
1797   unsigned Version = getTempVersion();
1798   APValue::LValueBase Base(Key, Index, Version);
1799   LV.set(Base);
1800   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1801   assert(Result.isAbsent() && "temporary created multiple times");
1802 
1803   // If we're creating a temporary immediately in the operand of a speculative
1804   // evaluation, don't register a cleanup to be run outside the speculative
1805   // evaluation context, since we won't actually be able to initialize this
1806   // object.
1807   if (Index <= Info.SpeculativeEvaluationDepth) {
1808     if (T.isDestructedType())
1809       Info.noteSideEffect();
1810   } else {
1811     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1812   }
1813   return Result;
1814 }
1815 
1816 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1817   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1818     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1819     return nullptr;
1820   }
1821 
1822   DynamicAllocLValue DA(NumHeapAllocs++);
1823   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1824   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1825                                    std::forward_as_tuple(DA), std::tuple<>());
1826   assert(Result.second && "reused a heap alloc index?");
1827   Result.first->second.AllocExpr = E;
1828   return &Result.first->second.Value;
1829 }
1830 
1831 /// Produce a string describing the given constexpr call.
1832 void CallStackFrame::describe(raw_ostream &Out) {
1833   unsigned ArgIndex = 0;
1834   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1835                       !isa<CXXConstructorDecl>(Callee) &&
1836                       cast<CXXMethodDecl>(Callee)->isInstance();
1837 
1838   if (!IsMemberCall)
1839     Out << *Callee << '(';
1840 
1841   if (This && IsMemberCall) {
1842     APValue Val;
1843     This->moveInto(Val);
1844     Val.printPretty(Out, Info.Ctx,
1845                     This->Designator.MostDerivedType);
1846     // FIXME: Add parens around Val if needed.
1847     Out << "->" << *Callee << '(';
1848     IsMemberCall = false;
1849   }
1850 
1851   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1852        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1853     if (ArgIndex > (unsigned)IsMemberCall)
1854       Out << ", ";
1855 
1856     const ParmVarDecl *Param = *I;
1857     const APValue &Arg = Arguments[ArgIndex];
1858     Arg.printPretty(Out, Info.Ctx, Param->getType());
1859 
1860     if (ArgIndex == 0 && IsMemberCall)
1861       Out << "->" << *Callee << '(';
1862   }
1863 
1864   Out << ')';
1865 }
1866 
1867 /// Evaluate an expression to see if it had side-effects, and discard its
1868 /// result.
1869 /// \return \c true if the caller should keep evaluating.
1870 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1871   APValue Scratch;
1872   if (!Evaluate(Scratch, Info, E))
1873     // We don't need the value, but we might have skipped a side effect here.
1874     return Info.noteSideEffect();
1875   return true;
1876 }
1877 
1878 /// Should this call expression be treated as a string literal?
1879 static bool IsStringLiteralCall(const CallExpr *E) {
1880   unsigned Builtin = E->getBuiltinCallee();
1881   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1882           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1883 }
1884 
1885 static bool IsGlobalLValue(APValue::LValueBase B) {
1886   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1887   // constant expression of pointer type that evaluates to...
1888 
1889   // ... a null pointer value, or a prvalue core constant expression of type
1890   // std::nullptr_t.
1891   if (!B) return true;
1892 
1893   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1894     // ... the address of an object with static storage duration,
1895     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1896       return VD->hasGlobalStorage();
1897     // ... the address of a function,
1898     // ... the address of a GUID [MS extension],
1899     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1900   }
1901 
1902   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1903     return true;
1904 
1905   const Expr *E = B.get<const Expr*>();
1906   switch (E->getStmtClass()) {
1907   default:
1908     return false;
1909   case Expr::CompoundLiteralExprClass: {
1910     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1911     return CLE->isFileScope() && CLE->isLValue();
1912   }
1913   case Expr::MaterializeTemporaryExprClass:
1914     // A materialized temporary might have been lifetime-extended to static
1915     // storage duration.
1916     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1917   // A string literal has static storage duration.
1918   case Expr::StringLiteralClass:
1919   case Expr::PredefinedExprClass:
1920   case Expr::ObjCStringLiteralClass:
1921   case Expr::ObjCEncodeExprClass:
1922     return true;
1923   case Expr::ObjCBoxedExprClass:
1924     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1925   case Expr::CallExprClass:
1926     return IsStringLiteralCall(cast<CallExpr>(E));
1927   // For GCC compatibility, &&label has static storage duration.
1928   case Expr::AddrLabelExprClass:
1929     return true;
1930   // A Block literal expression may be used as the initialization value for
1931   // Block variables at global or local static scope.
1932   case Expr::BlockExprClass:
1933     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1934   case Expr::ImplicitValueInitExprClass:
1935     // FIXME:
1936     // We can never form an lvalue with an implicit value initialization as its
1937     // base through expression evaluation, so these only appear in one case: the
1938     // implicit variable declaration we invent when checking whether a constexpr
1939     // constructor can produce a constant expression. We must assume that such
1940     // an expression might be a global lvalue.
1941     return true;
1942   }
1943 }
1944 
1945 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1946   return LVal.Base.dyn_cast<const ValueDecl*>();
1947 }
1948 
1949 static bool IsLiteralLValue(const LValue &Value) {
1950   if (Value.getLValueCallIndex())
1951     return false;
1952   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1953   return E && !isa<MaterializeTemporaryExpr>(E);
1954 }
1955 
1956 static bool IsWeakLValue(const LValue &Value) {
1957   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1958   return Decl && Decl->isWeak();
1959 }
1960 
1961 static bool isZeroSized(const LValue &Value) {
1962   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1963   if (Decl && isa<VarDecl>(Decl)) {
1964     QualType Ty = Decl->getType();
1965     if (Ty->isArrayType())
1966       return Ty->isIncompleteType() ||
1967              Decl->getASTContext().getTypeSize(Ty) == 0;
1968   }
1969   return false;
1970 }
1971 
1972 static bool HasSameBase(const LValue &A, const LValue &B) {
1973   if (!A.getLValueBase())
1974     return !B.getLValueBase();
1975   if (!B.getLValueBase())
1976     return false;
1977 
1978   if (A.getLValueBase().getOpaqueValue() !=
1979       B.getLValueBase().getOpaqueValue()) {
1980     const Decl *ADecl = GetLValueBaseDecl(A);
1981     if (!ADecl)
1982       return false;
1983     const Decl *BDecl = GetLValueBaseDecl(B);
1984     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1985       return false;
1986   }
1987 
1988   return IsGlobalLValue(A.getLValueBase()) ||
1989          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1990           A.getLValueVersion() == B.getLValueVersion());
1991 }
1992 
1993 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1994   assert(Base && "no location for a null lvalue");
1995   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1996   if (VD)
1997     Info.Note(VD->getLocation(), diag::note_declared_at);
1998   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1999     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2000   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2001     // FIXME: Produce a note for dangling pointers too.
2002     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2003       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2004                 diag::note_constexpr_dynamic_alloc_here);
2005   }
2006   // We have no information to show for a typeid(T) object.
2007 }
2008 
2009 enum class CheckEvaluationResultKind {
2010   ConstantExpression,
2011   FullyInitialized,
2012 };
2013 
2014 /// Materialized temporaries that we've already checked to determine if they're
2015 /// initializsed by a constant expression.
2016 using CheckedTemporaries =
2017     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2018 
2019 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2020                                   EvalInfo &Info, SourceLocation DiagLoc,
2021                                   QualType Type, const APValue &Value,
2022                                   Expr::ConstExprUsage Usage,
2023                                   SourceLocation SubobjectLoc,
2024                                   CheckedTemporaries &CheckedTemps);
2025 
2026 /// Check that this reference or pointer core constant expression is a valid
2027 /// value for an address or reference constant expression. Return true if we
2028 /// can fold this expression, whether or not it's a constant expression.
2029 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2030                                           QualType Type, const LValue &LVal,
2031                                           Expr::ConstExprUsage Usage,
2032                                           CheckedTemporaries &CheckedTemps) {
2033   bool IsReferenceType = Type->isReferenceType();
2034 
2035   APValue::LValueBase Base = LVal.getLValueBase();
2036   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2037 
2038   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2039     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2040       if (FD->isConsteval()) {
2041         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2042             << !Type->isAnyPointerType();
2043         Info.Note(FD->getLocation(), diag::note_declared_at);
2044         return false;
2045       }
2046     }
2047   }
2048 
2049   // Check that the object is a global. Note that the fake 'this' object we
2050   // manufacture when checking potential constant expressions is conservatively
2051   // assumed to be global here.
2052   if (!IsGlobalLValue(Base)) {
2053     if (Info.getLangOpts().CPlusPlus11) {
2054       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2055       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2056         << IsReferenceType << !Designator.Entries.empty()
2057         << !!VD << VD;
2058       NoteLValueLocation(Info, Base);
2059     } else {
2060       Info.FFDiag(Loc);
2061     }
2062     // Don't allow references to temporaries to escape.
2063     return false;
2064   }
2065   assert((Info.checkingPotentialConstantExpression() ||
2066           LVal.getLValueCallIndex() == 0) &&
2067          "have call index for global lvalue");
2068 
2069   if (Base.is<DynamicAllocLValue>()) {
2070     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2071         << IsReferenceType << !Designator.Entries.empty();
2072     NoteLValueLocation(Info, Base);
2073     return false;
2074   }
2075 
2076   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2077     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2078       // Check if this is a thread-local variable.
2079       if (Var->getTLSKind())
2080         // FIXME: Diagnostic!
2081         return false;
2082 
2083       // A dllimport variable never acts like a constant.
2084       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2085         // FIXME: Diagnostic!
2086         return false;
2087     }
2088     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2089       // __declspec(dllimport) must be handled very carefully:
2090       // We must never initialize an expression with the thunk in C++.
2091       // Doing otherwise would allow the same id-expression to yield
2092       // different addresses for the same function in different translation
2093       // units.  However, this means that we must dynamically initialize the
2094       // expression with the contents of the import address table at runtime.
2095       //
2096       // The C language has no notion of ODR; furthermore, it has no notion of
2097       // dynamic initialization.  This means that we are permitted to
2098       // perform initialization with the address of the thunk.
2099       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2100           FD->hasAttr<DLLImportAttr>())
2101         // FIXME: Diagnostic!
2102         return false;
2103     }
2104   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2105                  Base.dyn_cast<const Expr *>())) {
2106     if (CheckedTemps.insert(MTE).second) {
2107       QualType TempType = getType(Base);
2108       if (TempType.isDestructedType()) {
2109         Info.FFDiag(MTE->getExprLoc(),
2110                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2111             << TempType;
2112         return false;
2113       }
2114 
2115       APValue *V = MTE->getOrCreateValue(false);
2116       assert(V && "evasluation result refers to uninitialised temporary");
2117       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2118                                  Info, MTE->getExprLoc(), TempType, *V,
2119                                  Usage, SourceLocation(), CheckedTemps))
2120         return false;
2121     }
2122   }
2123 
2124   // Allow address constant expressions to be past-the-end pointers. This is
2125   // an extension: the standard requires them to point to an object.
2126   if (!IsReferenceType)
2127     return true;
2128 
2129   // A reference constant expression must refer to an object.
2130   if (!Base) {
2131     // FIXME: diagnostic
2132     Info.CCEDiag(Loc);
2133     return true;
2134   }
2135 
2136   // Does this refer one past the end of some object?
2137   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2138     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2139     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2140       << !Designator.Entries.empty() << !!VD << VD;
2141     NoteLValueLocation(Info, Base);
2142   }
2143 
2144   return true;
2145 }
2146 
2147 /// Member pointers are constant expressions unless they point to a
2148 /// non-virtual dllimport member function.
2149 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2150                                                  SourceLocation Loc,
2151                                                  QualType Type,
2152                                                  const APValue &Value,
2153                                                  Expr::ConstExprUsage Usage) {
2154   const ValueDecl *Member = Value.getMemberPointerDecl();
2155   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2156   if (!FD)
2157     return true;
2158   if (FD->isConsteval()) {
2159     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2160     Info.Note(FD->getLocation(), diag::note_declared_at);
2161     return false;
2162   }
2163   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2164          !FD->hasAttr<DLLImportAttr>();
2165 }
2166 
2167 /// Check that this core constant expression is of literal type, and if not,
2168 /// produce an appropriate diagnostic.
2169 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2170                              const LValue *This = nullptr) {
2171   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2172     return true;
2173 
2174   // C++1y: A constant initializer for an object o [...] may also invoke
2175   // constexpr constructors for o and its subobjects even if those objects
2176   // are of non-literal class types.
2177   //
2178   // C++11 missed this detail for aggregates, so classes like this:
2179   //   struct foo_t { union { int i; volatile int j; } u; };
2180   // are not (obviously) initializable like so:
2181   //   __attribute__((__require_constant_initialization__))
2182   //   static const foo_t x = {{0}};
2183   // because "i" is a subobject with non-literal initialization (due to the
2184   // volatile member of the union). See:
2185   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2186   // Therefore, we use the C++1y behavior.
2187   if (This && Info.EvaluatingDecl == This->getLValueBase())
2188     return true;
2189 
2190   // Prvalue constant expressions must be of literal types.
2191   if (Info.getLangOpts().CPlusPlus11)
2192     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2193       << E->getType();
2194   else
2195     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2196   return false;
2197 }
2198 
2199 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2200                                   EvalInfo &Info, SourceLocation DiagLoc,
2201                                   QualType Type, const APValue &Value,
2202                                   Expr::ConstExprUsage Usage,
2203                                   SourceLocation SubobjectLoc,
2204                                   CheckedTemporaries &CheckedTemps) {
2205   if (!Value.hasValue()) {
2206     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2207       << true << Type;
2208     if (SubobjectLoc.isValid())
2209       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2210     return false;
2211   }
2212 
2213   // We allow _Atomic(T) to be initialized from anything that T can be
2214   // initialized from.
2215   if (const AtomicType *AT = Type->getAs<AtomicType>())
2216     Type = AT->getValueType();
2217 
2218   // Core issue 1454: For a literal constant expression of array or class type,
2219   // each subobject of its value shall have been initialized by a constant
2220   // expression.
2221   if (Value.isArray()) {
2222     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2223     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2224       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2225                                  Value.getArrayInitializedElt(I), Usage,
2226                                  SubobjectLoc, CheckedTemps))
2227         return false;
2228     }
2229     if (!Value.hasArrayFiller())
2230       return true;
2231     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2232                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2233                                  CheckedTemps);
2234   }
2235   if (Value.isUnion() && Value.getUnionField()) {
2236     return CheckEvaluationResult(
2237         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2238         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2239         CheckedTemps);
2240   }
2241   if (Value.isStruct()) {
2242     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2243     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2244       unsigned BaseIndex = 0;
2245       for (const CXXBaseSpecifier &BS : CD->bases()) {
2246         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2247                                    Value.getStructBase(BaseIndex), Usage,
2248                                    BS.getBeginLoc(), CheckedTemps))
2249           return false;
2250         ++BaseIndex;
2251       }
2252     }
2253     for (const auto *I : RD->fields()) {
2254       if (I->isUnnamedBitfield())
2255         continue;
2256 
2257       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2258                                  Value.getStructField(I->getFieldIndex()),
2259                                  Usage, I->getLocation(), CheckedTemps))
2260         return false;
2261     }
2262   }
2263 
2264   if (Value.isLValue() &&
2265       CERK == CheckEvaluationResultKind::ConstantExpression) {
2266     LValue LVal;
2267     LVal.setFrom(Info.Ctx, Value);
2268     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2269                                          CheckedTemps);
2270   }
2271 
2272   if (Value.isMemberPointer() &&
2273       CERK == CheckEvaluationResultKind::ConstantExpression)
2274     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2275 
2276   // Everything else is fine.
2277   return true;
2278 }
2279 
2280 /// Check that this core constant expression value is a valid value for a
2281 /// constant expression. If not, report an appropriate diagnostic. Does not
2282 /// check that the expression is of literal type.
2283 static bool
2284 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2285                         const APValue &Value,
2286                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2287   CheckedTemporaries CheckedTemps;
2288   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2289                                Info, DiagLoc, Type, Value, Usage,
2290                                SourceLocation(), CheckedTemps);
2291 }
2292 
2293 /// Check that this evaluated value is fully-initialized and can be loaded by
2294 /// an lvalue-to-rvalue conversion.
2295 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2296                                   QualType Type, const APValue &Value) {
2297   CheckedTemporaries CheckedTemps;
2298   return CheckEvaluationResult(
2299       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2300       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2301 }
2302 
2303 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2304 /// "the allocated storage is deallocated within the evaluation".
2305 static bool CheckMemoryLeaks(EvalInfo &Info) {
2306   if (!Info.HeapAllocs.empty()) {
2307     // We can still fold to a constant despite a compile-time memory leak,
2308     // so long as the heap allocation isn't referenced in the result (we check
2309     // that in CheckConstantExpression).
2310     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2311                  diag::note_constexpr_memory_leak)
2312         << unsigned(Info.HeapAllocs.size() - 1);
2313   }
2314   return true;
2315 }
2316 
2317 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2318   // A null base expression indicates a null pointer.  These are always
2319   // evaluatable, and they are false unless the offset is zero.
2320   if (!Value.getLValueBase()) {
2321     Result = !Value.getLValueOffset().isZero();
2322     return true;
2323   }
2324 
2325   // We have a non-null base.  These are generally known to be true, but if it's
2326   // a weak declaration it can be null at runtime.
2327   Result = true;
2328   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2329   return !Decl || !Decl->isWeak();
2330 }
2331 
2332 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2333   switch (Val.getKind()) {
2334   case APValue::None:
2335   case APValue::Indeterminate:
2336     return false;
2337   case APValue::Int:
2338     Result = Val.getInt().getBoolValue();
2339     return true;
2340   case APValue::FixedPoint:
2341     Result = Val.getFixedPoint().getBoolValue();
2342     return true;
2343   case APValue::Float:
2344     Result = !Val.getFloat().isZero();
2345     return true;
2346   case APValue::ComplexInt:
2347     Result = Val.getComplexIntReal().getBoolValue() ||
2348              Val.getComplexIntImag().getBoolValue();
2349     return true;
2350   case APValue::ComplexFloat:
2351     Result = !Val.getComplexFloatReal().isZero() ||
2352              !Val.getComplexFloatImag().isZero();
2353     return true;
2354   case APValue::LValue:
2355     return EvalPointerValueAsBool(Val, Result);
2356   case APValue::MemberPointer:
2357     Result = Val.getMemberPointerDecl();
2358     return true;
2359   case APValue::Vector:
2360   case APValue::Array:
2361   case APValue::Struct:
2362   case APValue::Union:
2363   case APValue::AddrLabelDiff:
2364     return false;
2365   }
2366 
2367   llvm_unreachable("unknown APValue kind");
2368 }
2369 
2370 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2371                                        EvalInfo &Info) {
2372   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2373   APValue Val;
2374   if (!Evaluate(Val, Info, E))
2375     return false;
2376   return HandleConversionToBool(Val, Result);
2377 }
2378 
2379 template<typename T>
2380 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2381                            const T &SrcValue, QualType DestType) {
2382   Info.CCEDiag(E, diag::note_constexpr_overflow)
2383     << SrcValue << DestType;
2384   return Info.noteUndefinedBehavior();
2385 }
2386 
2387 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2388                                  QualType SrcType, const APFloat &Value,
2389                                  QualType DestType, APSInt &Result) {
2390   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2391   // Determine whether we are converting to unsigned or signed.
2392   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2393 
2394   Result = APSInt(DestWidth, !DestSigned);
2395   bool ignored;
2396   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2397       & APFloat::opInvalidOp)
2398     return HandleOverflow(Info, E, Value, DestType);
2399   return true;
2400 }
2401 
2402 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2403                                    QualType SrcType, QualType DestType,
2404                                    APFloat &Result) {
2405   APFloat Value = Result;
2406   bool ignored;
2407   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2408                  APFloat::rmNearestTiesToEven, &ignored);
2409   return true;
2410 }
2411 
2412 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2413                                  QualType DestType, QualType SrcType,
2414                                  const APSInt &Value) {
2415   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2416   // Figure out if this is a truncate, extend or noop cast.
2417   // If the input is signed, do a sign extend, noop, or truncate.
2418   APSInt Result = Value.extOrTrunc(DestWidth);
2419   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2420   if (DestType->isBooleanType())
2421     Result = Value.getBoolValue();
2422   return Result;
2423 }
2424 
2425 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2426                                  QualType SrcType, const APSInt &Value,
2427                                  QualType DestType, APFloat &Result) {
2428   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2429   Result.convertFromAPInt(Value, Value.isSigned(),
2430                           APFloat::rmNearestTiesToEven);
2431   return true;
2432 }
2433 
2434 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2435                                   APValue &Value, const FieldDecl *FD) {
2436   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2437 
2438   if (!Value.isInt()) {
2439     // Trying to store a pointer-cast-to-integer into a bitfield.
2440     // FIXME: In this case, we should provide the diagnostic for casting
2441     // a pointer to an integer.
2442     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2443     Info.FFDiag(E);
2444     return false;
2445   }
2446 
2447   APSInt &Int = Value.getInt();
2448   unsigned OldBitWidth = Int.getBitWidth();
2449   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2450   if (NewBitWidth < OldBitWidth)
2451     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2452   return true;
2453 }
2454 
2455 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2456                                   llvm::APInt &Res) {
2457   APValue SVal;
2458   if (!Evaluate(SVal, Info, E))
2459     return false;
2460   if (SVal.isInt()) {
2461     Res = SVal.getInt();
2462     return true;
2463   }
2464   if (SVal.isFloat()) {
2465     Res = SVal.getFloat().bitcastToAPInt();
2466     return true;
2467   }
2468   if (SVal.isVector()) {
2469     QualType VecTy = E->getType();
2470     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2471     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2472     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2473     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2474     Res = llvm::APInt::getNullValue(VecSize);
2475     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2476       APValue &Elt = SVal.getVectorElt(i);
2477       llvm::APInt EltAsInt;
2478       if (Elt.isInt()) {
2479         EltAsInt = Elt.getInt();
2480       } else if (Elt.isFloat()) {
2481         EltAsInt = Elt.getFloat().bitcastToAPInt();
2482       } else {
2483         // Don't try to handle vectors of anything other than int or float
2484         // (not sure if it's possible to hit this case).
2485         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2486         return false;
2487       }
2488       unsigned BaseEltSize = EltAsInt.getBitWidth();
2489       if (BigEndian)
2490         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2491       else
2492         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2493     }
2494     return true;
2495   }
2496   // Give up if the input isn't an int, float, or vector.  For example, we
2497   // reject "(v4i16)(intptr_t)&a".
2498   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2499   return false;
2500 }
2501 
2502 /// Perform the given integer operation, which is known to need at most BitWidth
2503 /// bits, and check for overflow in the original type (if that type was not an
2504 /// unsigned type).
2505 template<typename Operation>
2506 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2507                                  const APSInt &LHS, const APSInt &RHS,
2508                                  unsigned BitWidth, Operation Op,
2509                                  APSInt &Result) {
2510   if (LHS.isUnsigned()) {
2511     Result = Op(LHS, RHS);
2512     return true;
2513   }
2514 
2515   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2516   Result = Value.trunc(LHS.getBitWidth());
2517   if (Result.extend(BitWidth) != Value) {
2518     if (Info.checkingForUndefinedBehavior())
2519       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2520                                        diag::warn_integer_constant_overflow)
2521           << Result.toString(10) << E->getType();
2522     else
2523       return HandleOverflow(Info, E, Value, E->getType());
2524   }
2525   return true;
2526 }
2527 
2528 /// Perform the given binary integer operation.
2529 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2530                               BinaryOperatorKind Opcode, APSInt RHS,
2531                               APSInt &Result) {
2532   switch (Opcode) {
2533   default:
2534     Info.FFDiag(E);
2535     return false;
2536   case BO_Mul:
2537     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2538                                 std::multiplies<APSInt>(), Result);
2539   case BO_Add:
2540     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2541                                 std::plus<APSInt>(), Result);
2542   case BO_Sub:
2543     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2544                                 std::minus<APSInt>(), Result);
2545   case BO_And: Result = LHS & RHS; return true;
2546   case BO_Xor: Result = LHS ^ RHS; return true;
2547   case BO_Or:  Result = LHS | RHS; return true;
2548   case BO_Div:
2549   case BO_Rem:
2550     if (RHS == 0) {
2551       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2552       return false;
2553     }
2554     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2555     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2556     // this operation and gives the two's complement result.
2557     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2558         LHS.isSigned() && LHS.isMinSignedValue())
2559       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2560                             E->getType());
2561     return true;
2562   case BO_Shl: {
2563     if (Info.getLangOpts().OpenCL)
2564       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2565       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2566                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2567                     RHS.isUnsigned());
2568     else if (RHS.isSigned() && RHS.isNegative()) {
2569       // During constant-folding, a negative shift is an opposite shift. Such
2570       // a shift is not a constant expression.
2571       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2572       RHS = -RHS;
2573       goto shift_right;
2574     }
2575   shift_left:
2576     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2577     // the shifted type.
2578     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2579     if (SA != RHS) {
2580       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2581         << RHS << E->getType() << LHS.getBitWidth();
2582     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2583       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2584       // operand, and must not overflow the corresponding unsigned type.
2585       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2586       // E1 x 2^E2 module 2^N.
2587       if (LHS.isNegative())
2588         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2589       else if (LHS.countLeadingZeros() < SA)
2590         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2591     }
2592     Result = LHS << SA;
2593     return true;
2594   }
2595   case BO_Shr: {
2596     if (Info.getLangOpts().OpenCL)
2597       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2598       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2599                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2600                     RHS.isUnsigned());
2601     else if (RHS.isSigned() && RHS.isNegative()) {
2602       // During constant-folding, a negative shift is an opposite shift. Such a
2603       // shift is not a constant expression.
2604       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2605       RHS = -RHS;
2606       goto shift_left;
2607     }
2608   shift_right:
2609     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2610     // shifted type.
2611     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2612     if (SA != RHS)
2613       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2614         << RHS << E->getType() << LHS.getBitWidth();
2615     Result = LHS >> SA;
2616     return true;
2617   }
2618 
2619   case BO_LT: Result = LHS < RHS; return true;
2620   case BO_GT: Result = LHS > RHS; return true;
2621   case BO_LE: Result = LHS <= RHS; return true;
2622   case BO_GE: Result = LHS >= RHS; return true;
2623   case BO_EQ: Result = LHS == RHS; return true;
2624   case BO_NE: Result = LHS != RHS; return true;
2625   case BO_Cmp:
2626     llvm_unreachable("BO_Cmp should be handled elsewhere");
2627   }
2628 }
2629 
2630 /// Perform the given binary floating-point operation, in-place, on LHS.
2631 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2632                                   APFloat &LHS, BinaryOperatorKind Opcode,
2633                                   const APFloat &RHS) {
2634   switch (Opcode) {
2635   default:
2636     Info.FFDiag(E);
2637     return false;
2638   case BO_Mul:
2639     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2640     break;
2641   case BO_Add:
2642     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2643     break;
2644   case BO_Sub:
2645     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2646     break;
2647   case BO_Div:
2648     // [expr.mul]p4:
2649     //   If the second operand of / or % is zero the behavior is undefined.
2650     if (RHS.isZero())
2651       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2652     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2653     break;
2654   }
2655 
2656   // [expr.pre]p4:
2657   //   If during the evaluation of an expression, the result is not
2658   //   mathematically defined [...], the behavior is undefined.
2659   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2660   if (LHS.isNaN()) {
2661     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2662     return Info.noteUndefinedBehavior();
2663   }
2664   return true;
2665 }
2666 
2667 static bool handleLogicalOpForVector(const APInt &LHSValue,
2668                                      BinaryOperatorKind Opcode,
2669                                      const APInt &RHSValue, APInt &Result) {
2670   bool LHS = (LHSValue != 0);
2671   bool RHS = (RHSValue != 0);
2672 
2673   if (Opcode == BO_LAnd)
2674     Result = LHS && RHS;
2675   else
2676     Result = LHS || RHS;
2677   return true;
2678 }
2679 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2680                                      BinaryOperatorKind Opcode,
2681                                      const APFloat &RHSValue, APInt &Result) {
2682   bool LHS = !LHSValue.isZero();
2683   bool RHS = !RHSValue.isZero();
2684 
2685   if (Opcode == BO_LAnd)
2686     Result = LHS && RHS;
2687   else
2688     Result = LHS || RHS;
2689   return true;
2690 }
2691 
2692 static bool handleLogicalOpForVector(const APValue &LHSValue,
2693                                      BinaryOperatorKind Opcode,
2694                                      const APValue &RHSValue, APInt &Result) {
2695   // The result is always an int type, however operands match the first.
2696   if (LHSValue.getKind() == APValue::Int)
2697     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2698                                     RHSValue.getInt(), Result);
2699   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2700   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2701                                   RHSValue.getFloat(), Result);
2702 }
2703 
2704 template <typename APTy>
2705 static bool
2706 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2707                                const APTy &RHSValue, APInt &Result) {
2708   switch (Opcode) {
2709   default:
2710     llvm_unreachable("unsupported binary operator");
2711   case BO_EQ:
2712     Result = (LHSValue == RHSValue);
2713     break;
2714   case BO_NE:
2715     Result = (LHSValue != RHSValue);
2716     break;
2717   case BO_LT:
2718     Result = (LHSValue < RHSValue);
2719     break;
2720   case BO_GT:
2721     Result = (LHSValue > RHSValue);
2722     break;
2723   case BO_LE:
2724     Result = (LHSValue <= RHSValue);
2725     break;
2726   case BO_GE:
2727     Result = (LHSValue >= RHSValue);
2728     break;
2729   }
2730 
2731   return true;
2732 }
2733 
2734 static bool handleCompareOpForVector(const APValue &LHSValue,
2735                                      BinaryOperatorKind Opcode,
2736                                      const APValue &RHSValue, APInt &Result) {
2737   // The result is always an int type, however operands match the first.
2738   if (LHSValue.getKind() == APValue::Int)
2739     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2740                                           RHSValue.getInt(), Result);
2741   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2742   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2743                                         RHSValue.getFloat(), Result);
2744 }
2745 
2746 // Perform binary operations for vector types, in place on the LHS.
2747 static bool handleVectorVectorBinOp(EvalInfo &Info, const Expr *E,
2748                                     BinaryOperatorKind Opcode,
2749                                     APValue &LHSValue,
2750                                     const APValue &RHSValue) {
2751   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2752          "Operation not supported on vector types");
2753 
2754   const auto *VT = E->getType()->castAs<VectorType>();
2755   unsigned NumElements = VT->getNumElements();
2756   QualType EltTy = VT->getElementType();
2757 
2758   // In the cases (typically C as I've observed) where we aren't evaluating
2759   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2760   // just give up.
2761   if (!LHSValue.isVector()) {
2762     assert(LHSValue.isLValue() &&
2763            "A vector result that isn't a vector OR uncalculated LValue");
2764     Info.FFDiag(E);
2765     return false;
2766   }
2767 
2768   assert(LHSValue.getVectorLength() == NumElements &&
2769          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2770 
2771   SmallVector<APValue, 4> ResultElements;
2772 
2773   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2774     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2775     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2776 
2777     if (EltTy->isIntegerType()) {
2778       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2779                        EltTy->isUnsignedIntegerType()};
2780       bool Success = true;
2781 
2782       if (BinaryOperator::isLogicalOp(Opcode))
2783         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2784       else if (BinaryOperator::isComparisonOp(Opcode))
2785         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2786       else
2787         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2788                                     RHSElt.getInt(), EltResult);
2789 
2790       if (!Success) {
2791         Info.FFDiag(E);
2792         return false;
2793       }
2794       ResultElements.emplace_back(EltResult);
2795 
2796     } else if (EltTy->isFloatingType()) {
2797       assert(LHSElt.getKind() == APValue::Float &&
2798              RHSElt.getKind() == APValue::Float &&
2799              "Mismatched LHS/RHS/Result Type");
2800       APFloat LHSFloat = LHSElt.getFloat();
2801 
2802       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
2803                                  RHSElt.getFloat())) {
2804         Info.FFDiag(E);
2805         return false;
2806       }
2807 
2808       ResultElements.emplace_back(LHSFloat);
2809     }
2810   }
2811 
2812   LHSValue = APValue(ResultElements.data(), ResultElements.size());
2813   return true;
2814 }
2815 
2816 /// Cast an lvalue referring to a base subobject to a derived class, by
2817 /// truncating the lvalue's path to the given length.
2818 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2819                                const RecordDecl *TruncatedType,
2820                                unsigned TruncatedElements) {
2821   SubobjectDesignator &D = Result.Designator;
2822 
2823   // Check we actually point to a derived class object.
2824   if (TruncatedElements == D.Entries.size())
2825     return true;
2826   assert(TruncatedElements >= D.MostDerivedPathLength &&
2827          "not casting to a derived class");
2828   if (!Result.checkSubobject(Info, E, CSK_Derived))
2829     return false;
2830 
2831   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2832   const RecordDecl *RD = TruncatedType;
2833   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2834     if (RD->isInvalidDecl()) return false;
2835     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2836     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2837     if (isVirtualBaseClass(D.Entries[I]))
2838       Result.Offset -= Layout.getVBaseClassOffset(Base);
2839     else
2840       Result.Offset -= Layout.getBaseClassOffset(Base);
2841     RD = Base;
2842   }
2843   D.Entries.resize(TruncatedElements);
2844   return true;
2845 }
2846 
2847 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2848                                    const CXXRecordDecl *Derived,
2849                                    const CXXRecordDecl *Base,
2850                                    const ASTRecordLayout *RL = nullptr) {
2851   if (!RL) {
2852     if (Derived->isInvalidDecl()) return false;
2853     RL = &Info.Ctx.getASTRecordLayout(Derived);
2854   }
2855 
2856   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2857   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2858   return true;
2859 }
2860 
2861 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2862                              const CXXRecordDecl *DerivedDecl,
2863                              const CXXBaseSpecifier *Base) {
2864   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2865 
2866   if (!Base->isVirtual())
2867     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2868 
2869   SubobjectDesignator &D = Obj.Designator;
2870   if (D.Invalid)
2871     return false;
2872 
2873   // Extract most-derived object and corresponding type.
2874   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2875   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2876     return false;
2877 
2878   // Find the virtual base class.
2879   if (DerivedDecl->isInvalidDecl()) return false;
2880   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2881   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2882   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2883   return true;
2884 }
2885 
2886 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2887                                  QualType Type, LValue &Result) {
2888   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2889                                      PathE = E->path_end();
2890        PathI != PathE; ++PathI) {
2891     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2892                           *PathI))
2893       return false;
2894     Type = (*PathI)->getType();
2895   }
2896   return true;
2897 }
2898 
2899 /// Cast an lvalue referring to a derived class to a known base subobject.
2900 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2901                             const CXXRecordDecl *DerivedRD,
2902                             const CXXRecordDecl *BaseRD) {
2903   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2904                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2905   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2906     llvm_unreachable("Class must be derived from the passed in base class!");
2907 
2908   for (CXXBasePathElement &Elem : Paths.front())
2909     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2910       return false;
2911   return true;
2912 }
2913 
2914 /// Update LVal to refer to the given field, which must be a member of the type
2915 /// currently described by LVal.
2916 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2917                                const FieldDecl *FD,
2918                                const ASTRecordLayout *RL = nullptr) {
2919   if (!RL) {
2920     if (FD->getParent()->isInvalidDecl()) return false;
2921     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2922   }
2923 
2924   unsigned I = FD->getFieldIndex();
2925   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2926   LVal.addDecl(Info, E, FD);
2927   return true;
2928 }
2929 
2930 /// Update LVal to refer to the given indirect field.
2931 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2932                                        LValue &LVal,
2933                                        const IndirectFieldDecl *IFD) {
2934   for (const auto *C : IFD->chain())
2935     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2936       return false;
2937   return true;
2938 }
2939 
2940 /// Get the size of the given type in char units.
2941 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2942                          QualType Type, CharUnits &Size) {
2943   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2944   // extension.
2945   if (Type->isVoidType() || Type->isFunctionType()) {
2946     Size = CharUnits::One();
2947     return true;
2948   }
2949 
2950   if (Type->isDependentType()) {
2951     Info.FFDiag(Loc);
2952     return false;
2953   }
2954 
2955   if (!Type->isConstantSizeType()) {
2956     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2957     // FIXME: Better diagnostic.
2958     Info.FFDiag(Loc);
2959     return false;
2960   }
2961 
2962   Size = Info.Ctx.getTypeSizeInChars(Type);
2963   return true;
2964 }
2965 
2966 /// Update a pointer value to model pointer arithmetic.
2967 /// \param Info - Information about the ongoing evaluation.
2968 /// \param E - The expression being evaluated, for diagnostic purposes.
2969 /// \param LVal - The pointer value to be updated.
2970 /// \param EltTy - The pointee type represented by LVal.
2971 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2972 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2973                                         LValue &LVal, QualType EltTy,
2974                                         APSInt Adjustment) {
2975   CharUnits SizeOfPointee;
2976   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2977     return false;
2978 
2979   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2980   return true;
2981 }
2982 
2983 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2984                                         LValue &LVal, QualType EltTy,
2985                                         int64_t Adjustment) {
2986   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2987                                      APSInt::get(Adjustment));
2988 }
2989 
2990 /// Update an lvalue to refer to a component of a complex number.
2991 /// \param Info - Information about the ongoing evaluation.
2992 /// \param LVal - The lvalue to be updated.
2993 /// \param EltTy - The complex number's component type.
2994 /// \param Imag - False for the real component, true for the imaginary.
2995 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2996                                        LValue &LVal, QualType EltTy,
2997                                        bool Imag) {
2998   if (Imag) {
2999     CharUnits SizeOfComponent;
3000     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3001       return false;
3002     LVal.Offset += SizeOfComponent;
3003   }
3004   LVal.addComplex(Info, E, EltTy, Imag);
3005   return true;
3006 }
3007 
3008 /// Try to evaluate the initializer for a variable declaration.
3009 ///
3010 /// \param Info   Information about the ongoing evaluation.
3011 /// \param E      An expression to be used when printing diagnostics.
3012 /// \param VD     The variable whose initializer should be obtained.
3013 /// \param Frame  The frame in which the variable was created. Must be null
3014 ///               if this variable is not local to the evaluation.
3015 /// \param Result Filled in with a pointer to the value of the variable.
3016 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3017                                 const VarDecl *VD, CallStackFrame *Frame,
3018                                 APValue *&Result, const LValue *LVal) {
3019 
3020   // If this is a parameter to an active constexpr function call, perform
3021   // argument substitution.
3022   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
3023     // Assume arguments of a potential constant expression are unknown
3024     // constant expressions.
3025     if (Info.checkingPotentialConstantExpression())
3026       return false;
3027     if (!Frame || !Frame->Arguments) {
3028       Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD;
3029       return false;
3030     }
3031     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
3032     return true;
3033   }
3034 
3035   // If this is a local variable, dig out its value.
3036   if (Frame) {
3037     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
3038                   : Frame->getCurrentTemporary(VD);
3039     if (!Result) {
3040       // Assume variables referenced within a lambda's call operator that were
3041       // not declared within the call operator are captures and during checking
3042       // of a potential constant expression, assume they are unknown constant
3043       // expressions.
3044       assert(isLambdaCallOperator(Frame->Callee) &&
3045              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3046              "missing value for local variable");
3047       if (Info.checkingPotentialConstantExpression())
3048         return false;
3049       // FIXME: implement capture evaluation during constant expr evaluation.
3050       Info.FFDiag(E->getBeginLoc(),
3051                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3052           << "captures not currently allowed";
3053       return false;
3054     }
3055     return true;
3056   }
3057 
3058   // Dig out the initializer, and use the declaration which it's attached to.
3059   // FIXME: We should eventually check whether the variable has a reachable
3060   // initializing declaration.
3061   const Expr *Init = VD->getAnyInitializer(VD);
3062   if (!Init) {
3063     // Don't diagnose during potential constant expression checking; an
3064     // initializer might be added later.
3065     if (!Info.checkingPotentialConstantExpression()) {
3066       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3067         << VD;
3068       Info.Note(VD->getLocation(), diag::note_declared_at);
3069     }
3070     return false;
3071   }
3072 
3073   if (Init->isValueDependent()) {
3074     // The DeclRefExpr is not value-dependent, but the variable it refers to
3075     // has a value-dependent initializer. This should only happen in
3076     // constant-folding cases, where the variable is not actually of a suitable
3077     // type for use in a constant expression (otherwise the DeclRefExpr would
3078     // have been value-dependent too), so diagnose that.
3079     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3080     if (!Info.checkingPotentialConstantExpression()) {
3081       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3082                          ? diag::note_constexpr_ltor_non_constexpr
3083                          : diag::note_constexpr_ltor_non_integral, 1)
3084           << VD << VD->getType();
3085       Info.Note(VD->getLocation(), diag::note_declared_at);
3086     }
3087     return false;
3088   }
3089 
3090   // If we're currently evaluating the initializer of this declaration, use that
3091   // in-flight value.
3092   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
3093     Result = Info.EvaluatingDeclValue;
3094     return true;
3095   }
3096 
3097   // Check that we can fold the initializer. In C++, we will have already done
3098   // this in the cases where it matters for conformance.
3099   SmallVector<PartialDiagnosticAt, 8> Notes;
3100   if (!VD->evaluateValue(Notes)) {
3101     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3102               Notes.size() + 1) << VD;
3103     Info.Note(VD->getLocation(), diag::note_declared_at);
3104     Info.addNotes(Notes);
3105     return false;
3106   }
3107 
3108   // Check that the variable is actually usable in constant expressions.
3109   if (!VD->checkInitIsICE()) {
3110     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
3111                  Notes.size() + 1) << VD;
3112     Info.Note(VD->getLocation(), diag::note_declared_at);
3113     Info.addNotes(Notes);
3114   }
3115 
3116   // Never use the initializer of a weak variable, not even for constant
3117   // folding. We can't be sure that this is the definition that will be used.
3118   if (VD->isWeak()) {
3119     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3120     Info.Note(VD->getLocation(), diag::note_declared_at);
3121     return false;
3122   }
3123 
3124   Result = VD->getEvaluatedValue();
3125   return true;
3126 }
3127 
3128 static bool IsConstNonVolatile(QualType T) {
3129   Qualifiers Quals = T.getQualifiers();
3130   return Quals.hasConst() && !Quals.hasVolatile();
3131 }
3132 
3133 /// Get the base index of the given base class within an APValue representing
3134 /// the given derived class.
3135 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3136                              const CXXRecordDecl *Base) {
3137   Base = Base->getCanonicalDecl();
3138   unsigned Index = 0;
3139   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3140          E = Derived->bases_end(); I != E; ++I, ++Index) {
3141     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3142       return Index;
3143   }
3144 
3145   llvm_unreachable("base class missing from derived class's bases list");
3146 }
3147 
3148 /// Extract the value of a character from a string literal.
3149 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3150                                             uint64_t Index) {
3151   assert(!isa<SourceLocExpr>(Lit) &&
3152          "SourceLocExpr should have already been converted to a StringLiteral");
3153 
3154   // FIXME: Support MakeStringConstant
3155   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3156     std::string Str;
3157     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3158     assert(Index <= Str.size() && "Index too large");
3159     return APSInt::getUnsigned(Str.c_str()[Index]);
3160   }
3161 
3162   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3163     Lit = PE->getFunctionName();
3164   const StringLiteral *S = cast<StringLiteral>(Lit);
3165   const ConstantArrayType *CAT =
3166       Info.Ctx.getAsConstantArrayType(S->getType());
3167   assert(CAT && "string literal isn't an array");
3168   QualType CharType = CAT->getElementType();
3169   assert(CharType->isIntegerType() && "unexpected character type");
3170 
3171   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3172                CharType->isUnsignedIntegerType());
3173   if (Index < S->getLength())
3174     Value = S->getCodeUnit(Index);
3175   return Value;
3176 }
3177 
3178 // Expand a string literal into an array of characters.
3179 //
3180 // FIXME: This is inefficient; we should probably introduce something similar
3181 // to the LLVM ConstantDataArray to make this cheaper.
3182 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3183                                 APValue &Result,
3184                                 QualType AllocType = QualType()) {
3185   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3186       AllocType.isNull() ? S->getType() : AllocType);
3187   assert(CAT && "string literal isn't an array");
3188   QualType CharType = CAT->getElementType();
3189   assert(CharType->isIntegerType() && "unexpected character type");
3190 
3191   unsigned Elts = CAT->getSize().getZExtValue();
3192   Result = APValue(APValue::UninitArray(),
3193                    std::min(S->getLength(), Elts), Elts);
3194   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3195                CharType->isUnsignedIntegerType());
3196   if (Result.hasArrayFiller())
3197     Result.getArrayFiller() = APValue(Value);
3198   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3199     Value = S->getCodeUnit(I);
3200     Result.getArrayInitializedElt(I) = APValue(Value);
3201   }
3202 }
3203 
3204 // Expand an array so that it has more than Index filled elements.
3205 static void expandArray(APValue &Array, unsigned Index) {
3206   unsigned Size = Array.getArraySize();
3207   assert(Index < Size);
3208 
3209   // Always at least double the number of elements for which we store a value.
3210   unsigned OldElts = Array.getArrayInitializedElts();
3211   unsigned NewElts = std::max(Index+1, OldElts * 2);
3212   NewElts = std::min(Size, std::max(NewElts, 8u));
3213 
3214   // Copy the data across.
3215   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3216   for (unsigned I = 0; I != OldElts; ++I)
3217     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3218   for (unsigned I = OldElts; I != NewElts; ++I)
3219     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3220   if (NewValue.hasArrayFiller())
3221     NewValue.getArrayFiller() = Array.getArrayFiller();
3222   Array.swap(NewValue);
3223 }
3224 
3225 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3226 /// conversion. If it's of class type, we may assume that the copy operation
3227 /// is trivial. Note that this is never true for a union type with fields
3228 /// (because the copy always "reads" the active member) and always true for
3229 /// a non-class type.
3230 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3231 static bool isReadByLvalueToRvalueConversion(QualType T) {
3232   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3233   return !RD || isReadByLvalueToRvalueConversion(RD);
3234 }
3235 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3236   // FIXME: A trivial copy of a union copies the object representation, even if
3237   // the union is empty.
3238   if (RD->isUnion())
3239     return !RD->field_empty();
3240   if (RD->isEmpty())
3241     return false;
3242 
3243   for (auto *Field : RD->fields())
3244     if (!Field->isUnnamedBitfield() &&
3245         isReadByLvalueToRvalueConversion(Field->getType()))
3246       return true;
3247 
3248   for (auto &BaseSpec : RD->bases())
3249     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3250       return true;
3251 
3252   return false;
3253 }
3254 
3255 /// Diagnose an attempt to read from any unreadable field within the specified
3256 /// type, which might be a class type.
3257 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3258                                   QualType T) {
3259   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3260   if (!RD)
3261     return false;
3262 
3263   if (!RD->hasMutableFields())
3264     return false;
3265 
3266   for (auto *Field : RD->fields()) {
3267     // If we're actually going to read this field in some way, then it can't
3268     // be mutable. If we're in a union, then assigning to a mutable field
3269     // (even an empty one) can change the active member, so that's not OK.
3270     // FIXME: Add core issue number for the union case.
3271     if (Field->isMutable() &&
3272         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3273       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3274       Info.Note(Field->getLocation(), diag::note_declared_at);
3275       return true;
3276     }
3277 
3278     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3279       return true;
3280   }
3281 
3282   for (auto &BaseSpec : RD->bases())
3283     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3284       return true;
3285 
3286   // All mutable fields were empty, and thus not actually read.
3287   return false;
3288 }
3289 
3290 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3291                                         APValue::LValueBase Base,
3292                                         bool MutableSubobject = false) {
3293   // A temporary we created.
3294   if (Base.getCallIndex())
3295     return true;
3296 
3297   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3298   if (!Evaluating)
3299     return false;
3300 
3301   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3302 
3303   switch (Info.IsEvaluatingDecl) {
3304   case EvalInfo::EvaluatingDeclKind::None:
3305     return false;
3306 
3307   case EvalInfo::EvaluatingDeclKind::Ctor:
3308     // The variable whose initializer we're evaluating.
3309     if (BaseD)
3310       return declaresSameEntity(Evaluating, BaseD);
3311 
3312     // A temporary lifetime-extended by the variable whose initializer we're
3313     // evaluating.
3314     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3315       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3316         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3317     return false;
3318 
3319   case EvalInfo::EvaluatingDeclKind::Dtor:
3320     // C++2a [expr.const]p6:
3321     //   [during constant destruction] the lifetime of a and its non-mutable
3322     //   subobjects (but not its mutable subobjects) [are] considered to start
3323     //   within e.
3324     //
3325     // FIXME: We can meaningfully extend this to cover non-const objects, but
3326     // we will need special handling: we should be able to access only
3327     // subobjects of such objects that are themselves declared const.
3328     if (!BaseD ||
3329         !(BaseD->getType().isConstQualified() ||
3330           BaseD->getType()->isReferenceType()) ||
3331         MutableSubobject)
3332       return false;
3333     return declaresSameEntity(Evaluating, BaseD);
3334   }
3335 
3336   llvm_unreachable("unknown evaluating decl kind");
3337 }
3338 
3339 namespace {
3340 /// A handle to a complete object (an object that is not a subobject of
3341 /// another object).
3342 struct CompleteObject {
3343   /// The identity of the object.
3344   APValue::LValueBase Base;
3345   /// The value of the complete object.
3346   APValue *Value;
3347   /// The type of the complete object.
3348   QualType Type;
3349 
3350   CompleteObject() : Value(nullptr) {}
3351   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3352       : Base(Base), Value(Value), Type(Type) {}
3353 
3354   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3355     // If this isn't a "real" access (eg, if it's just accessing the type
3356     // info), allow it. We assume the type doesn't change dynamically for
3357     // subobjects of constexpr objects (even though we'd hit UB here if it
3358     // did). FIXME: Is this right?
3359     if (!isAnyAccess(AK))
3360       return true;
3361 
3362     // In C++14 onwards, it is permitted to read a mutable member whose
3363     // lifetime began within the evaluation.
3364     // FIXME: Should we also allow this in C++11?
3365     if (!Info.getLangOpts().CPlusPlus14)
3366       return false;
3367     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3368   }
3369 
3370   explicit operator bool() const { return !Type.isNull(); }
3371 };
3372 } // end anonymous namespace
3373 
3374 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3375                                  bool IsMutable = false) {
3376   // C++ [basic.type.qualifier]p1:
3377   // - A const object is an object of type const T or a non-mutable subobject
3378   //   of a const object.
3379   if (ObjType.isConstQualified() && !IsMutable)
3380     SubobjType.addConst();
3381   // - A volatile object is an object of type const T or a subobject of a
3382   //   volatile object.
3383   if (ObjType.isVolatileQualified())
3384     SubobjType.addVolatile();
3385   return SubobjType;
3386 }
3387 
3388 /// Find the designated sub-object of an rvalue.
3389 template<typename SubobjectHandler>
3390 typename SubobjectHandler::result_type
3391 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3392               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3393   if (Sub.Invalid)
3394     // A diagnostic will have already been produced.
3395     return handler.failed();
3396   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3397     if (Info.getLangOpts().CPlusPlus11)
3398       Info.FFDiag(E, Sub.isOnePastTheEnd()
3399                          ? diag::note_constexpr_access_past_end
3400                          : diag::note_constexpr_access_unsized_array)
3401           << handler.AccessKind;
3402     else
3403       Info.FFDiag(E);
3404     return handler.failed();
3405   }
3406 
3407   APValue *O = Obj.Value;
3408   QualType ObjType = Obj.Type;
3409   const FieldDecl *LastField = nullptr;
3410   const FieldDecl *VolatileField = nullptr;
3411 
3412   // Walk the designator's path to find the subobject.
3413   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3414     // Reading an indeterminate value is undefined, but assigning over one is OK.
3415     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3416         (O->isIndeterminate() &&
3417          !isValidIndeterminateAccess(handler.AccessKind))) {
3418       if (!Info.checkingPotentialConstantExpression())
3419         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3420             << handler.AccessKind << O->isIndeterminate();
3421       return handler.failed();
3422     }
3423 
3424     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3425     //    const and volatile semantics are not applied on an object under
3426     //    {con,de}struction.
3427     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3428         ObjType->isRecordType() &&
3429         Info.isEvaluatingCtorDtor(
3430             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3431                                          Sub.Entries.begin() + I)) !=
3432                           ConstructionPhase::None) {
3433       ObjType = Info.Ctx.getCanonicalType(ObjType);
3434       ObjType.removeLocalConst();
3435       ObjType.removeLocalVolatile();
3436     }
3437 
3438     // If this is our last pass, check that the final object type is OK.
3439     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3440       // Accesses to volatile objects are prohibited.
3441       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3442         if (Info.getLangOpts().CPlusPlus) {
3443           int DiagKind;
3444           SourceLocation Loc;
3445           const NamedDecl *Decl = nullptr;
3446           if (VolatileField) {
3447             DiagKind = 2;
3448             Loc = VolatileField->getLocation();
3449             Decl = VolatileField;
3450           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3451             DiagKind = 1;
3452             Loc = VD->getLocation();
3453             Decl = VD;
3454           } else {
3455             DiagKind = 0;
3456             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3457               Loc = E->getExprLoc();
3458           }
3459           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3460               << handler.AccessKind << DiagKind << Decl;
3461           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3462         } else {
3463           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3464         }
3465         return handler.failed();
3466       }
3467 
3468       // If we are reading an object of class type, there may still be more
3469       // things we need to check: if there are any mutable subobjects, we
3470       // cannot perform this read. (This only happens when performing a trivial
3471       // copy or assignment.)
3472       if (ObjType->isRecordType() &&
3473           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3474           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3475         return handler.failed();
3476     }
3477 
3478     if (I == N) {
3479       if (!handler.found(*O, ObjType))
3480         return false;
3481 
3482       // If we modified a bit-field, truncate it to the right width.
3483       if (isModification(handler.AccessKind) &&
3484           LastField && LastField->isBitField() &&
3485           !truncateBitfieldValue(Info, E, *O, LastField))
3486         return false;
3487 
3488       return true;
3489     }
3490 
3491     LastField = nullptr;
3492     if (ObjType->isArrayType()) {
3493       // Next subobject is an array element.
3494       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3495       assert(CAT && "vla in literal type?");
3496       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3497       if (CAT->getSize().ule(Index)) {
3498         // Note, it should not be possible to form a pointer with a valid
3499         // designator which points more than one past the end of the array.
3500         if (Info.getLangOpts().CPlusPlus11)
3501           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3502             << handler.AccessKind;
3503         else
3504           Info.FFDiag(E);
3505         return handler.failed();
3506       }
3507 
3508       ObjType = CAT->getElementType();
3509 
3510       if (O->getArrayInitializedElts() > Index)
3511         O = &O->getArrayInitializedElt(Index);
3512       else if (!isRead(handler.AccessKind)) {
3513         expandArray(*O, Index);
3514         O = &O->getArrayInitializedElt(Index);
3515       } else
3516         O = &O->getArrayFiller();
3517     } else if (ObjType->isAnyComplexType()) {
3518       // Next subobject is a complex number.
3519       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3520       if (Index > 1) {
3521         if (Info.getLangOpts().CPlusPlus11)
3522           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3523             << handler.AccessKind;
3524         else
3525           Info.FFDiag(E);
3526         return handler.failed();
3527       }
3528 
3529       ObjType = getSubobjectType(
3530           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3531 
3532       assert(I == N - 1 && "extracting subobject of scalar?");
3533       if (O->isComplexInt()) {
3534         return handler.found(Index ? O->getComplexIntImag()
3535                                    : O->getComplexIntReal(), ObjType);
3536       } else {
3537         assert(O->isComplexFloat());
3538         return handler.found(Index ? O->getComplexFloatImag()
3539                                    : O->getComplexFloatReal(), ObjType);
3540       }
3541     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3542       if (Field->isMutable() &&
3543           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3544         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3545           << handler.AccessKind << Field;
3546         Info.Note(Field->getLocation(), diag::note_declared_at);
3547         return handler.failed();
3548       }
3549 
3550       // Next subobject is a class, struct or union field.
3551       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3552       if (RD->isUnion()) {
3553         const FieldDecl *UnionField = O->getUnionField();
3554         if (!UnionField ||
3555             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3556           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3557             // Placement new onto an inactive union member makes it active.
3558             O->setUnion(Field, APValue());
3559           } else {
3560             // FIXME: If O->getUnionValue() is absent, report that there's no
3561             // active union member rather than reporting the prior active union
3562             // member. We'll need to fix nullptr_t to not use APValue() as its
3563             // representation first.
3564             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3565                 << handler.AccessKind << Field << !UnionField << UnionField;
3566             return handler.failed();
3567           }
3568         }
3569         O = &O->getUnionValue();
3570       } else
3571         O = &O->getStructField(Field->getFieldIndex());
3572 
3573       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3574       LastField = Field;
3575       if (Field->getType().isVolatileQualified())
3576         VolatileField = Field;
3577     } else {
3578       // Next subobject is a base class.
3579       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3580       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3581       O = &O->getStructBase(getBaseIndex(Derived, Base));
3582 
3583       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3584     }
3585   }
3586 }
3587 
3588 namespace {
3589 struct ExtractSubobjectHandler {
3590   EvalInfo &Info;
3591   const Expr *E;
3592   APValue &Result;
3593   const AccessKinds AccessKind;
3594 
3595   typedef bool result_type;
3596   bool failed() { return false; }
3597   bool found(APValue &Subobj, QualType SubobjType) {
3598     Result = Subobj;
3599     if (AccessKind == AK_ReadObjectRepresentation)
3600       return true;
3601     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3602   }
3603   bool found(APSInt &Value, QualType SubobjType) {
3604     Result = APValue(Value);
3605     return true;
3606   }
3607   bool found(APFloat &Value, QualType SubobjType) {
3608     Result = APValue(Value);
3609     return true;
3610   }
3611 };
3612 } // end anonymous namespace
3613 
3614 /// Extract the designated sub-object of an rvalue.
3615 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3616                              const CompleteObject &Obj,
3617                              const SubobjectDesignator &Sub, APValue &Result,
3618                              AccessKinds AK = AK_Read) {
3619   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3620   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3621   return findSubobject(Info, E, Obj, Sub, Handler);
3622 }
3623 
3624 namespace {
3625 struct ModifySubobjectHandler {
3626   EvalInfo &Info;
3627   APValue &NewVal;
3628   const Expr *E;
3629 
3630   typedef bool result_type;
3631   static const AccessKinds AccessKind = AK_Assign;
3632 
3633   bool checkConst(QualType QT) {
3634     // Assigning to a const object has undefined behavior.
3635     if (QT.isConstQualified()) {
3636       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3637       return false;
3638     }
3639     return true;
3640   }
3641 
3642   bool failed() { return false; }
3643   bool found(APValue &Subobj, QualType SubobjType) {
3644     if (!checkConst(SubobjType))
3645       return false;
3646     // We've been given ownership of NewVal, so just swap it in.
3647     Subobj.swap(NewVal);
3648     return true;
3649   }
3650   bool found(APSInt &Value, QualType SubobjType) {
3651     if (!checkConst(SubobjType))
3652       return false;
3653     if (!NewVal.isInt()) {
3654       // Maybe trying to write a cast pointer value into a complex?
3655       Info.FFDiag(E);
3656       return false;
3657     }
3658     Value = NewVal.getInt();
3659     return true;
3660   }
3661   bool found(APFloat &Value, QualType SubobjType) {
3662     if (!checkConst(SubobjType))
3663       return false;
3664     Value = NewVal.getFloat();
3665     return true;
3666   }
3667 };
3668 } // end anonymous namespace
3669 
3670 const AccessKinds ModifySubobjectHandler::AccessKind;
3671 
3672 /// Update the designated sub-object of an rvalue to the given value.
3673 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3674                             const CompleteObject &Obj,
3675                             const SubobjectDesignator &Sub,
3676                             APValue &NewVal) {
3677   ModifySubobjectHandler Handler = { Info, NewVal, E };
3678   return findSubobject(Info, E, Obj, Sub, Handler);
3679 }
3680 
3681 /// Find the position where two subobject designators diverge, or equivalently
3682 /// the length of the common initial subsequence.
3683 static unsigned FindDesignatorMismatch(QualType ObjType,
3684                                        const SubobjectDesignator &A,
3685                                        const SubobjectDesignator &B,
3686                                        bool &WasArrayIndex) {
3687   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3688   for (/**/; I != N; ++I) {
3689     if (!ObjType.isNull() &&
3690         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3691       // Next subobject is an array element.
3692       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3693         WasArrayIndex = true;
3694         return I;
3695       }
3696       if (ObjType->isAnyComplexType())
3697         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3698       else
3699         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3700     } else {
3701       if (A.Entries[I].getAsBaseOrMember() !=
3702           B.Entries[I].getAsBaseOrMember()) {
3703         WasArrayIndex = false;
3704         return I;
3705       }
3706       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3707         // Next subobject is a field.
3708         ObjType = FD->getType();
3709       else
3710         // Next subobject is a base class.
3711         ObjType = QualType();
3712     }
3713   }
3714   WasArrayIndex = false;
3715   return I;
3716 }
3717 
3718 /// Determine whether the given subobject designators refer to elements of the
3719 /// same array object.
3720 static bool AreElementsOfSameArray(QualType ObjType,
3721                                    const SubobjectDesignator &A,
3722                                    const SubobjectDesignator &B) {
3723   if (A.Entries.size() != B.Entries.size())
3724     return false;
3725 
3726   bool IsArray = A.MostDerivedIsArrayElement;
3727   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3728     // A is a subobject of the array element.
3729     return false;
3730 
3731   // If A (and B) designates an array element, the last entry will be the array
3732   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3733   // of length 1' case, and the entire path must match.
3734   bool WasArrayIndex;
3735   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3736   return CommonLength >= A.Entries.size() - IsArray;
3737 }
3738 
3739 /// Find the complete object to which an LValue refers.
3740 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3741                                          AccessKinds AK, const LValue &LVal,
3742                                          QualType LValType) {
3743   if (LVal.InvalidBase) {
3744     Info.FFDiag(E);
3745     return CompleteObject();
3746   }
3747 
3748   if (!LVal.Base) {
3749     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3750     return CompleteObject();
3751   }
3752 
3753   CallStackFrame *Frame = nullptr;
3754   unsigned Depth = 0;
3755   if (LVal.getLValueCallIndex()) {
3756     std::tie(Frame, Depth) =
3757         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3758     if (!Frame) {
3759       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3760         << AK << LVal.Base.is<const ValueDecl*>();
3761       NoteLValueLocation(Info, LVal.Base);
3762       return CompleteObject();
3763     }
3764   }
3765 
3766   bool IsAccess = isAnyAccess(AK);
3767 
3768   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3769   // is not a constant expression (even if the object is non-volatile). We also
3770   // apply this rule to C++98, in order to conform to the expected 'volatile'
3771   // semantics.
3772   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3773     if (Info.getLangOpts().CPlusPlus)
3774       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3775         << AK << LValType;
3776     else
3777       Info.FFDiag(E);
3778     return CompleteObject();
3779   }
3780 
3781   // Compute value storage location and type of base object.
3782   APValue *BaseVal = nullptr;
3783   QualType BaseType = getType(LVal.Base);
3784 
3785   if (const ConstantExpr *CE =
3786           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3787     /// Nested immediate invocation have been previously removed so if we found
3788     /// a ConstantExpr it can only be the EvaluatingDecl.
3789     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3790     (void)CE;
3791     BaseVal = Info.EvaluatingDeclValue;
3792   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3793     // Allow reading from a GUID declaration.
3794     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3795       if (isModification(AK)) {
3796         // All the remaining cases do not permit modification of the object.
3797         Info.FFDiag(E, diag::note_constexpr_modify_global);
3798         return CompleteObject();
3799       }
3800       APValue &V = GD->getAsAPValue();
3801       if (V.isAbsent()) {
3802         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3803             << GD->getType();
3804         return CompleteObject();
3805       }
3806       return CompleteObject(LVal.Base, &V, GD->getType());
3807     }
3808 
3809     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3810     // In C++11, constexpr, non-volatile variables initialized with constant
3811     // expressions are constant expressions too. Inside constexpr functions,
3812     // parameters are constant expressions even if they're non-const.
3813     // In C++1y, objects local to a constant expression (those with a Frame) are
3814     // both readable and writable inside constant expressions.
3815     // In C, such things can also be folded, although they are not ICEs.
3816     const VarDecl *VD = dyn_cast<VarDecl>(D);
3817     if (VD) {
3818       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3819         VD = VDef;
3820     }
3821     if (!VD || VD->isInvalidDecl()) {
3822       Info.FFDiag(E);
3823       return CompleteObject();
3824     }
3825 
3826     // In OpenCL if a variable is in constant address space it is a const value.
3827     bool IsConstant = BaseType.isConstQualified() ||
3828                       (Info.getLangOpts().OpenCL &&
3829                        BaseType.getAddressSpace() == LangAS::opencl_constant);
3830 
3831     // Unless we're looking at a local variable or argument in a constexpr call,
3832     // the variable we're reading must be const.
3833     if (!Frame) {
3834       if (Info.getLangOpts().CPlusPlus14 &&
3835           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3836         // OK, we can read and modify an object if we're in the process of
3837         // evaluating its initializer, because its lifetime began in this
3838         // evaluation.
3839       } else if (isModification(AK)) {
3840         // All the remaining cases do not permit modification of the object.
3841         Info.FFDiag(E, diag::note_constexpr_modify_global);
3842         return CompleteObject();
3843       } else if (VD->isConstexpr()) {
3844         // OK, we can read this variable.
3845       } else if (BaseType->isIntegralOrEnumerationType()) {
3846         // In OpenCL if a variable is in constant address space it is a const
3847         // value.
3848         if (!IsConstant) {
3849           if (!IsAccess)
3850             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3851           if (Info.getLangOpts().CPlusPlus) {
3852             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3853             Info.Note(VD->getLocation(), diag::note_declared_at);
3854           } else {
3855             Info.FFDiag(E);
3856           }
3857           return CompleteObject();
3858         }
3859       } else if (!IsAccess) {
3860         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3861       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
3862                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
3863         // This variable might end up being constexpr. Don't diagnose it yet.
3864       } else if (IsConstant) {
3865         // Keep evaluating to see what we can do. In particular, we support
3866         // folding of const floating-point types, in order to make static const
3867         // data members of such types (supported as an extension) more useful.
3868         if (Info.getLangOpts().CPlusPlus) {
3869           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
3870                               ? diag::note_constexpr_ltor_non_constexpr
3871                               : diag::note_constexpr_ltor_non_integral, 1)
3872               << VD << BaseType;
3873           Info.Note(VD->getLocation(), diag::note_declared_at);
3874         } else {
3875           Info.CCEDiag(E);
3876         }
3877       } else {
3878         // Never allow reading a non-const value.
3879         if (Info.getLangOpts().CPlusPlus) {
3880           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3881                              ? diag::note_constexpr_ltor_non_constexpr
3882                              : diag::note_constexpr_ltor_non_integral, 1)
3883               << VD << BaseType;
3884           Info.Note(VD->getLocation(), diag::note_declared_at);
3885         } else {
3886           Info.FFDiag(E);
3887         }
3888         return CompleteObject();
3889       }
3890     }
3891 
3892     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3893       return CompleteObject();
3894   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3895     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3896     if (!Alloc) {
3897       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3898       return CompleteObject();
3899     }
3900     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3901                           LVal.Base.getDynamicAllocType());
3902   } else {
3903     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3904 
3905     if (!Frame) {
3906       if (const MaterializeTemporaryExpr *MTE =
3907               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3908         assert(MTE->getStorageDuration() == SD_Static &&
3909                "should have a frame for a non-global materialized temporary");
3910 
3911         // Per C++1y [expr.const]p2:
3912         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3913         //   - a [...] glvalue of integral or enumeration type that refers to
3914         //     a non-volatile const object [...]
3915         //   [...]
3916         //   - a [...] glvalue of literal type that refers to a non-volatile
3917         //     object whose lifetime began within the evaluation of e.
3918         //
3919         // C++11 misses the 'began within the evaluation of e' check and
3920         // instead allows all temporaries, including things like:
3921         //   int &&r = 1;
3922         //   int x = ++r;
3923         //   constexpr int k = r;
3924         // Therefore we use the C++14 rules in C++11 too.
3925         //
3926         // Note that temporaries whose lifetimes began while evaluating a
3927         // variable's constructor are not usable while evaluating the
3928         // corresponding destructor, not even if they're of const-qualified
3929         // types.
3930         if (!(BaseType.isConstQualified() &&
3931               BaseType->isIntegralOrEnumerationType()) &&
3932             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3933           if (!IsAccess)
3934             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3935           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3936           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3937           return CompleteObject();
3938         }
3939 
3940         BaseVal = MTE->getOrCreateValue(false);
3941         assert(BaseVal && "got reference to unevaluated temporary");
3942       } else {
3943         if (!IsAccess)
3944           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3945         APValue Val;
3946         LVal.moveInto(Val);
3947         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3948             << AK
3949             << Val.getAsString(Info.Ctx,
3950                                Info.Ctx.getLValueReferenceType(LValType));
3951         NoteLValueLocation(Info, LVal.Base);
3952         return CompleteObject();
3953       }
3954     } else {
3955       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3956       assert(BaseVal && "missing value for temporary");
3957     }
3958   }
3959 
3960   // In C++14, we can't safely access any mutable state when we might be
3961   // evaluating after an unmodeled side effect.
3962   //
3963   // FIXME: Not all local state is mutable. Allow local constant subobjects
3964   // to be read here (but take care with 'mutable' fields).
3965   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3966        Info.EvalStatus.HasSideEffects) ||
3967       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3968     return CompleteObject();
3969 
3970   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3971 }
3972 
3973 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3974 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3975 /// glvalue referred to by an entity of reference type.
3976 ///
3977 /// \param Info - Information about the ongoing evaluation.
3978 /// \param Conv - The expression for which we are performing the conversion.
3979 ///               Used for diagnostics.
3980 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3981 ///               case of a non-class type).
3982 /// \param LVal - The glvalue on which we are attempting to perform this action.
3983 /// \param RVal - The produced value will be placed here.
3984 /// \param WantObjectRepresentation - If true, we're looking for the object
3985 ///               representation rather than the value, and in particular,
3986 ///               there is no requirement that the result be fully initialized.
3987 static bool
3988 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3989                                const LValue &LVal, APValue &RVal,
3990                                bool WantObjectRepresentation = false) {
3991   if (LVal.Designator.Invalid)
3992     return false;
3993 
3994   // Check for special cases where there is no existing APValue to look at.
3995   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3996 
3997   AccessKinds AK =
3998       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3999 
4000   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4001     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4002       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4003       // initializer until now for such expressions. Such an expression can't be
4004       // an ICE in C, so this only matters for fold.
4005       if (Type.isVolatileQualified()) {
4006         Info.FFDiag(Conv);
4007         return false;
4008       }
4009       APValue Lit;
4010       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4011         return false;
4012       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4013       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4014     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4015       // Special-case character extraction so we don't have to construct an
4016       // APValue for the whole string.
4017       assert(LVal.Designator.Entries.size() <= 1 &&
4018              "Can only read characters from string literals");
4019       if (LVal.Designator.Entries.empty()) {
4020         // Fail for now for LValue to RValue conversion of an array.
4021         // (This shouldn't show up in C/C++, but it could be triggered by a
4022         // weird EvaluateAsRValue call from a tool.)
4023         Info.FFDiag(Conv);
4024         return false;
4025       }
4026       if (LVal.Designator.isOnePastTheEnd()) {
4027         if (Info.getLangOpts().CPlusPlus11)
4028           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4029         else
4030           Info.FFDiag(Conv);
4031         return false;
4032       }
4033       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4034       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4035       return true;
4036     }
4037   }
4038 
4039   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4040   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4041 }
4042 
4043 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4044 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4045                              QualType LValType, APValue &Val) {
4046   if (LVal.Designator.Invalid)
4047     return false;
4048 
4049   if (!Info.getLangOpts().CPlusPlus14) {
4050     Info.FFDiag(E);
4051     return false;
4052   }
4053 
4054   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4055   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4056 }
4057 
4058 namespace {
4059 struct CompoundAssignSubobjectHandler {
4060   EvalInfo &Info;
4061   const Expr *E;
4062   QualType PromotedLHSType;
4063   BinaryOperatorKind Opcode;
4064   const APValue &RHS;
4065 
4066   static const AccessKinds AccessKind = AK_Assign;
4067 
4068   typedef bool result_type;
4069 
4070   bool checkConst(QualType QT) {
4071     // Assigning to a const object has undefined behavior.
4072     if (QT.isConstQualified()) {
4073       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4074       return false;
4075     }
4076     return true;
4077   }
4078 
4079   bool failed() { return false; }
4080   bool found(APValue &Subobj, QualType SubobjType) {
4081     switch (Subobj.getKind()) {
4082     case APValue::Int:
4083       return found(Subobj.getInt(), SubobjType);
4084     case APValue::Float:
4085       return found(Subobj.getFloat(), SubobjType);
4086     case APValue::ComplexInt:
4087     case APValue::ComplexFloat:
4088       // FIXME: Implement complex compound assignment.
4089       Info.FFDiag(E);
4090       return false;
4091     case APValue::LValue:
4092       return foundPointer(Subobj, SubobjType);
4093     case APValue::Vector:
4094       return foundVector(Subobj, SubobjType);
4095     default:
4096       // FIXME: can this happen?
4097       Info.FFDiag(E);
4098       return false;
4099     }
4100   }
4101 
4102   bool foundVector(APValue &Value, QualType SubobjType) {
4103     if (!checkConst(SubobjType))
4104       return false;
4105 
4106     if (!SubobjType->isVectorType()) {
4107       Info.FFDiag(E);
4108       return false;
4109     }
4110     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4111   }
4112 
4113   bool found(APSInt &Value, QualType SubobjType) {
4114     if (!checkConst(SubobjType))
4115       return false;
4116 
4117     if (!SubobjType->isIntegerType()) {
4118       // We don't support compound assignment on integer-cast-to-pointer
4119       // values.
4120       Info.FFDiag(E);
4121       return false;
4122     }
4123 
4124     if (RHS.isInt()) {
4125       APSInt LHS =
4126           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4127       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4128         return false;
4129       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4130       return true;
4131     } else if (RHS.isFloat()) {
4132       APFloat FValue(0.0);
4133       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
4134                                   FValue) &&
4135              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4136              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4137                                   Value);
4138     }
4139 
4140     Info.FFDiag(E);
4141     return false;
4142   }
4143   bool found(APFloat &Value, QualType SubobjType) {
4144     return checkConst(SubobjType) &&
4145            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4146                                   Value) &&
4147            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4148            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4149   }
4150   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4151     if (!checkConst(SubobjType))
4152       return false;
4153 
4154     QualType PointeeType;
4155     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4156       PointeeType = PT->getPointeeType();
4157 
4158     if (PointeeType.isNull() || !RHS.isInt() ||
4159         (Opcode != BO_Add && Opcode != BO_Sub)) {
4160       Info.FFDiag(E);
4161       return false;
4162     }
4163 
4164     APSInt Offset = RHS.getInt();
4165     if (Opcode == BO_Sub)
4166       negateAsSigned(Offset);
4167 
4168     LValue LVal;
4169     LVal.setFrom(Info.Ctx, Subobj);
4170     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4171       return false;
4172     LVal.moveInto(Subobj);
4173     return true;
4174   }
4175 };
4176 } // end anonymous namespace
4177 
4178 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4179 
4180 /// Perform a compound assignment of LVal <op>= RVal.
4181 static bool handleCompoundAssignment(
4182     EvalInfo &Info, const Expr *E,
4183     const LValue &LVal, QualType LValType, QualType PromotedLValType,
4184     BinaryOperatorKind Opcode, const APValue &RVal) {
4185   if (LVal.Designator.Invalid)
4186     return false;
4187 
4188   if (!Info.getLangOpts().CPlusPlus14) {
4189     Info.FFDiag(E);
4190     return false;
4191   }
4192 
4193   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4194   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4195                                              RVal };
4196   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4197 }
4198 
4199 namespace {
4200 struct IncDecSubobjectHandler {
4201   EvalInfo &Info;
4202   const UnaryOperator *E;
4203   AccessKinds AccessKind;
4204   APValue *Old;
4205 
4206   typedef bool result_type;
4207 
4208   bool checkConst(QualType QT) {
4209     // Assigning to a const object has undefined behavior.
4210     if (QT.isConstQualified()) {
4211       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4212       return false;
4213     }
4214     return true;
4215   }
4216 
4217   bool failed() { return false; }
4218   bool found(APValue &Subobj, QualType SubobjType) {
4219     // Stash the old value. Also clear Old, so we don't clobber it later
4220     // if we're post-incrementing a complex.
4221     if (Old) {
4222       *Old = Subobj;
4223       Old = nullptr;
4224     }
4225 
4226     switch (Subobj.getKind()) {
4227     case APValue::Int:
4228       return found(Subobj.getInt(), SubobjType);
4229     case APValue::Float:
4230       return found(Subobj.getFloat(), SubobjType);
4231     case APValue::ComplexInt:
4232       return found(Subobj.getComplexIntReal(),
4233                    SubobjType->castAs<ComplexType>()->getElementType()
4234                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4235     case APValue::ComplexFloat:
4236       return found(Subobj.getComplexFloatReal(),
4237                    SubobjType->castAs<ComplexType>()->getElementType()
4238                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4239     case APValue::LValue:
4240       return foundPointer(Subobj, SubobjType);
4241     default:
4242       // FIXME: can this happen?
4243       Info.FFDiag(E);
4244       return false;
4245     }
4246   }
4247   bool found(APSInt &Value, QualType SubobjType) {
4248     if (!checkConst(SubobjType))
4249       return false;
4250 
4251     if (!SubobjType->isIntegerType()) {
4252       // We don't support increment / decrement on integer-cast-to-pointer
4253       // values.
4254       Info.FFDiag(E);
4255       return false;
4256     }
4257 
4258     if (Old) *Old = APValue(Value);
4259 
4260     // bool arithmetic promotes to int, and the conversion back to bool
4261     // doesn't reduce mod 2^n, so special-case it.
4262     if (SubobjType->isBooleanType()) {
4263       if (AccessKind == AK_Increment)
4264         Value = 1;
4265       else
4266         Value = !Value;
4267       return true;
4268     }
4269 
4270     bool WasNegative = Value.isNegative();
4271     if (AccessKind == AK_Increment) {
4272       ++Value;
4273 
4274       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4275         APSInt ActualValue(Value, /*IsUnsigned*/true);
4276         return HandleOverflow(Info, E, ActualValue, SubobjType);
4277       }
4278     } else {
4279       --Value;
4280 
4281       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4282         unsigned BitWidth = Value.getBitWidth();
4283         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4284         ActualValue.setBit(BitWidth);
4285         return HandleOverflow(Info, E, ActualValue, SubobjType);
4286       }
4287     }
4288     return true;
4289   }
4290   bool found(APFloat &Value, QualType SubobjType) {
4291     if (!checkConst(SubobjType))
4292       return false;
4293 
4294     if (Old) *Old = APValue(Value);
4295 
4296     APFloat One(Value.getSemantics(), 1);
4297     if (AccessKind == AK_Increment)
4298       Value.add(One, APFloat::rmNearestTiesToEven);
4299     else
4300       Value.subtract(One, APFloat::rmNearestTiesToEven);
4301     return true;
4302   }
4303   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4304     if (!checkConst(SubobjType))
4305       return false;
4306 
4307     QualType PointeeType;
4308     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4309       PointeeType = PT->getPointeeType();
4310     else {
4311       Info.FFDiag(E);
4312       return false;
4313     }
4314 
4315     LValue LVal;
4316     LVal.setFrom(Info.Ctx, Subobj);
4317     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4318                                      AccessKind == AK_Increment ? 1 : -1))
4319       return false;
4320     LVal.moveInto(Subobj);
4321     return true;
4322   }
4323 };
4324 } // end anonymous namespace
4325 
4326 /// Perform an increment or decrement on LVal.
4327 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4328                          QualType LValType, bool IsIncrement, APValue *Old) {
4329   if (LVal.Designator.Invalid)
4330     return false;
4331 
4332   if (!Info.getLangOpts().CPlusPlus14) {
4333     Info.FFDiag(E);
4334     return false;
4335   }
4336 
4337   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4338   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4339   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4340   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4341 }
4342 
4343 /// Build an lvalue for the object argument of a member function call.
4344 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4345                                    LValue &This) {
4346   if (Object->getType()->isPointerType() && Object->isRValue())
4347     return EvaluatePointer(Object, This, Info);
4348 
4349   if (Object->isGLValue())
4350     return EvaluateLValue(Object, This, Info);
4351 
4352   if (Object->getType()->isLiteralType(Info.Ctx))
4353     return EvaluateTemporary(Object, This, Info);
4354 
4355   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4356   return false;
4357 }
4358 
4359 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4360 /// lvalue referring to the result.
4361 ///
4362 /// \param Info - Information about the ongoing evaluation.
4363 /// \param LV - An lvalue referring to the base of the member pointer.
4364 /// \param RHS - The member pointer expression.
4365 /// \param IncludeMember - Specifies whether the member itself is included in
4366 ///        the resulting LValue subobject designator. This is not possible when
4367 ///        creating a bound member function.
4368 /// \return The field or method declaration to which the member pointer refers,
4369 ///         or 0 if evaluation fails.
4370 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4371                                                   QualType LVType,
4372                                                   LValue &LV,
4373                                                   const Expr *RHS,
4374                                                   bool IncludeMember = true) {
4375   MemberPtr MemPtr;
4376   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4377     return nullptr;
4378 
4379   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4380   // member value, the behavior is undefined.
4381   if (!MemPtr.getDecl()) {
4382     // FIXME: Specific diagnostic.
4383     Info.FFDiag(RHS);
4384     return nullptr;
4385   }
4386 
4387   if (MemPtr.isDerivedMember()) {
4388     // This is a member of some derived class. Truncate LV appropriately.
4389     // The end of the derived-to-base path for the base object must match the
4390     // derived-to-base path for the member pointer.
4391     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4392         LV.Designator.Entries.size()) {
4393       Info.FFDiag(RHS);
4394       return nullptr;
4395     }
4396     unsigned PathLengthToMember =
4397         LV.Designator.Entries.size() - MemPtr.Path.size();
4398     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4399       const CXXRecordDecl *LVDecl = getAsBaseClass(
4400           LV.Designator.Entries[PathLengthToMember + I]);
4401       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4402       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4403         Info.FFDiag(RHS);
4404         return nullptr;
4405       }
4406     }
4407 
4408     // Truncate the lvalue to the appropriate derived class.
4409     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4410                             PathLengthToMember))
4411       return nullptr;
4412   } else if (!MemPtr.Path.empty()) {
4413     // Extend the LValue path with the member pointer's path.
4414     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4415                                   MemPtr.Path.size() + IncludeMember);
4416 
4417     // Walk down to the appropriate base class.
4418     if (const PointerType *PT = LVType->getAs<PointerType>())
4419       LVType = PT->getPointeeType();
4420     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4421     assert(RD && "member pointer access on non-class-type expression");
4422     // The first class in the path is that of the lvalue.
4423     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4424       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4425       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4426         return nullptr;
4427       RD = Base;
4428     }
4429     // Finally cast to the class containing the member.
4430     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4431                                 MemPtr.getContainingRecord()))
4432       return nullptr;
4433   }
4434 
4435   // Add the member. Note that we cannot build bound member functions here.
4436   if (IncludeMember) {
4437     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4438       if (!HandleLValueMember(Info, RHS, LV, FD))
4439         return nullptr;
4440     } else if (const IndirectFieldDecl *IFD =
4441                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4442       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4443         return nullptr;
4444     } else {
4445       llvm_unreachable("can't construct reference to bound member function");
4446     }
4447   }
4448 
4449   return MemPtr.getDecl();
4450 }
4451 
4452 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4453                                                   const BinaryOperator *BO,
4454                                                   LValue &LV,
4455                                                   bool IncludeMember = true) {
4456   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4457 
4458   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4459     if (Info.noteFailure()) {
4460       MemberPtr MemPtr;
4461       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4462     }
4463     return nullptr;
4464   }
4465 
4466   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4467                                    BO->getRHS(), IncludeMember);
4468 }
4469 
4470 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4471 /// the provided lvalue, which currently refers to the base object.
4472 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4473                                     LValue &Result) {
4474   SubobjectDesignator &D = Result.Designator;
4475   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4476     return false;
4477 
4478   QualType TargetQT = E->getType();
4479   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4480     TargetQT = PT->getPointeeType();
4481 
4482   // Check this cast lands within the final derived-to-base subobject path.
4483   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4484     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4485       << D.MostDerivedType << TargetQT;
4486     return false;
4487   }
4488 
4489   // Check the type of the final cast. We don't need to check the path,
4490   // since a cast can only be formed if the path is unique.
4491   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4492   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4493   const CXXRecordDecl *FinalType;
4494   if (NewEntriesSize == D.MostDerivedPathLength)
4495     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4496   else
4497     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4498   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4499     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4500       << D.MostDerivedType << TargetQT;
4501     return false;
4502   }
4503 
4504   // Truncate the lvalue to the appropriate derived class.
4505   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4506 }
4507 
4508 /// Get the value to use for a default-initialized object of type T.
4509 /// Return false if it encounters something invalid.
4510 static bool getDefaultInitValue(QualType T, APValue &Result) {
4511   bool Success = true;
4512   if (auto *RD = T->getAsCXXRecordDecl()) {
4513     if (RD->isInvalidDecl()) {
4514       Result = APValue();
4515       return false;
4516     }
4517     if (RD->isUnion()) {
4518       Result = APValue((const FieldDecl *)nullptr);
4519       return true;
4520     }
4521     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4522                      std::distance(RD->field_begin(), RD->field_end()));
4523 
4524     unsigned Index = 0;
4525     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4526                                                   End = RD->bases_end();
4527          I != End; ++I, ++Index)
4528       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4529 
4530     for (const auto *I : RD->fields()) {
4531       if (I->isUnnamedBitfield())
4532         continue;
4533       Success &= getDefaultInitValue(I->getType(),
4534                                      Result.getStructField(I->getFieldIndex()));
4535     }
4536     return Success;
4537   }
4538 
4539   if (auto *AT =
4540           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4541     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4542     if (Result.hasArrayFiller())
4543       Success &=
4544           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4545 
4546     return Success;
4547   }
4548 
4549   Result = APValue::IndeterminateValue();
4550   return true;
4551 }
4552 
4553 namespace {
4554 enum EvalStmtResult {
4555   /// Evaluation failed.
4556   ESR_Failed,
4557   /// Hit a 'return' statement.
4558   ESR_Returned,
4559   /// Evaluation succeeded.
4560   ESR_Succeeded,
4561   /// Hit a 'continue' statement.
4562   ESR_Continue,
4563   /// Hit a 'break' statement.
4564   ESR_Break,
4565   /// Still scanning for 'case' or 'default' statement.
4566   ESR_CaseNotFound
4567 };
4568 }
4569 
4570 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4571   // We don't need to evaluate the initializer for a static local.
4572   if (!VD->hasLocalStorage())
4573     return true;
4574 
4575   LValue Result;
4576   APValue &Val =
4577       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4578 
4579   const Expr *InitE = VD->getInit();
4580   if (!InitE)
4581     return getDefaultInitValue(VD->getType(), Val);
4582 
4583   if (InitE->isValueDependent())
4584     return false;
4585 
4586   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4587     // Wipe out any partially-computed value, to allow tracking that this
4588     // evaluation failed.
4589     Val = APValue();
4590     return false;
4591   }
4592 
4593   return true;
4594 }
4595 
4596 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4597   bool OK = true;
4598 
4599   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4600     OK &= EvaluateVarDecl(Info, VD);
4601 
4602   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4603     for (auto *BD : DD->bindings())
4604       if (auto *VD = BD->getHoldingVar())
4605         OK &= EvaluateDecl(Info, VD);
4606 
4607   return OK;
4608 }
4609 
4610 
4611 /// Evaluate a condition (either a variable declaration or an expression).
4612 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4613                          const Expr *Cond, bool &Result) {
4614   FullExpressionRAII Scope(Info);
4615   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4616     return false;
4617   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4618     return false;
4619   return Scope.destroy();
4620 }
4621 
4622 namespace {
4623 /// A location where the result (returned value) of evaluating a
4624 /// statement should be stored.
4625 struct StmtResult {
4626   /// The APValue that should be filled in with the returned value.
4627   APValue &Value;
4628   /// The location containing the result, if any (used to support RVO).
4629   const LValue *Slot;
4630 };
4631 
4632 struct TempVersionRAII {
4633   CallStackFrame &Frame;
4634 
4635   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4636     Frame.pushTempVersion();
4637   }
4638 
4639   ~TempVersionRAII() {
4640     Frame.popTempVersion();
4641   }
4642 };
4643 
4644 }
4645 
4646 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4647                                    const Stmt *S,
4648                                    const SwitchCase *SC = nullptr);
4649 
4650 /// Evaluate the body of a loop, and translate the result as appropriate.
4651 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4652                                        const Stmt *Body,
4653                                        const SwitchCase *Case = nullptr) {
4654   BlockScopeRAII Scope(Info);
4655 
4656   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4657   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4658     ESR = ESR_Failed;
4659 
4660   switch (ESR) {
4661   case ESR_Break:
4662     return ESR_Succeeded;
4663   case ESR_Succeeded:
4664   case ESR_Continue:
4665     return ESR_Continue;
4666   case ESR_Failed:
4667   case ESR_Returned:
4668   case ESR_CaseNotFound:
4669     return ESR;
4670   }
4671   llvm_unreachable("Invalid EvalStmtResult!");
4672 }
4673 
4674 /// Evaluate a switch statement.
4675 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4676                                      const SwitchStmt *SS) {
4677   BlockScopeRAII Scope(Info);
4678 
4679   // Evaluate the switch condition.
4680   APSInt Value;
4681   {
4682     if (const Stmt *Init = SS->getInit()) {
4683       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4684       if (ESR != ESR_Succeeded) {
4685         if (ESR != ESR_Failed && !Scope.destroy())
4686           ESR = ESR_Failed;
4687         return ESR;
4688       }
4689     }
4690 
4691     FullExpressionRAII CondScope(Info);
4692     if (SS->getConditionVariable() &&
4693         !EvaluateDecl(Info, SS->getConditionVariable()))
4694       return ESR_Failed;
4695     if (!EvaluateInteger(SS->getCond(), Value, Info))
4696       return ESR_Failed;
4697     if (!CondScope.destroy())
4698       return ESR_Failed;
4699   }
4700 
4701   // Find the switch case corresponding to the value of the condition.
4702   // FIXME: Cache this lookup.
4703   const SwitchCase *Found = nullptr;
4704   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4705        SC = SC->getNextSwitchCase()) {
4706     if (isa<DefaultStmt>(SC)) {
4707       Found = SC;
4708       continue;
4709     }
4710 
4711     const CaseStmt *CS = cast<CaseStmt>(SC);
4712     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4713     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4714                               : LHS;
4715     if (LHS <= Value && Value <= RHS) {
4716       Found = SC;
4717       break;
4718     }
4719   }
4720 
4721   if (!Found)
4722     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4723 
4724   // Search the switch body for the switch case and evaluate it from there.
4725   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4726   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4727     return ESR_Failed;
4728 
4729   switch (ESR) {
4730   case ESR_Break:
4731     return ESR_Succeeded;
4732   case ESR_Succeeded:
4733   case ESR_Continue:
4734   case ESR_Failed:
4735   case ESR_Returned:
4736     return ESR;
4737   case ESR_CaseNotFound:
4738     // This can only happen if the switch case is nested within a statement
4739     // expression. We have no intention of supporting that.
4740     Info.FFDiag(Found->getBeginLoc(),
4741                 diag::note_constexpr_stmt_expr_unsupported);
4742     return ESR_Failed;
4743   }
4744   llvm_unreachable("Invalid EvalStmtResult!");
4745 }
4746 
4747 // Evaluate a statement.
4748 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4749                                    const Stmt *S, const SwitchCase *Case) {
4750   if (!Info.nextStep(S))
4751     return ESR_Failed;
4752 
4753   // If we're hunting down a 'case' or 'default' label, recurse through
4754   // substatements until we hit the label.
4755   if (Case) {
4756     switch (S->getStmtClass()) {
4757     case Stmt::CompoundStmtClass:
4758       // FIXME: Precompute which substatement of a compound statement we
4759       // would jump to, and go straight there rather than performing a
4760       // linear scan each time.
4761     case Stmt::LabelStmtClass:
4762     case Stmt::AttributedStmtClass:
4763     case Stmt::DoStmtClass:
4764       break;
4765 
4766     case Stmt::CaseStmtClass:
4767     case Stmt::DefaultStmtClass:
4768       if (Case == S)
4769         Case = nullptr;
4770       break;
4771 
4772     case Stmt::IfStmtClass: {
4773       // FIXME: Precompute which side of an 'if' we would jump to, and go
4774       // straight there rather than scanning both sides.
4775       const IfStmt *IS = cast<IfStmt>(S);
4776 
4777       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4778       // preceded by our switch label.
4779       BlockScopeRAII Scope(Info);
4780 
4781       // Step into the init statement in case it brings an (uninitialized)
4782       // variable into scope.
4783       if (const Stmt *Init = IS->getInit()) {
4784         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4785         if (ESR != ESR_CaseNotFound) {
4786           assert(ESR != ESR_Succeeded);
4787           return ESR;
4788         }
4789       }
4790 
4791       // Condition variable must be initialized if it exists.
4792       // FIXME: We can skip evaluating the body if there's a condition
4793       // variable, as there can't be any case labels within it.
4794       // (The same is true for 'for' statements.)
4795 
4796       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4797       if (ESR == ESR_Failed)
4798         return ESR;
4799       if (ESR != ESR_CaseNotFound)
4800         return Scope.destroy() ? ESR : ESR_Failed;
4801       if (!IS->getElse())
4802         return ESR_CaseNotFound;
4803 
4804       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4805       if (ESR == ESR_Failed)
4806         return ESR;
4807       if (ESR != ESR_CaseNotFound)
4808         return Scope.destroy() ? ESR : ESR_Failed;
4809       return ESR_CaseNotFound;
4810     }
4811 
4812     case Stmt::WhileStmtClass: {
4813       EvalStmtResult ESR =
4814           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4815       if (ESR != ESR_Continue)
4816         return ESR;
4817       break;
4818     }
4819 
4820     case Stmt::ForStmtClass: {
4821       const ForStmt *FS = cast<ForStmt>(S);
4822       BlockScopeRAII Scope(Info);
4823 
4824       // Step into the init statement in case it brings an (uninitialized)
4825       // variable into scope.
4826       if (const Stmt *Init = FS->getInit()) {
4827         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4828         if (ESR != ESR_CaseNotFound) {
4829           assert(ESR != ESR_Succeeded);
4830           return ESR;
4831         }
4832       }
4833 
4834       EvalStmtResult ESR =
4835           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4836       if (ESR != ESR_Continue)
4837         return ESR;
4838       if (FS->getInc()) {
4839         FullExpressionRAII IncScope(Info);
4840         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4841           return ESR_Failed;
4842       }
4843       break;
4844     }
4845 
4846     case Stmt::DeclStmtClass: {
4847       // Start the lifetime of any uninitialized variables we encounter. They
4848       // might be used by the selected branch of the switch.
4849       const DeclStmt *DS = cast<DeclStmt>(S);
4850       for (const auto *D : DS->decls()) {
4851         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4852           if (VD->hasLocalStorage() && !VD->getInit())
4853             if (!EvaluateVarDecl(Info, VD))
4854               return ESR_Failed;
4855           // FIXME: If the variable has initialization that can't be jumped
4856           // over, bail out of any immediately-surrounding compound-statement
4857           // too. There can't be any case labels here.
4858         }
4859       }
4860       return ESR_CaseNotFound;
4861     }
4862 
4863     default:
4864       return ESR_CaseNotFound;
4865     }
4866   }
4867 
4868   switch (S->getStmtClass()) {
4869   default:
4870     if (const Expr *E = dyn_cast<Expr>(S)) {
4871       // Don't bother evaluating beyond an expression-statement which couldn't
4872       // be evaluated.
4873       // FIXME: Do we need the FullExpressionRAII object here?
4874       // VisitExprWithCleanups should create one when necessary.
4875       FullExpressionRAII Scope(Info);
4876       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4877         return ESR_Failed;
4878       return ESR_Succeeded;
4879     }
4880 
4881     Info.FFDiag(S->getBeginLoc());
4882     return ESR_Failed;
4883 
4884   case Stmt::NullStmtClass:
4885     return ESR_Succeeded;
4886 
4887   case Stmt::DeclStmtClass: {
4888     const DeclStmt *DS = cast<DeclStmt>(S);
4889     for (const auto *D : DS->decls()) {
4890       // Each declaration initialization is its own full-expression.
4891       FullExpressionRAII Scope(Info);
4892       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4893         return ESR_Failed;
4894       if (!Scope.destroy())
4895         return ESR_Failed;
4896     }
4897     return ESR_Succeeded;
4898   }
4899 
4900   case Stmt::ReturnStmtClass: {
4901     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4902     FullExpressionRAII Scope(Info);
4903     if (RetExpr &&
4904         !(Result.Slot
4905               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4906               : Evaluate(Result.Value, Info, RetExpr)))
4907       return ESR_Failed;
4908     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4909   }
4910 
4911   case Stmt::CompoundStmtClass: {
4912     BlockScopeRAII Scope(Info);
4913 
4914     const CompoundStmt *CS = cast<CompoundStmt>(S);
4915     for (const auto *BI : CS->body()) {
4916       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4917       if (ESR == ESR_Succeeded)
4918         Case = nullptr;
4919       else if (ESR != ESR_CaseNotFound) {
4920         if (ESR != ESR_Failed && !Scope.destroy())
4921           return ESR_Failed;
4922         return ESR;
4923       }
4924     }
4925     if (Case)
4926       return ESR_CaseNotFound;
4927     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4928   }
4929 
4930   case Stmt::IfStmtClass: {
4931     const IfStmt *IS = cast<IfStmt>(S);
4932 
4933     // Evaluate the condition, as either a var decl or as an expression.
4934     BlockScopeRAII Scope(Info);
4935     if (const Stmt *Init = IS->getInit()) {
4936       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4937       if (ESR != ESR_Succeeded) {
4938         if (ESR != ESR_Failed && !Scope.destroy())
4939           return ESR_Failed;
4940         return ESR;
4941       }
4942     }
4943     bool Cond;
4944     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4945       return ESR_Failed;
4946 
4947     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4948       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4949       if (ESR != ESR_Succeeded) {
4950         if (ESR != ESR_Failed && !Scope.destroy())
4951           return ESR_Failed;
4952         return ESR;
4953       }
4954     }
4955     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4956   }
4957 
4958   case Stmt::WhileStmtClass: {
4959     const WhileStmt *WS = cast<WhileStmt>(S);
4960     while (true) {
4961       BlockScopeRAII Scope(Info);
4962       bool Continue;
4963       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4964                         Continue))
4965         return ESR_Failed;
4966       if (!Continue)
4967         break;
4968 
4969       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4970       if (ESR != ESR_Continue) {
4971         if (ESR != ESR_Failed && !Scope.destroy())
4972           return ESR_Failed;
4973         return ESR;
4974       }
4975       if (!Scope.destroy())
4976         return ESR_Failed;
4977     }
4978     return ESR_Succeeded;
4979   }
4980 
4981   case Stmt::DoStmtClass: {
4982     const DoStmt *DS = cast<DoStmt>(S);
4983     bool Continue;
4984     do {
4985       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4986       if (ESR != ESR_Continue)
4987         return ESR;
4988       Case = nullptr;
4989 
4990       FullExpressionRAII CondScope(Info);
4991       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4992           !CondScope.destroy())
4993         return ESR_Failed;
4994     } while (Continue);
4995     return ESR_Succeeded;
4996   }
4997 
4998   case Stmt::ForStmtClass: {
4999     const ForStmt *FS = cast<ForStmt>(S);
5000     BlockScopeRAII ForScope(Info);
5001     if (FS->getInit()) {
5002       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5003       if (ESR != ESR_Succeeded) {
5004         if (ESR != ESR_Failed && !ForScope.destroy())
5005           return ESR_Failed;
5006         return ESR;
5007       }
5008     }
5009     while (true) {
5010       BlockScopeRAII IterScope(Info);
5011       bool Continue = true;
5012       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5013                                          FS->getCond(), Continue))
5014         return ESR_Failed;
5015       if (!Continue)
5016         break;
5017 
5018       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5019       if (ESR != ESR_Continue) {
5020         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5021           return ESR_Failed;
5022         return ESR;
5023       }
5024 
5025       if (FS->getInc()) {
5026         FullExpressionRAII IncScope(Info);
5027         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5028           return ESR_Failed;
5029       }
5030 
5031       if (!IterScope.destroy())
5032         return ESR_Failed;
5033     }
5034     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5035   }
5036 
5037   case Stmt::CXXForRangeStmtClass: {
5038     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5039     BlockScopeRAII Scope(Info);
5040 
5041     // Evaluate the init-statement if present.
5042     if (FS->getInit()) {
5043       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5044       if (ESR != ESR_Succeeded) {
5045         if (ESR != ESR_Failed && !Scope.destroy())
5046           return ESR_Failed;
5047         return ESR;
5048       }
5049     }
5050 
5051     // Initialize the __range variable.
5052     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5053     if (ESR != ESR_Succeeded) {
5054       if (ESR != ESR_Failed && !Scope.destroy())
5055         return ESR_Failed;
5056       return ESR;
5057     }
5058 
5059     // Create the __begin and __end iterators.
5060     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5061     if (ESR != ESR_Succeeded) {
5062       if (ESR != ESR_Failed && !Scope.destroy())
5063         return ESR_Failed;
5064       return ESR;
5065     }
5066     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5067     if (ESR != ESR_Succeeded) {
5068       if (ESR != ESR_Failed && !Scope.destroy())
5069         return ESR_Failed;
5070       return ESR;
5071     }
5072 
5073     while (true) {
5074       // Condition: __begin != __end.
5075       {
5076         bool Continue = true;
5077         FullExpressionRAII CondExpr(Info);
5078         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5079           return ESR_Failed;
5080         if (!Continue)
5081           break;
5082       }
5083 
5084       // User's variable declaration, initialized by *__begin.
5085       BlockScopeRAII InnerScope(Info);
5086       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5087       if (ESR != ESR_Succeeded) {
5088         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5089           return ESR_Failed;
5090         return ESR;
5091       }
5092 
5093       // Loop body.
5094       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5095       if (ESR != ESR_Continue) {
5096         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5097           return ESR_Failed;
5098         return ESR;
5099       }
5100 
5101       // Increment: ++__begin
5102       if (!EvaluateIgnoredValue(Info, FS->getInc()))
5103         return ESR_Failed;
5104 
5105       if (!InnerScope.destroy())
5106         return ESR_Failed;
5107     }
5108 
5109     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5110   }
5111 
5112   case Stmt::SwitchStmtClass:
5113     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5114 
5115   case Stmt::ContinueStmtClass:
5116     return ESR_Continue;
5117 
5118   case Stmt::BreakStmtClass:
5119     return ESR_Break;
5120 
5121   case Stmt::LabelStmtClass:
5122     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5123 
5124   case Stmt::AttributedStmtClass:
5125     // As a general principle, C++11 attributes can be ignored without
5126     // any semantic impact.
5127     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5128                         Case);
5129 
5130   case Stmt::CaseStmtClass:
5131   case Stmt::DefaultStmtClass:
5132     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5133   case Stmt::CXXTryStmtClass:
5134     // Evaluate try blocks by evaluating all sub statements.
5135     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5136   }
5137 }
5138 
5139 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5140 /// default constructor. If so, we'll fold it whether or not it's marked as
5141 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5142 /// so we need special handling.
5143 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5144                                            const CXXConstructorDecl *CD,
5145                                            bool IsValueInitialization) {
5146   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5147     return false;
5148 
5149   // Value-initialization does not call a trivial default constructor, so such a
5150   // call is a core constant expression whether or not the constructor is
5151   // constexpr.
5152   if (!CD->isConstexpr() && !IsValueInitialization) {
5153     if (Info.getLangOpts().CPlusPlus11) {
5154       // FIXME: If DiagDecl is an implicitly-declared special member function,
5155       // we should be much more explicit about why it's not constexpr.
5156       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5157         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5158       Info.Note(CD->getLocation(), diag::note_declared_at);
5159     } else {
5160       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5161     }
5162   }
5163   return true;
5164 }
5165 
5166 /// CheckConstexprFunction - Check that a function can be called in a constant
5167 /// expression.
5168 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5169                                    const FunctionDecl *Declaration,
5170                                    const FunctionDecl *Definition,
5171                                    const Stmt *Body) {
5172   // Potential constant expressions can contain calls to declared, but not yet
5173   // defined, constexpr functions.
5174   if (Info.checkingPotentialConstantExpression() && !Definition &&
5175       Declaration->isConstexpr())
5176     return false;
5177 
5178   // Bail out if the function declaration itself is invalid.  We will
5179   // have produced a relevant diagnostic while parsing it, so just
5180   // note the problematic sub-expression.
5181   if (Declaration->isInvalidDecl()) {
5182     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5183     return false;
5184   }
5185 
5186   // DR1872: An instantiated virtual constexpr function can't be called in a
5187   // constant expression (prior to C++20). We can still constant-fold such a
5188   // call.
5189   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5190       cast<CXXMethodDecl>(Declaration)->isVirtual())
5191     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5192 
5193   if (Definition && Definition->isInvalidDecl()) {
5194     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5195     return false;
5196   }
5197 
5198   if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5199     for (const auto *InitExpr : CtorDecl->inits()) {
5200       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5201         return false;
5202     }
5203   }
5204 
5205   // Can we evaluate this function call?
5206   if (Definition && Definition->isConstexpr() && Body)
5207     return true;
5208 
5209   if (Info.getLangOpts().CPlusPlus11) {
5210     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5211 
5212     // If this function is not constexpr because it is an inherited
5213     // non-constexpr constructor, diagnose that directly.
5214     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5215     if (CD && CD->isInheritingConstructor()) {
5216       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5217       if (!Inherited->isConstexpr())
5218         DiagDecl = CD = Inherited;
5219     }
5220 
5221     // FIXME: If DiagDecl is an implicitly-declared special member function
5222     // or an inheriting constructor, we should be much more explicit about why
5223     // it's not constexpr.
5224     if (CD && CD->isInheritingConstructor())
5225       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5226         << CD->getInheritedConstructor().getConstructor()->getParent();
5227     else
5228       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5229         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5230     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5231   } else {
5232     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5233   }
5234   return false;
5235 }
5236 
5237 namespace {
5238 struct CheckDynamicTypeHandler {
5239   AccessKinds AccessKind;
5240   typedef bool result_type;
5241   bool failed() { return false; }
5242   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5243   bool found(APSInt &Value, QualType SubobjType) { return true; }
5244   bool found(APFloat &Value, QualType SubobjType) { return true; }
5245 };
5246 } // end anonymous namespace
5247 
5248 /// Check that we can access the notional vptr of an object / determine its
5249 /// dynamic type.
5250 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5251                              AccessKinds AK, bool Polymorphic) {
5252   if (This.Designator.Invalid)
5253     return false;
5254 
5255   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5256 
5257   if (!Obj)
5258     return false;
5259 
5260   if (!Obj.Value) {
5261     // The object is not usable in constant expressions, so we can't inspect
5262     // its value to see if it's in-lifetime or what the active union members
5263     // are. We can still check for a one-past-the-end lvalue.
5264     if (This.Designator.isOnePastTheEnd() ||
5265         This.Designator.isMostDerivedAnUnsizedArray()) {
5266       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5267                          ? diag::note_constexpr_access_past_end
5268                          : diag::note_constexpr_access_unsized_array)
5269           << AK;
5270       return false;
5271     } else if (Polymorphic) {
5272       // Conservatively refuse to perform a polymorphic operation if we would
5273       // not be able to read a notional 'vptr' value.
5274       APValue Val;
5275       This.moveInto(Val);
5276       QualType StarThisType =
5277           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5278       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5279           << AK << Val.getAsString(Info.Ctx, StarThisType);
5280       return false;
5281     }
5282     return true;
5283   }
5284 
5285   CheckDynamicTypeHandler Handler{AK};
5286   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5287 }
5288 
5289 /// Check that the pointee of the 'this' pointer in a member function call is
5290 /// either within its lifetime or in its period of construction or destruction.
5291 static bool
5292 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5293                                      const LValue &This,
5294                                      const CXXMethodDecl *NamedMember) {
5295   return checkDynamicType(
5296       Info, E, This,
5297       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5298 }
5299 
5300 struct DynamicType {
5301   /// The dynamic class type of the object.
5302   const CXXRecordDecl *Type;
5303   /// The corresponding path length in the lvalue.
5304   unsigned PathLength;
5305 };
5306 
5307 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5308                                              unsigned PathLength) {
5309   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5310       Designator.Entries.size() && "invalid path length");
5311   return (PathLength == Designator.MostDerivedPathLength)
5312              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5313              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5314 }
5315 
5316 /// Determine the dynamic type of an object.
5317 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5318                                                 LValue &This, AccessKinds AK) {
5319   // If we don't have an lvalue denoting an object of class type, there is no
5320   // meaningful dynamic type. (We consider objects of non-class type to have no
5321   // dynamic type.)
5322   if (!checkDynamicType(Info, E, This, AK, true))
5323     return None;
5324 
5325   // Refuse to compute a dynamic type in the presence of virtual bases. This
5326   // shouldn't happen other than in constant-folding situations, since literal
5327   // types can't have virtual bases.
5328   //
5329   // Note that consumers of DynamicType assume that the type has no virtual
5330   // bases, and will need modifications if this restriction is relaxed.
5331   const CXXRecordDecl *Class =
5332       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5333   if (!Class || Class->getNumVBases()) {
5334     Info.FFDiag(E);
5335     return None;
5336   }
5337 
5338   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5339   // binary search here instead. But the overwhelmingly common case is that
5340   // we're not in the middle of a constructor, so it probably doesn't matter
5341   // in practice.
5342   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5343   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5344        PathLength <= Path.size(); ++PathLength) {
5345     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5346                                       Path.slice(0, PathLength))) {
5347     case ConstructionPhase::Bases:
5348     case ConstructionPhase::DestroyingBases:
5349       // We're constructing or destroying a base class. This is not the dynamic
5350       // type.
5351       break;
5352 
5353     case ConstructionPhase::None:
5354     case ConstructionPhase::AfterBases:
5355     case ConstructionPhase::AfterFields:
5356     case ConstructionPhase::Destroying:
5357       // We've finished constructing the base classes and not yet started
5358       // destroying them again, so this is the dynamic type.
5359       return DynamicType{getBaseClassType(This.Designator, PathLength),
5360                          PathLength};
5361     }
5362   }
5363 
5364   // CWG issue 1517: we're constructing a base class of the object described by
5365   // 'This', so that object has not yet begun its period of construction and
5366   // any polymorphic operation on it results in undefined behavior.
5367   Info.FFDiag(E);
5368   return None;
5369 }
5370 
5371 /// Perform virtual dispatch.
5372 static const CXXMethodDecl *HandleVirtualDispatch(
5373     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5374     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5375   Optional<DynamicType> DynType = ComputeDynamicType(
5376       Info, E, This,
5377       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5378   if (!DynType)
5379     return nullptr;
5380 
5381   // Find the final overrider. It must be declared in one of the classes on the
5382   // path from the dynamic type to the static type.
5383   // FIXME: If we ever allow literal types to have virtual base classes, that
5384   // won't be true.
5385   const CXXMethodDecl *Callee = Found;
5386   unsigned PathLength = DynType->PathLength;
5387   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5388     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5389     const CXXMethodDecl *Overrider =
5390         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5391     if (Overrider) {
5392       Callee = Overrider;
5393       break;
5394     }
5395   }
5396 
5397   // C++2a [class.abstract]p6:
5398   //   the effect of making a virtual call to a pure virtual function [...] is
5399   //   undefined
5400   if (Callee->isPure()) {
5401     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5402     Info.Note(Callee->getLocation(), diag::note_declared_at);
5403     return nullptr;
5404   }
5405 
5406   // If necessary, walk the rest of the path to determine the sequence of
5407   // covariant adjustment steps to apply.
5408   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5409                                        Found->getReturnType())) {
5410     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5411     for (unsigned CovariantPathLength = PathLength + 1;
5412          CovariantPathLength != This.Designator.Entries.size();
5413          ++CovariantPathLength) {
5414       const CXXRecordDecl *NextClass =
5415           getBaseClassType(This.Designator, CovariantPathLength);
5416       const CXXMethodDecl *Next =
5417           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5418       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5419                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5420         CovariantAdjustmentPath.push_back(Next->getReturnType());
5421     }
5422     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5423                                          CovariantAdjustmentPath.back()))
5424       CovariantAdjustmentPath.push_back(Found->getReturnType());
5425   }
5426 
5427   // Perform 'this' adjustment.
5428   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5429     return nullptr;
5430 
5431   return Callee;
5432 }
5433 
5434 /// Perform the adjustment from a value returned by a virtual function to
5435 /// a value of the statically expected type, which may be a pointer or
5436 /// reference to a base class of the returned type.
5437 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5438                                             APValue &Result,
5439                                             ArrayRef<QualType> Path) {
5440   assert(Result.isLValue() &&
5441          "unexpected kind of APValue for covariant return");
5442   if (Result.isNullPointer())
5443     return true;
5444 
5445   LValue LVal;
5446   LVal.setFrom(Info.Ctx, Result);
5447 
5448   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5449   for (unsigned I = 1; I != Path.size(); ++I) {
5450     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5451     assert(OldClass && NewClass && "unexpected kind of covariant return");
5452     if (OldClass != NewClass &&
5453         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5454       return false;
5455     OldClass = NewClass;
5456   }
5457 
5458   LVal.moveInto(Result);
5459   return true;
5460 }
5461 
5462 /// Determine whether \p Base, which is known to be a direct base class of
5463 /// \p Derived, is a public base class.
5464 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5465                               const CXXRecordDecl *Base) {
5466   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5467     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5468     if (BaseClass && declaresSameEntity(BaseClass, Base))
5469       return BaseSpec.getAccessSpecifier() == AS_public;
5470   }
5471   llvm_unreachable("Base is not a direct base of Derived");
5472 }
5473 
5474 /// Apply the given dynamic cast operation on the provided lvalue.
5475 ///
5476 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5477 /// to find a suitable target subobject.
5478 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5479                               LValue &Ptr) {
5480   // We can't do anything with a non-symbolic pointer value.
5481   SubobjectDesignator &D = Ptr.Designator;
5482   if (D.Invalid)
5483     return false;
5484 
5485   // C++ [expr.dynamic.cast]p6:
5486   //   If v is a null pointer value, the result is a null pointer value.
5487   if (Ptr.isNullPointer() && !E->isGLValue())
5488     return true;
5489 
5490   // For all the other cases, we need the pointer to point to an object within
5491   // its lifetime / period of construction / destruction, and we need to know
5492   // its dynamic type.
5493   Optional<DynamicType> DynType =
5494       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5495   if (!DynType)
5496     return false;
5497 
5498   // C++ [expr.dynamic.cast]p7:
5499   //   If T is "pointer to cv void", then the result is a pointer to the most
5500   //   derived object
5501   if (E->getType()->isVoidPointerType())
5502     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5503 
5504   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5505   assert(C && "dynamic_cast target is not void pointer nor class");
5506   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5507 
5508   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5509     // C++ [expr.dynamic.cast]p9:
5510     if (!E->isGLValue()) {
5511       //   The value of a failed cast to pointer type is the null pointer value
5512       //   of the required result type.
5513       Ptr.setNull(Info.Ctx, E->getType());
5514       return true;
5515     }
5516 
5517     //   A failed cast to reference type throws [...] std::bad_cast.
5518     unsigned DiagKind;
5519     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5520                    DynType->Type->isDerivedFrom(C)))
5521       DiagKind = 0;
5522     else if (!Paths || Paths->begin() == Paths->end())
5523       DiagKind = 1;
5524     else if (Paths->isAmbiguous(CQT))
5525       DiagKind = 2;
5526     else {
5527       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5528       DiagKind = 3;
5529     }
5530     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5531         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5532         << Info.Ctx.getRecordType(DynType->Type)
5533         << E->getType().getUnqualifiedType();
5534     return false;
5535   };
5536 
5537   // Runtime check, phase 1:
5538   //   Walk from the base subobject towards the derived object looking for the
5539   //   target type.
5540   for (int PathLength = Ptr.Designator.Entries.size();
5541        PathLength >= (int)DynType->PathLength; --PathLength) {
5542     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5543     if (declaresSameEntity(Class, C))
5544       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5545     // We can only walk across public inheritance edges.
5546     if (PathLength > (int)DynType->PathLength &&
5547         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5548                            Class))
5549       return RuntimeCheckFailed(nullptr);
5550   }
5551 
5552   // Runtime check, phase 2:
5553   //   Search the dynamic type for an unambiguous public base of type C.
5554   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5555                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5556   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5557       Paths.front().Access == AS_public) {
5558     // Downcast to the dynamic type...
5559     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5560       return false;
5561     // ... then upcast to the chosen base class subobject.
5562     for (CXXBasePathElement &Elem : Paths.front())
5563       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5564         return false;
5565     return true;
5566   }
5567 
5568   // Otherwise, the runtime check fails.
5569   return RuntimeCheckFailed(&Paths);
5570 }
5571 
5572 namespace {
5573 struct StartLifetimeOfUnionMemberHandler {
5574   EvalInfo &Info;
5575   const Expr *LHSExpr;
5576   const FieldDecl *Field;
5577   bool DuringInit;
5578   bool Failed = false;
5579   static const AccessKinds AccessKind = AK_Assign;
5580 
5581   typedef bool result_type;
5582   bool failed() { return Failed; }
5583   bool found(APValue &Subobj, QualType SubobjType) {
5584     // We are supposed to perform no initialization but begin the lifetime of
5585     // the object. We interpret that as meaning to do what default
5586     // initialization of the object would do if all constructors involved were
5587     // trivial:
5588     //  * All base, non-variant member, and array element subobjects' lifetimes
5589     //    begin
5590     //  * No variant members' lifetimes begin
5591     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5592     assert(SubobjType->isUnionType());
5593     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5594       // This union member is already active. If it's also in-lifetime, there's
5595       // nothing to do.
5596       if (Subobj.getUnionValue().hasValue())
5597         return true;
5598     } else if (DuringInit) {
5599       // We're currently in the process of initializing a different union
5600       // member.  If we carried on, that initialization would attempt to
5601       // store to an inactive union member, resulting in undefined behavior.
5602       Info.FFDiag(LHSExpr,
5603                   diag::note_constexpr_union_member_change_during_init);
5604       return false;
5605     }
5606     APValue Result;
5607     Failed = !getDefaultInitValue(Field->getType(), Result);
5608     Subobj.setUnion(Field, Result);
5609     return true;
5610   }
5611   bool found(APSInt &Value, QualType SubobjType) {
5612     llvm_unreachable("wrong value kind for union object");
5613   }
5614   bool found(APFloat &Value, QualType SubobjType) {
5615     llvm_unreachable("wrong value kind for union object");
5616   }
5617 };
5618 } // end anonymous namespace
5619 
5620 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5621 
5622 /// Handle a builtin simple-assignment or a call to a trivial assignment
5623 /// operator whose left-hand side might involve a union member access. If it
5624 /// does, implicitly start the lifetime of any accessed union elements per
5625 /// C++20 [class.union]5.
5626 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5627                                           const LValue &LHS) {
5628   if (LHS.InvalidBase || LHS.Designator.Invalid)
5629     return false;
5630 
5631   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5632   // C++ [class.union]p5:
5633   //   define the set S(E) of subexpressions of E as follows:
5634   unsigned PathLength = LHS.Designator.Entries.size();
5635   for (const Expr *E = LHSExpr; E != nullptr;) {
5636     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5637     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5638       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5639       // Note that we can't implicitly start the lifetime of a reference,
5640       // so we don't need to proceed any further if we reach one.
5641       if (!FD || FD->getType()->isReferenceType())
5642         break;
5643 
5644       //    ... and also contains A.B if B names a union member ...
5645       if (FD->getParent()->isUnion()) {
5646         //    ... of a non-class, non-array type, or of a class type with a
5647         //    trivial default constructor that is not deleted, or an array of
5648         //    such types.
5649         auto *RD =
5650             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5651         if (!RD || RD->hasTrivialDefaultConstructor())
5652           UnionPathLengths.push_back({PathLength - 1, FD});
5653       }
5654 
5655       E = ME->getBase();
5656       --PathLength;
5657       assert(declaresSameEntity(FD,
5658                                 LHS.Designator.Entries[PathLength]
5659                                     .getAsBaseOrMember().getPointer()));
5660 
5661       //   -- If E is of the form A[B] and is interpreted as a built-in array
5662       //      subscripting operator, S(E) is [S(the array operand, if any)].
5663     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5664       // Step over an ArrayToPointerDecay implicit cast.
5665       auto *Base = ASE->getBase()->IgnoreImplicit();
5666       if (!Base->getType()->isArrayType())
5667         break;
5668 
5669       E = Base;
5670       --PathLength;
5671 
5672     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5673       // Step over a derived-to-base conversion.
5674       E = ICE->getSubExpr();
5675       if (ICE->getCastKind() == CK_NoOp)
5676         continue;
5677       if (ICE->getCastKind() != CK_DerivedToBase &&
5678           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5679         break;
5680       // Walk path backwards as we walk up from the base to the derived class.
5681       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5682         --PathLength;
5683         (void)Elt;
5684         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5685                                   LHS.Designator.Entries[PathLength]
5686                                       .getAsBaseOrMember().getPointer()));
5687       }
5688 
5689     //   -- Otherwise, S(E) is empty.
5690     } else {
5691       break;
5692     }
5693   }
5694 
5695   // Common case: no unions' lifetimes are started.
5696   if (UnionPathLengths.empty())
5697     return true;
5698 
5699   //   if modification of X [would access an inactive union member], an object
5700   //   of the type of X is implicitly created
5701   CompleteObject Obj =
5702       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5703   if (!Obj)
5704     return false;
5705   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5706            llvm::reverse(UnionPathLengths)) {
5707     // Form a designator for the union object.
5708     SubobjectDesignator D = LHS.Designator;
5709     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5710 
5711     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5712                       ConstructionPhase::AfterBases;
5713     StartLifetimeOfUnionMemberHandler StartLifetime{
5714         Info, LHSExpr, LengthAndField.second, DuringInit};
5715     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5716       return false;
5717   }
5718 
5719   return true;
5720 }
5721 
5722 namespace {
5723 typedef SmallVector<APValue, 8> ArgVector;
5724 }
5725 
5726 /// EvaluateArgs - Evaluate the arguments to a function call.
5727 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5728                          EvalInfo &Info, const FunctionDecl *Callee) {
5729   bool Success = true;
5730   llvm::SmallBitVector ForbiddenNullArgs;
5731   if (Callee->hasAttr<NonNullAttr>()) {
5732     ForbiddenNullArgs.resize(Args.size());
5733     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5734       if (!Attr->args_size()) {
5735         ForbiddenNullArgs.set();
5736         break;
5737       } else
5738         for (auto Idx : Attr->args()) {
5739           unsigned ASTIdx = Idx.getASTIndex();
5740           if (ASTIdx >= Args.size())
5741             continue;
5742           ForbiddenNullArgs[ASTIdx] = 1;
5743         }
5744     }
5745   }
5746   // FIXME: This is the wrong evaluation order for an assignment operator
5747   // called via operator syntax.
5748   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5749     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5750       // If we're checking for a potential constant expression, evaluate all
5751       // initializers even if some of them fail.
5752       if (!Info.noteFailure())
5753         return false;
5754       Success = false;
5755     } else if (!ForbiddenNullArgs.empty() &&
5756                ForbiddenNullArgs[Idx] &&
5757                ArgValues[Idx].isLValue() &&
5758                ArgValues[Idx].isNullPointer()) {
5759       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5760       if (!Info.noteFailure())
5761         return false;
5762       Success = false;
5763     }
5764   }
5765   return Success;
5766 }
5767 
5768 /// Evaluate a function call.
5769 static bool HandleFunctionCall(SourceLocation CallLoc,
5770                                const FunctionDecl *Callee, const LValue *This,
5771                                ArrayRef<const Expr*> Args, const Stmt *Body,
5772                                EvalInfo &Info, APValue &Result,
5773                                const LValue *ResultSlot) {
5774   ArgVector ArgValues(Args.size());
5775   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5776     return false;
5777 
5778   if (!Info.CheckCallLimit(CallLoc))
5779     return false;
5780 
5781   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5782 
5783   // For a trivial copy or move assignment, perform an APValue copy. This is
5784   // essential for unions, where the operations performed by the assignment
5785   // operator cannot be represented as statements.
5786   //
5787   // Skip this for non-union classes with no fields; in that case, the defaulted
5788   // copy/move does not actually read the object.
5789   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5790   if (MD && MD->isDefaulted() &&
5791       (MD->getParent()->isUnion() ||
5792        (MD->isTrivial() &&
5793         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5794     assert(This &&
5795            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5796     LValue RHS;
5797     RHS.setFrom(Info.Ctx, ArgValues[0]);
5798     APValue RHSValue;
5799     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5800                                         RHSValue, MD->getParent()->isUnion()))
5801       return false;
5802     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
5803         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5804       return false;
5805     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5806                           RHSValue))
5807       return false;
5808     This->moveInto(Result);
5809     return true;
5810   } else if (MD && isLambdaCallOperator(MD)) {
5811     // We're in a lambda; determine the lambda capture field maps unless we're
5812     // just constexpr checking a lambda's call operator. constexpr checking is
5813     // done before the captures have been added to the closure object (unless
5814     // we're inferring constexpr-ness), so we don't have access to them in this
5815     // case. But since we don't need the captures to constexpr check, we can
5816     // just ignore them.
5817     if (!Info.checkingPotentialConstantExpression())
5818       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5819                                         Frame.LambdaThisCaptureField);
5820   }
5821 
5822   StmtResult Ret = {Result, ResultSlot};
5823   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5824   if (ESR == ESR_Succeeded) {
5825     if (Callee->getReturnType()->isVoidType())
5826       return true;
5827     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5828   }
5829   return ESR == ESR_Returned;
5830 }
5831 
5832 /// Evaluate a constructor call.
5833 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5834                                   APValue *ArgValues,
5835                                   const CXXConstructorDecl *Definition,
5836                                   EvalInfo &Info, APValue &Result) {
5837   SourceLocation CallLoc = E->getExprLoc();
5838   if (!Info.CheckCallLimit(CallLoc))
5839     return false;
5840 
5841   const CXXRecordDecl *RD = Definition->getParent();
5842   if (RD->getNumVBases()) {
5843     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5844     return false;
5845   }
5846 
5847   EvalInfo::EvaluatingConstructorRAII EvalObj(
5848       Info,
5849       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5850       RD->getNumBases());
5851   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5852 
5853   // FIXME: Creating an APValue just to hold a nonexistent return value is
5854   // wasteful.
5855   APValue RetVal;
5856   StmtResult Ret = {RetVal, nullptr};
5857 
5858   // If it's a delegating constructor, delegate.
5859   if (Definition->isDelegatingConstructor()) {
5860     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5861     {
5862       FullExpressionRAII InitScope(Info);
5863       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5864           !InitScope.destroy())
5865         return false;
5866     }
5867     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5868   }
5869 
5870   // For a trivial copy or move constructor, perform an APValue copy. This is
5871   // essential for unions (or classes with anonymous union members), where the
5872   // operations performed by the constructor cannot be represented by
5873   // ctor-initializers.
5874   //
5875   // Skip this for empty non-union classes; we should not perform an
5876   // lvalue-to-rvalue conversion on them because their copy constructor does not
5877   // actually read them.
5878   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5879       (Definition->getParent()->isUnion() ||
5880        (Definition->isTrivial() &&
5881         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5882     LValue RHS;
5883     RHS.setFrom(Info.Ctx, ArgValues[0]);
5884     return handleLValueToRValueConversion(
5885         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5886         RHS, Result, Definition->getParent()->isUnion());
5887   }
5888 
5889   // Reserve space for the struct members.
5890   if (!Result.hasValue()) {
5891     if (!RD->isUnion())
5892       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5893                        std::distance(RD->field_begin(), RD->field_end()));
5894     else
5895       // A union starts with no active member.
5896       Result = APValue((const FieldDecl*)nullptr);
5897   }
5898 
5899   if (RD->isInvalidDecl()) return false;
5900   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5901 
5902   // A scope for temporaries lifetime-extended by reference members.
5903   BlockScopeRAII LifetimeExtendedScope(Info);
5904 
5905   bool Success = true;
5906   unsigned BasesSeen = 0;
5907 #ifndef NDEBUG
5908   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5909 #endif
5910   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5911   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5912     // We might be initializing the same field again if this is an indirect
5913     // field initialization.
5914     if (FieldIt == RD->field_end() ||
5915         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5916       assert(Indirect && "fields out of order?");
5917       return;
5918     }
5919 
5920     // Default-initialize any fields with no explicit initializer.
5921     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5922       assert(FieldIt != RD->field_end() && "missing field?");
5923       if (!FieldIt->isUnnamedBitfield())
5924         Success &= getDefaultInitValue(
5925             FieldIt->getType(),
5926             Result.getStructField(FieldIt->getFieldIndex()));
5927     }
5928     ++FieldIt;
5929   };
5930   for (const auto *I : Definition->inits()) {
5931     LValue Subobject = This;
5932     LValue SubobjectParent = This;
5933     APValue *Value = &Result;
5934 
5935     // Determine the subobject to initialize.
5936     FieldDecl *FD = nullptr;
5937     if (I->isBaseInitializer()) {
5938       QualType BaseType(I->getBaseClass(), 0);
5939 #ifndef NDEBUG
5940       // Non-virtual base classes are initialized in the order in the class
5941       // definition. We have already checked for virtual base classes.
5942       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5943       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5944              "base class initializers not in expected order");
5945       ++BaseIt;
5946 #endif
5947       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5948                                   BaseType->getAsCXXRecordDecl(), &Layout))
5949         return false;
5950       Value = &Result.getStructBase(BasesSeen++);
5951     } else if ((FD = I->getMember())) {
5952       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5953         return false;
5954       if (RD->isUnion()) {
5955         Result = APValue(FD);
5956         Value = &Result.getUnionValue();
5957       } else {
5958         SkipToField(FD, false);
5959         Value = &Result.getStructField(FD->getFieldIndex());
5960       }
5961     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5962       // Walk the indirect field decl's chain to find the object to initialize,
5963       // and make sure we've initialized every step along it.
5964       auto IndirectFieldChain = IFD->chain();
5965       for (auto *C : IndirectFieldChain) {
5966         FD = cast<FieldDecl>(C);
5967         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5968         // Switch the union field if it differs. This happens if we had
5969         // preceding zero-initialization, and we're now initializing a union
5970         // subobject other than the first.
5971         // FIXME: In this case, the values of the other subobjects are
5972         // specified, since zero-initialization sets all padding bits to zero.
5973         if (!Value->hasValue() ||
5974             (Value->isUnion() && Value->getUnionField() != FD)) {
5975           if (CD->isUnion())
5976             *Value = APValue(FD);
5977           else
5978             // FIXME: This immediately starts the lifetime of all members of
5979             // an anonymous struct. It would be preferable to strictly start
5980             // member lifetime in initialization order.
5981             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
5982         }
5983         // Store Subobject as its parent before updating it for the last element
5984         // in the chain.
5985         if (C == IndirectFieldChain.back())
5986           SubobjectParent = Subobject;
5987         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5988           return false;
5989         if (CD->isUnion())
5990           Value = &Value->getUnionValue();
5991         else {
5992           if (C == IndirectFieldChain.front() && !RD->isUnion())
5993             SkipToField(FD, true);
5994           Value = &Value->getStructField(FD->getFieldIndex());
5995         }
5996       }
5997     } else {
5998       llvm_unreachable("unknown base initializer kind");
5999     }
6000 
6001     // Need to override This for implicit field initializers as in this case
6002     // This refers to innermost anonymous struct/union containing initializer,
6003     // not to currently constructed class.
6004     const Expr *Init = I->getInit();
6005     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6006                                   isa<CXXDefaultInitExpr>(Init));
6007     FullExpressionRAII InitScope(Info);
6008     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6009         (FD && FD->isBitField() &&
6010          !truncateBitfieldValue(Info, Init, *Value, FD))) {
6011       // If we're checking for a potential constant expression, evaluate all
6012       // initializers even if some of them fail.
6013       if (!Info.noteFailure())
6014         return false;
6015       Success = false;
6016     }
6017 
6018     // This is the point at which the dynamic type of the object becomes this
6019     // class type.
6020     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6021       EvalObj.finishedConstructingBases();
6022   }
6023 
6024   // Default-initialize any remaining fields.
6025   if (!RD->isUnion()) {
6026     for (; FieldIt != RD->field_end(); ++FieldIt) {
6027       if (!FieldIt->isUnnamedBitfield())
6028         Success &= getDefaultInitValue(
6029             FieldIt->getType(),
6030             Result.getStructField(FieldIt->getFieldIndex()));
6031     }
6032   }
6033 
6034   EvalObj.finishedConstructingFields();
6035 
6036   return Success &&
6037          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6038          LifetimeExtendedScope.destroy();
6039 }
6040 
6041 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6042                                   ArrayRef<const Expr*> Args,
6043                                   const CXXConstructorDecl *Definition,
6044                                   EvalInfo &Info, APValue &Result) {
6045   ArgVector ArgValues(Args.size());
6046   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
6047     return false;
6048 
6049   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
6050                                Info, Result);
6051 }
6052 
6053 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6054                                   const LValue &This, APValue &Value,
6055                                   QualType T) {
6056   // Objects can only be destroyed while they're within their lifetimes.
6057   // FIXME: We have no representation for whether an object of type nullptr_t
6058   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6059   // as indeterminate instead?
6060   if (Value.isAbsent() && !T->isNullPtrType()) {
6061     APValue Printable;
6062     This.moveInto(Printable);
6063     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6064       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6065     return false;
6066   }
6067 
6068   // Invent an expression for location purposes.
6069   // FIXME: We shouldn't need to do this.
6070   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6071 
6072   // For arrays, destroy elements right-to-left.
6073   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6074     uint64_t Size = CAT->getSize().getZExtValue();
6075     QualType ElemT = CAT->getElementType();
6076 
6077     LValue ElemLV = This;
6078     ElemLV.addArray(Info, &LocE, CAT);
6079     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6080       return false;
6081 
6082     // Ensure that we have actual array elements available to destroy; the
6083     // destructors might mutate the value, so we can't run them on the array
6084     // filler.
6085     if (Size && Size > Value.getArrayInitializedElts())
6086       expandArray(Value, Value.getArraySize() - 1);
6087 
6088     for (; Size != 0; --Size) {
6089       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6090       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6091           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6092         return false;
6093     }
6094 
6095     // End the lifetime of this array now.
6096     Value = APValue();
6097     return true;
6098   }
6099 
6100   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6101   if (!RD) {
6102     if (T.isDestructedType()) {
6103       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6104       return false;
6105     }
6106 
6107     Value = APValue();
6108     return true;
6109   }
6110 
6111   if (RD->getNumVBases()) {
6112     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6113     return false;
6114   }
6115 
6116   const CXXDestructorDecl *DD = RD->getDestructor();
6117   if (!DD && !RD->hasTrivialDestructor()) {
6118     Info.FFDiag(CallLoc);
6119     return false;
6120   }
6121 
6122   if (!DD || DD->isTrivial() ||
6123       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6124     // A trivial destructor just ends the lifetime of the object. Check for
6125     // this case before checking for a body, because we might not bother
6126     // building a body for a trivial destructor. Note that it doesn't matter
6127     // whether the destructor is constexpr in this case; all trivial
6128     // destructors are constexpr.
6129     //
6130     // If an anonymous union would be destroyed, some enclosing destructor must
6131     // have been explicitly defined, and the anonymous union destruction should
6132     // have no effect.
6133     Value = APValue();
6134     return true;
6135   }
6136 
6137   if (!Info.CheckCallLimit(CallLoc))
6138     return false;
6139 
6140   const FunctionDecl *Definition = nullptr;
6141   const Stmt *Body = DD->getBody(Definition);
6142 
6143   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6144     return false;
6145 
6146   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
6147 
6148   // We're now in the period of destruction of this object.
6149   unsigned BasesLeft = RD->getNumBases();
6150   EvalInfo::EvaluatingDestructorRAII EvalObj(
6151       Info,
6152       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6153   if (!EvalObj.DidInsert) {
6154     // C++2a [class.dtor]p19:
6155     //   the behavior is undefined if the destructor is invoked for an object
6156     //   whose lifetime has ended
6157     // (Note that formally the lifetime ends when the period of destruction
6158     // begins, even though certain uses of the object remain valid until the
6159     // period of destruction ends.)
6160     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6161     return false;
6162   }
6163 
6164   // FIXME: Creating an APValue just to hold a nonexistent return value is
6165   // wasteful.
6166   APValue RetVal;
6167   StmtResult Ret = {RetVal, nullptr};
6168   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6169     return false;
6170 
6171   // A union destructor does not implicitly destroy its members.
6172   if (RD->isUnion())
6173     return true;
6174 
6175   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6176 
6177   // We don't have a good way to iterate fields in reverse, so collect all the
6178   // fields first and then walk them backwards.
6179   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6180   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6181     if (FD->isUnnamedBitfield())
6182       continue;
6183 
6184     LValue Subobject = This;
6185     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6186       return false;
6187 
6188     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6189     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6190                                FD->getType()))
6191       return false;
6192   }
6193 
6194   if (BasesLeft != 0)
6195     EvalObj.startedDestroyingBases();
6196 
6197   // Destroy base classes in reverse order.
6198   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6199     --BasesLeft;
6200 
6201     QualType BaseType = Base.getType();
6202     LValue Subobject = This;
6203     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6204                                 BaseType->getAsCXXRecordDecl(), &Layout))
6205       return false;
6206 
6207     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6208     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6209                                BaseType))
6210       return false;
6211   }
6212   assert(BasesLeft == 0 && "NumBases was wrong?");
6213 
6214   // The period of destruction ends now. The object is gone.
6215   Value = APValue();
6216   return true;
6217 }
6218 
6219 namespace {
6220 struct DestroyObjectHandler {
6221   EvalInfo &Info;
6222   const Expr *E;
6223   const LValue &This;
6224   const AccessKinds AccessKind;
6225 
6226   typedef bool result_type;
6227   bool failed() { return false; }
6228   bool found(APValue &Subobj, QualType SubobjType) {
6229     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6230                                  SubobjType);
6231   }
6232   bool found(APSInt &Value, QualType SubobjType) {
6233     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6234     return false;
6235   }
6236   bool found(APFloat &Value, QualType SubobjType) {
6237     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6238     return false;
6239   }
6240 };
6241 }
6242 
6243 /// Perform a destructor or pseudo-destructor call on the given object, which
6244 /// might in general not be a complete object.
6245 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6246                               const LValue &This, QualType ThisType) {
6247   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6248   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6249   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6250 }
6251 
6252 /// Destroy and end the lifetime of the given complete object.
6253 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6254                               APValue::LValueBase LVBase, APValue &Value,
6255                               QualType T) {
6256   // If we've had an unmodeled side-effect, we can't rely on mutable state
6257   // (such as the object we're about to destroy) being correct.
6258   if (Info.EvalStatus.HasSideEffects)
6259     return false;
6260 
6261   LValue LV;
6262   LV.set({LVBase});
6263   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6264 }
6265 
6266 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6267 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6268                                   LValue &Result) {
6269   if (Info.checkingPotentialConstantExpression() ||
6270       Info.SpeculativeEvaluationDepth)
6271     return false;
6272 
6273   // This is permitted only within a call to std::allocator<T>::allocate.
6274   auto Caller = Info.getStdAllocatorCaller("allocate");
6275   if (!Caller) {
6276     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6277                                      ? diag::note_constexpr_new_untyped
6278                                      : diag::note_constexpr_new);
6279     return false;
6280   }
6281 
6282   QualType ElemType = Caller.ElemType;
6283   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6284     Info.FFDiag(E->getExprLoc(),
6285                 diag::note_constexpr_new_not_complete_object_type)
6286         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6287     return false;
6288   }
6289 
6290   APSInt ByteSize;
6291   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6292     return false;
6293   bool IsNothrow = false;
6294   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6295     EvaluateIgnoredValue(Info, E->getArg(I));
6296     IsNothrow |= E->getType()->isNothrowT();
6297   }
6298 
6299   CharUnits ElemSize;
6300   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6301     return false;
6302   APInt Size, Remainder;
6303   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6304   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6305   if (Remainder != 0) {
6306     // This likely indicates a bug in the implementation of 'std::allocator'.
6307     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6308         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6309     return false;
6310   }
6311 
6312   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6313     if (IsNothrow) {
6314       Result.setNull(Info.Ctx, E->getType());
6315       return true;
6316     }
6317 
6318     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6319     return false;
6320   }
6321 
6322   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6323                                                      ArrayType::Normal, 0);
6324   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6325   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6326   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6327   return true;
6328 }
6329 
6330 static bool hasVirtualDestructor(QualType T) {
6331   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6332     if (CXXDestructorDecl *DD = RD->getDestructor())
6333       return DD->isVirtual();
6334   return false;
6335 }
6336 
6337 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6338   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6339     if (CXXDestructorDecl *DD = RD->getDestructor())
6340       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6341   return nullptr;
6342 }
6343 
6344 /// Check that the given object is a suitable pointer to a heap allocation that
6345 /// still exists and is of the right kind for the purpose of a deletion.
6346 ///
6347 /// On success, returns the heap allocation to deallocate. On failure, produces
6348 /// a diagnostic and returns None.
6349 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6350                                             const LValue &Pointer,
6351                                             DynAlloc::Kind DeallocKind) {
6352   auto PointerAsString = [&] {
6353     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6354   };
6355 
6356   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6357   if (!DA) {
6358     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6359         << PointerAsString();
6360     if (Pointer.Base)
6361       NoteLValueLocation(Info, Pointer.Base);
6362     return None;
6363   }
6364 
6365   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6366   if (!Alloc) {
6367     Info.FFDiag(E, diag::note_constexpr_double_delete);
6368     return None;
6369   }
6370 
6371   QualType AllocType = Pointer.Base.getDynamicAllocType();
6372   if (DeallocKind != (*Alloc)->getKind()) {
6373     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6374         << DeallocKind << (*Alloc)->getKind() << AllocType;
6375     NoteLValueLocation(Info, Pointer.Base);
6376     return None;
6377   }
6378 
6379   bool Subobject = false;
6380   if (DeallocKind == DynAlloc::New) {
6381     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6382                 Pointer.Designator.isOnePastTheEnd();
6383   } else {
6384     Subobject = Pointer.Designator.Entries.size() != 1 ||
6385                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6386   }
6387   if (Subobject) {
6388     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6389         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6390     return None;
6391   }
6392 
6393   return Alloc;
6394 }
6395 
6396 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6397 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6398   if (Info.checkingPotentialConstantExpression() ||
6399       Info.SpeculativeEvaluationDepth)
6400     return false;
6401 
6402   // This is permitted only within a call to std::allocator<T>::deallocate.
6403   if (!Info.getStdAllocatorCaller("deallocate")) {
6404     Info.FFDiag(E->getExprLoc());
6405     return true;
6406   }
6407 
6408   LValue Pointer;
6409   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6410     return false;
6411   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6412     EvaluateIgnoredValue(Info, E->getArg(I));
6413 
6414   if (Pointer.Designator.Invalid)
6415     return false;
6416 
6417   // Deleting a null pointer has no effect.
6418   if (Pointer.isNullPointer())
6419     return true;
6420 
6421   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6422     return false;
6423 
6424   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6425   return true;
6426 }
6427 
6428 //===----------------------------------------------------------------------===//
6429 // Generic Evaluation
6430 //===----------------------------------------------------------------------===//
6431 namespace {
6432 
6433 class BitCastBuffer {
6434   // FIXME: We're going to need bit-level granularity when we support
6435   // bit-fields.
6436   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6437   // we don't support a host or target where that is the case. Still, we should
6438   // use a more generic type in case we ever do.
6439   SmallVector<Optional<unsigned char>, 32> Bytes;
6440 
6441   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6442                 "Need at least 8 bit unsigned char");
6443 
6444   bool TargetIsLittleEndian;
6445 
6446 public:
6447   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6448       : Bytes(Width.getQuantity()),
6449         TargetIsLittleEndian(TargetIsLittleEndian) {}
6450 
6451   LLVM_NODISCARD
6452   bool readObject(CharUnits Offset, CharUnits Width,
6453                   SmallVectorImpl<unsigned char> &Output) const {
6454     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6455       // If a byte of an integer is uninitialized, then the whole integer is
6456       // uninitalized.
6457       if (!Bytes[I.getQuantity()])
6458         return false;
6459       Output.push_back(*Bytes[I.getQuantity()]);
6460     }
6461     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6462       std::reverse(Output.begin(), Output.end());
6463     return true;
6464   }
6465 
6466   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6467     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6468       std::reverse(Input.begin(), Input.end());
6469 
6470     size_t Index = 0;
6471     for (unsigned char Byte : Input) {
6472       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6473       Bytes[Offset.getQuantity() + Index] = Byte;
6474       ++Index;
6475     }
6476   }
6477 
6478   size_t size() { return Bytes.size(); }
6479 };
6480 
6481 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6482 /// target would represent the value at runtime.
6483 class APValueToBufferConverter {
6484   EvalInfo &Info;
6485   BitCastBuffer Buffer;
6486   const CastExpr *BCE;
6487 
6488   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6489                            const CastExpr *BCE)
6490       : Info(Info),
6491         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6492         BCE(BCE) {}
6493 
6494   bool visit(const APValue &Val, QualType Ty) {
6495     return visit(Val, Ty, CharUnits::fromQuantity(0));
6496   }
6497 
6498   // Write out Val with type Ty into Buffer starting at Offset.
6499   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6500     assert((size_t)Offset.getQuantity() <= Buffer.size());
6501 
6502     // As a special case, nullptr_t has an indeterminate value.
6503     if (Ty->isNullPtrType())
6504       return true;
6505 
6506     // Dig through Src to find the byte at SrcOffset.
6507     switch (Val.getKind()) {
6508     case APValue::Indeterminate:
6509     case APValue::None:
6510       return true;
6511 
6512     case APValue::Int:
6513       return visitInt(Val.getInt(), Ty, Offset);
6514     case APValue::Float:
6515       return visitFloat(Val.getFloat(), Ty, Offset);
6516     case APValue::Array:
6517       return visitArray(Val, Ty, Offset);
6518     case APValue::Struct:
6519       return visitRecord(Val, Ty, Offset);
6520 
6521     case APValue::ComplexInt:
6522     case APValue::ComplexFloat:
6523     case APValue::Vector:
6524     case APValue::FixedPoint:
6525       // FIXME: We should support these.
6526 
6527     case APValue::Union:
6528     case APValue::MemberPointer:
6529     case APValue::AddrLabelDiff: {
6530       Info.FFDiag(BCE->getBeginLoc(),
6531                   diag::note_constexpr_bit_cast_unsupported_type)
6532           << Ty;
6533       return false;
6534     }
6535 
6536     case APValue::LValue:
6537       llvm_unreachable("LValue subobject in bit_cast?");
6538     }
6539     llvm_unreachable("Unhandled APValue::ValueKind");
6540   }
6541 
6542   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6543     const RecordDecl *RD = Ty->getAsRecordDecl();
6544     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6545 
6546     // Visit the base classes.
6547     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6548       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6549         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6550         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6551 
6552         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6553                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6554           return false;
6555       }
6556     }
6557 
6558     // Visit the fields.
6559     unsigned FieldIdx = 0;
6560     for (FieldDecl *FD : RD->fields()) {
6561       if (FD->isBitField()) {
6562         Info.FFDiag(BCE->getBeginLoc(),
6563                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6564         return false;
6565       }
6566 
6567       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6568 
6569       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6570              "only bit-fields can have sub-char alignment");
6571       CharUnits FieldOffset =
6572           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6573       QualType FieldTy = FD->getType();
6574       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6575         return false;
6576       ++FieldIdx;
6577     }
6578 
6579     return true;
6580   }
6581 
6582   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6583     const auto *CAT =
6584         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6585     if (!CAT)
6586       return false;
6587 
6588     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6589     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6590     unsigned ArraySize = Val.getArraySize();
6591     // First, initialize the initialized elements.
6592     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6593       const APValue &SubObj = Val.getArrayInitializedElt(I);
6594       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6595         return false;
6596     }
6597 
6598     // Next, initialize the rest of the array using the filler.
6599     if (Val.hasArrayFiller()) {
6600       const APValue &Filler = Val.getArrayFiller();
6601       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6602         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6603           return false;
6604       }
6605     }
6606 
6607     return true;
6608   }
6609 
6610   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6611     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6612     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6613     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6614     Buffer.writeObject(Offset, Bytes);
6615     return true;
6616   }
6617 
6618   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6619     APSInt AsInt(Val.bitcastToAPInt());
6620     return visitInt(AsInt, Ty, Offset);
6621   }
6622 
6623 public:
6624   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6625                                          const CastExpr *BCE) {
6626     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6627     APValueToBufferConverter Converter(Info, DstSize, BCE);
6628     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6629       return None;
6630     return Converter.Buffer;
6631   }
6632 };
6633 
6634 /// Write an BitCastBuffer into an APValue.
6635 class BufferToAPValueConverter {
6636   EvalInfo &Info;
6637   const BitCastBuffer &Buffer;
6638   const CastExpr *BCE;
6639 
6640   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6641                            const CastExpr *BCE)
6642       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6643 
6644   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6645   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6646   // Ideally this will be unreachable.
6647   llvm::NoneType unsupportedType(QualType Ty) {
6648     Info.FFDiag(BCE->getBeginLoc(),
6649                 diag::note_constexpr_bit_cast_unsupported_type)
6650         << Ty;
6651     return None;
6652   }
6653 
6654   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6655                           const EnumType *EnumSugar = nullptr) {
6656     if (T->isNullPtrType()) {
6657       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6658       return APValue((Expr *)nullptr,
6659                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6660                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6661     }
6662 
6663     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6664     SmallVector<uint8_t, 8> Bytes;
6665     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6666       // If this is std::byte or unsigned char, then its okay to store an
6667       // indeterminate value.
6668       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6669       bool IsUChar =
6670           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6671                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6672       if (!IsStdByte && !IsUChar) {
6673         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6674         Info.FFDiag(BCE->getExprLoc(),
6675                     diag::note_constexpr_bit_cast_indet_dest)
6676             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6677         return None;
6678       }
6679 
6680       return APValue::IndeterminateValue();
6681     }
6682 
6683     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6684     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6685 
6686     if (T->isIntegralOrEnumerationType()) {
6687       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6688       return APValue(Val);
6689     }
6690 
6691     if (T->isRealFloatingType()) {
6692       const llvm::fltSemantics &Semantics =
6693           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6694       return APValue(APFloat(Semantics, Val));
6695     }
6696 
6697     return unsupportedType(QualType(T, 0));
6698   }
6699 
6700   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6701     const RecordDecl *RD = RTy->getAsRecordDecl();
6702     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6703 
6704     unsigned NumBases = 0;
6705     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6706       NumBases = CXXRD->getNumBases();
6707 
6708     APValue ResultVal(APValue::UninitStruct(), NumBases,
6709                       std::distance(RD->field_begin(), RD->field_end()));
6710 
6711     // Visit the base classes.
6712     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6713       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6714         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6715         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6716         if (BaseDecl->isEmpty() ||
6717             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6718           continue;
6719 
6720         Optional<APValue> SubObj = visitType(
6721             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6722         if (!SubObj)
6723           return None;
6724         ResultVal.getStructBase(I) = *SubObj;
6725       }
6726     }
6727 
6728     // Visit the fields.
6729     unsigned FieldIdx = 0;
6730     for (FieldDecl *FD : RD->fields()) {
6731       // FIXME: We don't currently support bit-fields. A lot of the logic for
6732       // this is in CodeGen, so we need to factor it around.
6733       if (FD->isBitField()) {
6734         Info.FFDiag(BCE->getBeginLoc(),
6735                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6736         return None;
6737       }
6738 
6739       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6740       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6741 
6742       CharUnits FieldOffset =
6743           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6744           Offset;
6745       QualType FieldTy = FD->getType();
6746       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6747       if (!SubObj)
6748         return None;
6749       ResultVal.getStructField(FieldIdx) = *SubObj;
6750       ++FieldIdx;
6751     }
6752 
6753     return ResultVal;
6754   }
6755 
6756   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6757     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6758     assert(!RepresentationType.isNull() &&
6759            "enum forward decl should be caught by Sema");
6760     const auto *AsBuiltin =
6761         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6762     // Recurse into the underlying type. Treat std::byte transparently as
6763     // unsigned char.
6764     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6765   }
6766 
6767   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6768     size_t Size = Ty->getSize().getLimitedValue();
6769     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6770 
6771     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6772     for (size_t I = 0; I != Size; ++I) {
6773       Optional<APValue> ElementValue =
6774           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6775       if (!ElementValue)
6776         return None;
6777       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6778     }
6779 
6780     return ArrayValue;
6781   }
6782 
6783   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6784     return unsupportedType(QualType(Ty, 0));
6785   }
6786 
6787   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6788     QualType Can = Ty.getCanonicalType();
6789 
6790     switch (Can->getTypeClass()) {
6791 #define TYPE(Class, Base)                                                      \
6792   case Type::Class:                                                            \
6793     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6794 #define ABSTRACT_TYPE(Class, Base)
6795 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6796   case Type::Class:                                                            \
6797     llvm_unreachable("non-canonical type should be impossible!");
6798 #define DEPENDENT_TYPE(Class, Base)                                            \
6799   case Type::Class:                                                            \
6800     llvm_unreachable(                                                          \
6801         "dependent types aren't supported in the constant evaluator!");
6802 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6803   case Type::Class:                                                            \
6804     llvm_unreachable("either dependent or not canonical!");
6805 #include "clang/AST/TypeNodes.inc"
6806     }
6807     llvm_unreachable("Unhandled Type::TypeClass");
6808   }
6809 
6810 public:
6811   // Pull out a full value of type DstType.
6812   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6813                                    const CastExpr *BCE) {
6814     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6815     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6816   }
6817 };
6818 
6819 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6820                                                  QualType Ty, EvalInfo *Info,
6821                                                  const ASTContext &Ctx,
6822                                                  bool CheckingDest) {
6823   Ty = Ty.getCanonicalType();
6824 
6825   auto diag = [&](int Reason) {
6826     if (Info)
6827       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6828           << CheckingDest << (Reason == 4) << Reason;
6829     return false;
6830   };
6831   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6832     if (Info)
6833       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6834           << NoteTy << Construct << Ty;
6835     return false;
6836   };
6837 
6838   if (Ty->isUnionType())
6839     return diag(0);
6840   if (Ty->isPointerType())
6841     return diag(1);
6842   if (Ty->isMemberPointerType())
6843     return diag(2);
6844   if (Ty.isVolatileQualified())
6845     return diag(3);
6846 
6847   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6848     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6849       for (CXXBaseSpecifier &BS : CXXRD->bases())
6850         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6851                                                   CheckingDest))
6852           return note(1, BS.getType(), BS.getBeginLoc());
6853     }
6854     for (FieldDecl *FD : Record->fields()) {
6855       if (FD->getType()->isReferenceType())
6856         return diag(4);
6857       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6858                                                 CheckingDest))
6859         return note(0, FD->getType(), FD->getBeginLoc());
6860     }
6861   }
6862 
6863   if (Ty->isArrayType() &&
6864       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6865                                             Info, Ctx, CheckingDest))
6866     return false;
6867 
6868   return true;
6869 }
6870 
6871 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6872                                              const ASTContext &Ctx,
6873                                              const CastExpr *BCE) {
6874   bool DestOK = checkBitCastConstexprEligibilityType(
6875       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6876   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6877                                 BCE->getBeginLoc(),
6878                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6879   return SourceOK;
6880 }
6881 
6882 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6883                                         APValue &SourceValue,
6884                                         const CastExpr *BCE) {
6885   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6886          "no host or target supports non 8-bit chars");
6887   assert(SourceValue.isLValue() &&
6888          "LValueToRValueBitcast requires an lvalue operand!");
6889 
6890   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6891     return false;
6892 
6893   LValue SourceLValue;
6894   APValue SourceRValue;
6895   SourceLValue.setFrom(Info.Ctx, SourceValue);
6896   if (!handleLValueToRValueConversion(
6897           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6898           SourceRValue, /*WantObjectRepresentation=*/true))
6899     return false;
6900 
6901   // Read out SourceValue into a char buffer.
6902   Optional<BitCastBuffer> Buffer =
6903       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6904   if (!Buffer)
6905     return false;
6906 
6907   // Write out the buffer into a new APValue.
6908   Optional<APValue> MaybeDestValue =
6909       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6910   if (!MaybeDestValue)
6911     return false;
6912 
6913   DestValue = std::move(*MaybeDestValue);
6914   return true;
6915 }
6916 
6917 template <class Derived>
6918 class ExprEvaluatorBase
6919   : public ConstStmtVisitor<Derived, bool> {
6920 private:
6921   Derived &getDerived() { return static_cast<Derived&>(*this); }
6922   bool DerivedSuccess(const APValue &V, const Expr *E) {
6923     return getDerived().Success(V, E);
6924   }
6925   bool DerivedZeroInitialization(const Expr *E) {
6926     return getDerived().ZeroInitialization(E);
6927   }
6928 
6929   // Check whether a conditional operator with a non-constant condition is a
6930   // potential constant expression. If neither arm is a potential constant
6931   // expression, then the conditional operator is not either.
6932   template<typename ConditionalOperator>
6933   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6934     assert(Info.checkingPotentialConstantExpression());
6935 
6936     // Speculatively evaluate both arms.
6937     SmallVector<PartialDiagnosticAt, 8> Diag;
6938     {
6939       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6940       StmtVisitorTy::Visit(E->getFalseExpr());
6941       if (Diag.empty())
6942         return;
6943     }
6944 
6945     {
6946       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6947       Diag.clear();
6948       StmtVisitorTy::Visit(E->getTrueExpr());
6949       if (Diag.empty())
6950         return;
6951     }
6952 
6953     Error(E, diag::note_constexpr_conditional_never_const);
6954   }
6955 
6956 
6957   template<typename ConditionalOperator>
6958   bool HandleConditionalOperator(const ConditionalOperator *E) {
6959     bool BoolResult;
6960     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6961       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6962         CheckPotentialConstantConditional(E);
6963         return false;
6964       }
6965       if (Info.noteFailure()) {
6966         StmtVisitorTy::Visit(E->getTrueExpr());
6967         StmtVisitorTy::Visit(E->getFalseExpr());
6968       }
6969       return false;
6970     }
6971 
6972     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6973     return StmtVisitorTy::Visit(EvalExpr);
6974   }
6975 
6976 protected:
6977   EvalInfo &Info;
6978   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6979   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6980 
6981   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6982     return Info.CCEDiag(E, D);
6983   }
6984 
6985   bool ZeroInitialization(const Expr *E) { return Error(E); }
6986 
6987 public:
6988   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6989 
6990   EvalInfo &getEvalInfo() { return Info; }
6991 
6992   /// Report an evaluation error. This should only be called when an error is
6993   /// first discovered. When propagating an error, just return false.
6994   bool Error(const Expr *E, diag::kind D) {
6995     Info.FFDiag(E, D);
6996     return false;
6997   }
6998   bool Error(const Expr *E) {
6999     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7000   }
7001 
7002   bool VisitStmt(const Stmt *) {
7003     llvm_unreachable("Expression evaluator should not be called on stmts");
7004   }
7005   bool VisitExpr(const Expr *E) {
7006     return Error(E);
7007   }
7008 
7009   bool VisitConstantExpr(const ConstantExpr *E) {
7010     if (E->hasAPValueResult())
7011       return DerivedSuccess(E->getAPValueResult(), E);
7012 
7013     return StmtVisitorTy::Visit(E->getSubExpr());
7014   }
7015 
7016   bool VisitParenExpr(const ParenExpr *E)
7017     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7018   bool VisitUnaryExtension(const UnaryOperator *E)
7019     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7020   bool VisitUnaryPlus(const UnaryOperator *E)
7021     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7022   bool VisitChooseExpr(const ChooseExpr *E)
7023     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7024   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7025     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7026   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7027     { return StmtVisitorTy::Visit(E->getReplacement()); }
7028   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7029     TempVersionRAII RAII(*Info.CurrentCall);
7030     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7031     return StmtVisitorTy::Visit(E->getExpr());
7032   }
7033   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7034     TempVersionRAII RAII(*Info.CurrentCall);
7035     // The initializer may not have been parsed yet, or might be erroneous.
7036     if (!E->getExpr())
7037       return Error(E);
7038     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7039     return StmtVisitorTy::Visit(E->getExpr());
7040   }
7041 
7042   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7043     FullExpressionRAII Scope(Info);
7044     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7045   }
7046 
7047   // Temporaries are registered when created, so we don't care about
7048   // CXXBindTemporaryExpr.
7049   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7050     return StmtVisitorTy::Visit(E->getSubExpr());
7051   }
7052 
7053   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7054     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7055     return static_cast<Derived*>(this)->VisitCastExpr(E);
7056   }
7057   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7058     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7059       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7060     return static_cast<Derived*>(this)->VisitCastExpr(E);
7061   }
7062   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7063     return static_cast<Derived*>(this)->VisitCastExpr(E);
7064   }
7065 
7066   bool VisitBinaryOperator(const BinaryOperator *E) {
7067     switch (E->getOpcode()) {
7068     default:
7069       return Error(E);
7070 
7071     case BO_Comma:
7072       VisitIgnoredValue(E->getLHS());
7073       return StmtVisitorTy::Visit(E->getRHS());
7074 
7075     case BO_PtrMemD:
7076     case BO_PtrMemI: {
7077       LValue Obj;
7078       if (!HandleMemberPointerAccess(Info, E, Obj))
7079         return false;
7080       APValue Result;
7081       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7082         return false;
7083       return DerivedSuccess(Result, E);
7084     }
7085     }
7086   }
7087 
7088   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7089     return StmtVisitorTy::Visit(E->getSemanticForm());
7090   }
7091 
7092   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7093     // Evaluate and cache the common expression. We treat it as a temporary,
7094     // even though it's not quite the same thing.
7095     LValue CommonLV;
7096     if (!Evaluate(Info.CurrentCall->createTemporary(
7097                       E->getOpaqueValue(),
7098                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
7099                       CommonLV),
7100                   Info, E->getCommon()))
7101       return false;
7102 
7103     return HandleConditionalOperator(E);
7104   }
7105 
7106   bool VisitConditionalOperator(const ConditionalOperator *E) {
7107     bool IsBcpCall = false;
7108     // If the condition (ignoring parens) is a __builtin_constant_p call,
7109     // the result is a constant expression if it can be folded without
7110     // side-effects. This is an important GNU extension. See GCC PR38377
7111     // for discussion.
7112     if (const CallExpr *CallCE =
7113           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7114       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7115         IsBcpCall = true;
7116 
7117     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7118     // constant expression; we can't check whether it's potentially foldable.
7119     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7120     // it would return 'false' in this mode.
7121     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7122       return false;
7123 
7124     FoldConstant Fold(Info, IsBcpCall);
7125     if (!HandleConditionalOperator(E)) {
7126       Fold.keepDiagnostics();
7127       return false;
7128     }
7129 
7130     return true;
7131   }
7132 
7133   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7134     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7135       return DerivedSuccess(*Value, E);
7136 
7137     const Expr *Source = E->getSourceExpr();
7138     if (!Source)
7139       return Error(E);
7140     if (Source == E) { // sanity checking.
7141       assert(0 && "OpaqueValueExpr recursively refers to itself");
7142       return Error(E);
7143     }
7144     return StmtVisitorTy::Visit(Source);
7145   }
7146 
7147   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7148     for (const Expr *SemE : E->semantics()) {
7149       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7150         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7151         // result expression: there could be two different LValues that would
7152         // refer to the same object in that case, and we can't model that.
7153         if (SemE == E->getResultExpr())
7154           return Error(E);
7155 
7156         // Unique OVEs get evaluated if and when we encounter them when
7157         // emitting the rest of the semantic form, rather than eagerly.
7158         if (OVE->isUnique())
7159           continue;
7160 
7161         LValue LV;
7162         if (!Evaluate(Info.CurrentCall->createTemporary(
7163                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
7164                       Info, OVE->getSourceExpr()))
7165           return false;
7166       } else if (SemE == E->getResultExpr()) {
7167         if (!StmtVisitorTy::Visit(SemE))
7168           return false;
7169       } else {
7170         if (!EvaluateIgnoredValue(Info, SemE))
7171           return false;
7172       }
7173     }
7174     return true;
7175   }
7176 
7177   bool VisitCallExpr(const CallExpr *E) {
7178     APValue Result;
7179     if (!handleCallExpr(E, Result, nullptr))
7180       return false;
7181     return DerivedSuccess(Result, E);
7182   }
7183 
7184   bool handleCallExpr(const CallExpr *E, APValue &Result,
7185                      const LValue *ResultSlot) {
7186     const Expr *Callee = E->getCallee()->IgnoreParens();
7187     QualType CalleeType = Callee->getType();
7188 
7189     const FunctionDecl *FD = nullptr;
7190     LValue *This = nullptr, ThisVal;
7191     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7192     bool HasQualifier = false;
7193 
7194     // Extract function decl and 'this' pointer from the callee.
7195     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7196       const CXXMethodDecl *Member = nullptr;
7197       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7198         // Explicit bound member calls, such as x.f() or p->g();
7199         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7200           return false;
7201         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7202         if (!Member)
7203           return Error(Callee);
7204         This = &ThisVal;
7205         HasQualifier = ME->hasQualifier();
7206       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7207         // Indirect bound member calls ('.*' or '->*').
7208         const ValueDecl *D =
7209             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7210         if (!D)
7211           return false;
7212         Member = dyn_cast<CXXMethodDecl>(D);
7213         if (!Member)
7214           return Error(Callee);
7215         This = &ThisVal;
7216       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7217         if (!Info.getLangOpts().CPlusPlus20)
7218           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7219         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7220                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7221       } else
7222         return Error(Callee);
7223       FD = Member;
7224     } else if (CalleeType->isFunctionPointerType()) {
7225       LValue Call;
7226       if (!EvaluatePointer(Callee, Call, Info))
7227         return false;
7228 
7229       if (!Call.getLValueOffset().isZero())
7230         return Error(Callee);
7231       FD = dyn_cast_or_null<FunctionDecl>(
7232                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
7233       if (!FD)
7234         return Error(Callee);
7235       // Don't call function pointers which have been cast to some other type.
7236       // Per DR (no number yet), the caller and callee can differ in noexcept.
7237       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7238         CalleeType->getPointeeType(), FD->getType())) {
7239         return Error(E);
7240       }
7241 
7242       // Overloaded operator calls to member functions are represented as normal
7243       // calls with '*this' as the first argument.
7244       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7245       if (MD && !MD->isStatic()) {
7246         // FIXME: When selecting an implicit conversion for an overloaded
7247         // operator delete, we sometimes try to evaluate calls to conversion
7248         // operators without a 'this' parameter!
7249         if (Args.empty())
7250           return Error(E);
7251 
7252         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7253           return false;
7254         This = &ThisVal;
7255         Args = Args.slice(1);
7256       } else if (MD && MD->isLambdaStaticInvoker()) {
7257         // Map the static invoker for the lambda back to the call operator.
7258         // Conveniently, we don't have to slice out the 'this' argument (as is
7259         // being done for the non-static case), since a static member function
7260         // doesn't have an implicit argument passed in.
7261         const CXXRecordDecl *ClosureClass = MD->getParent();
7262         assert(
7263             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7264             "Number of captures must be zero for conversion to function-ptr");
7265 
7266         const CXXMethodDecl *LambdaCallOp =
7267             ClosureClass->getLambdaCallOperator();
7268 
7269         // Set 'FD', the function that will be called below, to the call
7270         // operator.  If the closure object represents a generic lambda, find
7271         // the corresponding specialization of the call operator.
7272 
7273         if (ClosureClass->isGenericLambda()) {
7274           assert(MD->isFunctionTemplateSpecialization() &&
7275                  "A generic lambda's static-invoker function must be a "
7276                  "template specialization");
7277           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7278           FunctionTemplateDecl *CallOpTemplate =
7279               LambdaCallOp->getDescribedFunctionTemplate();
7280           void *InsertPos = nullptr;
7281           FunctionDecl *CorrespondingCallOpSpecialization =
7282               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7283           assert(CorrespondingCallOpSpecialization &&
7284                  "We must always have a function call operator specialization "
7285                  "that corresponds to our static invoker specialization");
7286           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7287         } else
7288           FD = LambdaCallOp;
7289       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7290         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7291             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7292           LValue Ptr;
7293           if (!HandleOperatorNewCall(Info, E, Ptr))
7294             return false;
7295           Ptr.moveInto(Result);
7296           return true;
7297         } else {
7298           return HandleOperatorDeleteCall(Info, E);
7299         }
7300       }
7301     } else
7302       return Error(E);
7303 
7304     SmallVector<QualType, 4> CovariantAdjustmentPath;
7305     if (This) {
7306       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7307       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7308         // Perform virtual dispatch, if necessary.
7309         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7310                                    CovariantAdjustmentPath);
7311         if (!FD)
7312           return false;
7313       } else {
7314         // Check that the 'this' pointer points to an object of the right type.
7315         // FIXME: If this is an assignment operator call, we may need to change
7316         // the active union member before we check this.
7317         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7318           return false;
7319       }
7320     }
7321 
7322     // Destructor calls are different enough that they have their own codepath.
7323     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7324       assert(This && "no 'this' pointer for destructor call");
7325       return HandleDestruction(Info, E, *This,
7326                                Info.Ctx.getRecordType(DD->getParent()));
7327     }
7328 
7329     const FunctionDecl *Definition = nullptr;
7330     Stmt *Body = FD->getBody(Definition);
7331 
7332     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7333         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7334                             Result, ResultSlot))
7335       return false;
7336 
7337     if (!CovariantAdjustmentPath.empty() &&
7338         !HandleCovariantReturnAdjustment(Info, E, Result,
7339                                          CovariantAdjustmentPath))
7340       return false;
7341 
7342     return true;
7343   }
7344 
7345   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7346     return StmtVisitorTy::Visit(E->getInitializer());
7347   }
7348   bool VisitInitListExpr(const InitListExpr *E) {
7349     if (E->getNumInits() == 0)
7350       return DerivedZeroInitialization(E);
7351     if (E->getNumInits() == 1)
7352       return StmtVisitorTy::Visit(E->getInit(0));
7353     return Error(E);
7354   }
7355   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7356     return DerivedZeroInitialization(E);
7357   }
7358   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7359     return DerivedZeroInitialization(E);
7360   }
7361   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7362     return DerivedZeroInitialization(E);
7363   }
7364 
7365   /// A member expression where the object is a prvalue is itself a prvalue.
7366   bool VisitMemberExpr(const MemberExpr *E) {
7367     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7368            "missing temporary materialization conversion");
7369     assert(!E->isArrow() && "missing call to bound member function?");
7370 
7371     APValue Val;
7372     if (!Evaluate(Val, Info, E->getBase()))
7373       return false;
7374 
7375     QualType BaseTy = E->getBase()->getType();
7376 
7377     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7378     if (!FD) return Error(E);
7379     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7380     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7381            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7382 
7383     // Note: there is no lvalue base here. But this case should only ever
7384     // happen in C or in C++98, where we cannot be evaluating a constexpr
7385     // constructor, which is the only case the base matters.
7386     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7387     SubobjectDesignator Designator(BaseTy);
7388     Designator.addDeclUnchecked(FD);
7389 
7390     APValue Result;
7391     return extractSubobject(Info, E, Obj, Designator, Result) &&
7392            DerivedSuccess(Result, E);
7393   }
7394 
7395   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7396     APValue Val;
7397     if (!Evaluate(Val, Info, E->getBase()))
7398       return false;
7399 
7400     if (Val.isVector()) {
7401       SmallVector<uint32_t, 4> Indices;
7402       E->getEncodedElementAccess(Indices);
7403       if (Indices.size() == 1) {
7404         // Return scalar.
7405         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7406       } else {
7407         // Construct new APValue vector.
7408         SmallVector<APValue, 4> Elts;
7409         for (unsigned I = 0; I < Indices.size(); ++I) {
7410           Elts.push_back(Val.getVectorElt(Indices[I]));
7411         }
7412         APValue VecResult(Elts.data(), Indices.size());
7413         return DerivedSuccess(VecResult, E);
7414       }
7415     }
7416 
7417     return false;
7418   }
7419 
7420   bool VisitCastExpr(const CastExpr *E) {
7421     switch (E->getCastKind()) {
7422     default:
7423       break;
7424 
7425     case CK_AtomicToNonAtomic: {
7426       APValue AtomicVal;
7427       // This does not need to be done in place even for class/array types:
7428       // atomic-to-non-atomic conversion implies copying the object
7429       // representation.
7430       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7431         return false;
7432       return DerivedSuccess(AtomicVal, E);
7433     }
7434 
7435     case CK_NoOp:
7436     case CK_UserDefinedConversion:
7437       return StmtVisitorTy::Visit(E->getSubExpr());
7438 
7439     case CK_LValueToRValue: {
7440       LValue LVal;
7441       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7442         return false;
7443       APValue RVal;
7444       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7445       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7446                                           LVal, RVal))
7447         return false;
7448       return DerivedSuccess(RVal, E);
7449     }
7450     case CK_LValueToRValueBitCast: {
7451       APValue DestValue, SourceValue;
7452       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7453         return false;
7454       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7455         return false;
7456       return DerivedSuccess(DestValue, E);
7457     }
7458 
7459     case CK_AddressSpaceConversion: {
7460       APValue Value;
7461       if (!Evaluate(Value, Info, E->getSubExpr()))
7462         return false;
7463       return DerivedSuccess(Value, E);
7464     }
7465     }
7466 
7467     return Error(E);
7468   }
7469 
7470   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7471     return VisitUnaryPostIncDec(UO);
7472   }
7473   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7474     return VisitUnaryPostIncDec(UO);
7475   }
7476   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7477     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7478       return Error(UO);
7479 
7480     LValue LVal;
7481     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7482       return false;
7483     APValue RVal;
7484     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7485                       UO->isIncrementOp(), &RVal))
7486       return false;
7487     return DerivedSuccess(RVal, UO);
7488   }
7489 
7490   bool VisitStmtExpr(const StmtExpr *E) {
7491     // We will have checked the full-expressions inside the statement expression
7492     // when they were completed, and don't need to check them again now.
7493     if (Info.checkingForUndefinedBehavior())
7494       return Error(E);
7495 
7496     const CompoundStmt *CS = E->getSubStmt();
7497     if (CS->body_empty())
7498       return true;
7499 
7500     BlockScopeRAII Scope(Info);
7501     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7502                                            BE = CS->body_end();
7503          /**/; ++BI) {
7504       if (BI + 1 == BE) {
7505         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7506         if (!FinalExpr) {
7507           Info.FFDiag((*BI)->getBeginLoc(),
7508                       diag::note_constexpr_stmt_expr_unsupported);
7509           return false;
7510         }
7511         return this->Visit(FinalExpr) && Scope.destroy();
7512       }
7513 
7514       APValue ReturnValue;
7515       StmtResult Result = { ReturnValue, nullptr };
7516       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7517       if (ESR != ESR_Succeeded) {
7518         // FIXME: If the statement-expression terminated due to 'return',
7519         // 'break', or 'continue', it would be nice to propagate that to
7520         // the outer statement evaluation rather than bailing out.
7521         if (ESR != ESR_Failed)
7522           Info.FFDiag((*BI)->getBeginLoc(),
7523                       diag::note_constexpr_stmt_expr_unsupported);
7524         return false;
7525       }
7526     }
7527 
7528     llvm_unreachable("Return from function from the loop above.");
7529   }
7530 
7531   /// Visit a value which is evaluated, but whose value is ignored.
7532   void VisitIgnoredValue(const Expr *E) {
7533     EvaluateIgnoredValue(Info, E);
7534   }
7535 
7536   /// Potentially visit a MemberExpr's base expression.
7537   void VisitIgnoredBaseExpression(const Expr *E) {
7538     // While MSVC doesn't evaluate the base expression, it does diagnose the
7539     // presence of side-effecting behavior.
7540     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7541       return;
7542     VisitIgnoredValue(E);
7543   }
7544 };
7545 
7546 } // namespace
7547 
7548 //===----------------------------------------------------------------------===//
7549 // Common base class for lvalue and temporary evaluation.
7550 //===----------------------------------------------------------------------===//
7551 namespace {
7552 template<class Derived>
7553 class LValueExprEvaluatorBase
7554   : public ExprEvaluatorBase<Derived> {
7555 protected:
7556   LValue &Result;
7557   bool InvalidBaseOK;
7558   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7559   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7560 
7561   bool Success(APValue::LValueBase B) {
7562     Result.set(B);
7563     return true;
7564   }
7565 
7566   bool evaluatePointer(const Expr *E, LValue &Result) {
7567     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7568   }
7569 
7570 public:
7571   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7572       : ExprEvaluatorBaseTy(Info), Result(Result),
7573         InvalidBaseOK(InvalidBaseOK) {}
7574 
7575   bool Success(const APValue &V, const Expr *E) {
7576     Result.setFrom(this->Info.Ctx, V);
7577     return true;
7578   }
7579 
7580   bool VisitMemberExpr(const MemberExpr *E) {
7581     // Handle non-static data members.
7582     QualType BaseTy;
7583     bool EvalOK;
7584     if (E->isArrow()) {
7585       EvalOK = evaluatePointer(E->getBase(), Result);
7586       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7587     } else if (E->getBase()->isRValue()) {
7588       assert(E->getBase()->getType()->isRecordType());
7589       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7590       BaseTy = E->getBase()->getType();
7591     } else {
7592       EvalOK = this->Visit(E->getBase());
7593       BaseTy = E->getBase()->getType();
7594     }
7595     if (!EvalOK) {
7596       if (!InvalidBaseOK)
7597         return false;
7598       Result.setInvalid(E);
7599       return true;
7600     }
7601 
7602     const ValueDecl *MD = E->getMemberDecl();
7603     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7604       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7605              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7606       (void)BaseTy;
7607       if (!HandleLValueMember(this->Info, E, Result, FD))
7608         return false;
7609     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7610       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7611         return false;
7612     } else
7613       return this->Error(E);
7614 
7615     if (MD->getType()->isReferenceType()) {
7616       APValue RefValue;
7617       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7618                                           RefValue))
7619         return false;
7620       return Success(RefValue, E);
7621     }
7622     return true;
7623   }
7624 
7625   bool VisitBinaryOperator(const BinaryOperator *E) {
7626     switch (E->getOpcode()) {
7627     default:
7628       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7629 
7630     case BO_PtrMemD:
7631     case BO_PtrMemI:
7632       return HandleMemberPointerAccess(this->Info, E, Result);
7633     }
7634   }
7635 
7636   bool VisitCastExpr(const CastExpr *E) {
7637     switch (E->getCastKind()) {
7638     default:
7639       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7640 
7641     case CK_DerivedToBase:
7642     case CK_UncheckedDerivedToBase:
7643       if (!this->Visit(E->getSubExpr()))
7644         return false;
7645 
7646       // Now figure out the necessary offset to add to the base LV to get from
7647       // the derived class to the base class.
7648       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7649                                   Result);
7650     }
7651   }
7652 };
7653 }
7654 
7655 //===----------------------------------------------------------------------===//
7656 // LValue Evaluation
7657 //
7658 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7659 // function designators (in C), decl references to void objects (in C), and
7660 // temporaries (if building with -Wno-address-of-temporary).
7661 //
7662 // LValue evaluation produces values comprising a base expression of one of the
7663 // following types:
7664 // - Declarations
7665 //  * VarDecl
7666 //  * FunctionDecl
7667 // - Literals
7668 //  * CompoundLiteralExpr in C (and in global scope in C++)
7669 //  * StringLiteral
7670 //  * PredefinedExpr
7671 //  * ObjCStringLiteralExpr
7672 //  * ObjCEncodeExpr
7673 //  * AddrLabelExpr
7674 //  * BlockExpr
7675 //  * CallExpr for a MakeStringConstant builtin
7676 // - typeid(T) expressions, as TypeInfoLValues
7677 // - Locals and temporaries
7678 //  * MaterializeTemporaryExpr
7679 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7680 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7681 //    from the AST (FIXME).
7682 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7683 //    CallIndex, for a lifetime-extended temporary.
7684 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7685 //    immediate invocation.
7686 // plus an offset in bytes.
7687 //===----------------------------------------------------------------------===//
7688 namespace {
7689 class LValueExprEvaluator
7690   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7691 public:
7692   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7693     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7694 
7695   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7696   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7697 
7698   bool VisitDeclRefExpr(const DeclRefExpr *E);
7699   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7700   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7701   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7702   bool VisitMemberExpr(const MemberExpr *E);
7703   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7704   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7705   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7706   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7707   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7708   bool VisitUnaryDeref(const UnaryOperator *E);
7709   bool VisitUnaryReal(const UnaryOperator *E);
7710   bool VisitUnaryImag(const UnaryOperator *E);
7711   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7712     return VisitUnaryPreIncDec(UO);
7713   }
7714   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7715     return VisitUnaryPreIncDec(UO);
7716   }
7717   bool VisitBinAssign(const BinaryOperator *BO);
7718   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7719 
7720   bool VisitCastExpr(const CastExpr *E) {
7721     switch (E->getCastKind()) {
7722     default:
7723       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7724 
7725     case CK_LValueBitCast:
7726       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7727       if (!Visit(E->getSubExpr()))
7728         return false;
7729       Result.Designator.setInvalid();
7730       return true;
7731 
7732     case CK_BaseToDerived:
7733       if (!Visit(E->getSubExpr()))
7734         return false;
7735       return HandleBaseToDerivedCast(Info, E, Result);
7736 
7737     case CK_Dynamic:
7738       if (!Visit(E->getSubExpr()))
7739         return false;
7740       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7741     }
7742   }
7743 };
7744 } // end anonymous namespace
7745 
7746 /// Evaluate an expression as an lvalue. This can be legitimately called on
7747 /// expressions which are not glvalues, in three cases:
7748 ///  * function designators in C, and
7749 ///  * "extern void" objects
7750 ///  * @selector() expressions in Objective-C
7751 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7752                            bool InvalidBaseOK) {
7753   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7754          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7755   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7756 }
7757 
7758 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7759   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7760     return Success(FD);
7761   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7762     return VisitVarDecl(E, VD);
7763   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7764     return Visit(BD->getBinding());
7765   if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl()))
7766     return Success(GD);
7767   return Error(E);
7768 }
7769 
7770 
7771 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7772 
7773   // If we are within a lambda's call operator, check whether the 'VD' referred
7774   // to within 'E' actually represents a lambda-capture that maps to a
7775   // data-member/field within the closure object, and if so, evaluate to the
7776   // field or what the field refers to.
7777   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7778       isa<DeclRefExpr>(E) &&
7779       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7780     // We don't always have a complete capture-map when checking or inferring if
7781     // the function call operator meets the requirements of a constexpr function
7782     // - but we don't need to evaluate the captures to determine constexprness
7783     // (dcl.constexpr C++17).
7784     if (Info.checkingPotentialConstantExpression())
7785       return false;
7786 
7787     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7788       // Start with 'Result' referring to the complete closure object...
7789       Result = *Info.CurrentCall->This;
7790       // ... then update it to refer to the field of the closure object
7791       // that represents the capture.
7792       if (!HandleLValueMember(Info, E, Result, FD))
7793         return false;
7794       // And if the field is of reference type, update 'Result' to refer to what
7795       // the field refers to.
7796       if (FD->getType()->isReferenceType()) {
7797         APValue RVal;
7798         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7799                                             RVal))
7800           return false;
7801         Result.setFrom(Info.Ctx, RVal);
7802       }
7803       return true;
7804     }
7805   }
7806   CallStackFrame *Frame = nullptr;
7807   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7808     // Only if a local variable was declared in the function currently being
7809     // evaluated, do we expect to be able to find its value in the current
7810     // frame. (Otherwise it was likely declared in an enclosing context and
7811     // could either have a valid evaluatable value (for e.g. a constexpr
7812     // variable) or be ill-formed (and trigger an appropriate evaluation
7813     // diagnostic)).
7814     if (Info.CurrentCall->Callee &&
7815         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7816       Frame = Info.CurrentCall;
7817     }
7818   }
7819 
7820   if (!VD->getType()->isReferenceType()) {
7821     if (Frame) {
7822       Result.set({VD, Frame->Index,
7823                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7824       return true;
7825     }
7826     return Success(VD);
7827   }
7828 
7829   APValue *V;
7830   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7831     return false;
7832   if (!V->hasValue()) {
7833     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7834     // adjust the diagnostic to say that.
7835     if (!Info.checkingPotentialConstantExpression())
7836       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7837     return false;
7838   }
7839   return Success(*V, E);
7840 }
7841 
7842 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7843     const MaterializeTemporaryExpr *E) {
7844   // Walk through the expression to find the materialized temporary itself.
7845   SmallVector<const Expr *, 2> CommaLHSs;
7846   SmallVector<SubobjectAdjustment, 2> Adjustments;
7847   const Expr *Inner =
7848       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7849 
7850   // If we passed any comma operators, evaluate their LHSs.
7851   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7852     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7853       return false;
7854 
7855   // A materialized temporary with static storage duration can appear within the
7856   // result of a constant expression evaluation, so we need to preserve its
7857   // value for use outside this evaluation.
7858   APValue *Value;
7859   if (E->getStorageDuration() == SD_Static) {
7860     Value = E->getOrCreateValue(true);
7861     *Value = APValue();
7862     Result.set(E);
7863   } else {
7864     Value = &Info.CurrentCall->createTemporary(
7865         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7866   }
7867 
7868   QualType Type = Inner->getType();
7869 
7870   // Materialize the temporary itself.
7871   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7872     *Value = APValue();
7873     return false;
7874   }
7875 
7876   // Adjust our lvalue to refer to the desired subobject.
7877   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7878     --I;
7879     switch (Adjustments[I].Kind) {
7880     case SubobjectAdjustment::DerivedToBaseAdjustment:
7881       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7882                                 Type, Result))
7883         return false;
7884       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7885       break;
7886 
7887     case SubobjectAdjustment::FieldAdjustment:
7888       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7889         return false;
7890       Type = Adjustments[I].Field->getType();
7891       break;
7892 
7893     case SubobjectAdjustment::MemberPointerAdjustment:
7894       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7895                                      Adjustments[I].Ptr.RHS))
7896         return false;
7897       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7898       break;
7899     }
7900   }
7901 
7902   return true;
7903 }
7904 
7905 bool
7906 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7907   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7908          "lvalue compound literal in c++?");
7909   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7910   // only see this when folding in C, so there's no standard to follow here.
7911   return Success(E);
7912 }
7913 
7914 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7915   TypeInfoLValue TypeInfo;
7916 
7917   if (!E->isPotentiallyEvaluated()) {
7918     if (E->isTypeOperand())
7919       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7920     else
7921       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7922   } else {
7923     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
7924       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7925         << E->getExprOperand()->getType()
7926         << E->getExprOperand()->getSourceRange();
7927     }
7928 
7929     if (!Visit(E->getExprOperand()))
7930       return false;
7931 
7932     Optional<DynamicType> DynType =
7933         ComputeDynamicType(Info, E, Result, AK_TypeId);
7934     if (!DynType)
7935       return false;
7936 
7937     TypeInfo =
7938         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7939   }
7940 
7941   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7942 }
7943 
7944 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7945   return Success(E->getGuidDecl());
7946 }
7947 
7948 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7949   // Handle static data members.
7950   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7951     VisitIgnoredBaseExpression(E->getBase());
7952     return VisitVarDecl(E, VD);
7953   }
7954 
7955   // Handle static member functions.
7956   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7957     if (MD->isStatic()) {
7958       VisitIgnoredBaseExpression(E->getBase());
7959       return Success(MD);
7960     }
7961   }
7962 
7963   // Handle non-static data members.
7964   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7965 }
7966 
7967 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7968   // FIXME: Deal with vectors as array subscript bases.
7969   if (E->getBase()->getType()->isVectorType())
7970     return Error(E);
7971 
7972   bool Success = true;
7973   if (!evaluatePointer(E->getBase(), Result)) {
7974     if (!Info.noteFailure())
7975       return false;
7976     Success = false;
7977   }
7978 
7979   APSInt Index;
7980   if (!EvaluateInteger(E->getIdx(), Index, Info))
7981     return false;
7982 
7983   return Success &&
7984          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7985 }
7986 
7987 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7988   return evaluatePointer(E->getSubExpr(), Result);
7989 }
7990 
7991 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7992   if (!Visit(E->getSubExpr()))
7993     return false;
7994   // __real is a no-op on scalar lvalues.
7995   if (E->getSubExpr()->getType()->isAnyComplexType())
7996     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7997   return true;
7998 }
7999 
8000 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8001   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8002          "lvalue __imag__ on scalar?");
8003   if (!Visit(E->getSubExpr()))
8004     return false;
8005   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8006   return true;
8007 }
8008 
8009 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8010   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8011     return Error(UO);
8012 
8013   if (!this->Visit(UO->getSubExpr()))
8014     return false;
8015 
8016   return handleIncDec(
8017       this->Info, UO, Result, UO->getSubExpr()->getType(),
8018       UO->isIncrementOp(), nullptr);
8019 }
8020 
8021 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8022     const CompoundAssignOperator *CAO) {
8023   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8024     return Error(CAO);
8025 
8026   APValue RHS;
8027 
8028   // The overall lvalue result is the result of evaluating the LHS.
8029   if (!this->Visit(CAO->getLHS())) {
8030     if (Info.noteFailure())
8031       Evaluate(RHS, this->Info, CAO->getRHS());
8032     return false;
8033   }
8034 
8035   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
8036     return false;
8037 
8038   return handleCompoundAssignment(
8039       this->Info, CAO,
8040       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8041       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8042 }
8043 
8044 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8045   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8046     return Error(E);
8047 
8048   APValue NewVal;
8049 
8050   if (!this->Visit(E->getLHS())) {
8051     if (Info.noteFailure())
8052       Evaluate(NewVal, this->Info, E->getRHS());
8053     return false;
8054   }
8055 
8056   if (!Evaluate(NewVal, this->Info, E->getRHS()))
8057     return false;
8058 
8059   if (Info.getLangOpts().CPlusPlus20 &&
8060       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8061     return false;
8062 
8063   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8064                           NewVal);
8065 }
8066 
8067 //===----------------------------------------------------------------------===//
8068 // Pointer Evaluation
8069 //===----------------------------------------------------------------------===//
8070 
8071 /// Attempts to compute the number of bytes available at the pointer
8072 /// returned by a function with the alloc_size attribute. Returns true if we
8073 /// were successful. Places an unsigned number into `Result`.
8074 ///
8075 /// This expects the given CallExpr to be a call to a function with an
8076 /// alloc_size attribute.
8077 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8078                                             const CallExpr *Call,
8079                                             llvm::APInt &Result) {
8080   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8081 
8082   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8083   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8084   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8085   if (Call->getNumArgs() <= SizeArgNo)
8086     return false;
8087 
8088   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8089     Expr::EvalResult ExprResult;
8090     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8091       return false;
8092     Into = ExprResult.Val.getInt();
8093     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8094       return false;
8095     Into = Into.zextOrSelf(BitsInSizeT);
8096     return true;
8097   };
8098 
8099   APSInt SizeOfElem;
8100   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8101     return false;
8102 
8103   if (!AllocSize->getNumElemsParam().isValid()) {
8104     Result = std::move(SizeOfElem);
8105     return true;
8106   }
8107 
8108   APSInt NumberOfElems;
8109   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8110   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8111     return false;
8112 
8113   bool Overflow;
8114   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8115   if (Overflow)
8116     return false;
8117 
8118   Result = std::move(BytesAvailable);
8119   return true;
8120 }
8121 
8122 /// Convenience function. LVal's base must be a call to an alloc_size
8123 /// function.
8124 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8125                                             const LValue &LVal,
8126                                             llvm::APInt &Result) {
8127   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8128          "Can't get the size of a non alloc_size function");
8129   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8130   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8131   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8132 }
8133 
8134 /// Attempts to evaluate the given LValueBase as the result of a call to
8135 /// a function with the alloc_size attribute. If it was possible to do so, this
8136 /// function will return true, make Result's Base point to said function call,
8137 /// and mark Result's Base as invalid.
8138 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8139                                       LValue &Result) {
8140   if (Base.isNull())
8141     return false;
8142 
8143   // Because we do no form of static analysis, we only support const variables.
8144   //
8145   // Additionally, we can't support parameters, nor can we support static
8146   // variables (in the latter case, use-before-assign isn't UB; in the former,
8147   // we have no clue what they'll be assigned to).
8148   const auto *VD =
8149       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8150   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8151     return false;
8152 
8153   const Expr *Init = VD->getAnyInitializer();
8154   if (!Init)
8155     return false;
8156 
8157   const Expr *E = Init->IgnoreParens();
8158   if (!tryUnwrapAllocSizeCall(E))
8159     return false;
8160 
8161   // Store E instead of E unwrapped so that the type of the LValue's base is
8162   // what the user wanted.
8163   Result.setInvalid(E);
8164 
8165   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8166   Result.addUnsizedArray(Info, E, Pointee);
8167   return true;
8168 }
8169 
8170 namespace {
8171 class PointerExprEvaluator
8172   : public ExprEvaluatorBase<PointerExprEvaluator> {
8173   LValue &Result;
8174   bool InvalidBaseOK;
8175 
8176   bool Success(const Expr *E) {
8177     Result.set(E);
8178     return true;
8179   }
8180 
8181   bool evaluateLValue(const Expr *E, LValue &Result) {
8182     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8183   }
8184 
8185   bool evaluatePointer(const Expr *E, LValue &Result) {
8186     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8187   }
8188 
8189   bool visitNonBuiltinCallExpr(const CallExpr *E);
8190 public:
8191 
8192   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8193       : ExprEvaluatorBaseTy(info), Result(Result),
8194         InvalidBaseOK(InvalidBaseOK) {}
8195 
8196   bool Success(const APValue &V, const Expr *E) {
8197     Result.setFrom(Info.Ctx, V);
8198     return true;
8199   }
8200   bool ZeroInitialization(const Expr *E) {
8201     Result.setNull(Info.Ctx, E->getType());
8202     return true;
8203   }
8204 
8205   bool VisitBinaryOperator(const BinaryOperator *E);
8206   bool VisitCastExpr(const CastExpr* E);
8207   bool VisitUnaryAddrOf(const UnaryOperator *E);
8208   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8209       { return Success(E); }
8210   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8211     if (E->isExpressibleAsConstantInitializer())
8212       return Success(E);
8213     if (Info.noteFailure())
8214       EvaluateIgnoredValue(Info, E->getSubExpr());
8215     return Error(E);
8216   }
8217   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8218       { return Success(E); }
8219   bool VisitCallExpr(const CallExpr *E);
8220   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8221   bool VisitBlockExpr(const BlockExpr *E) {
8222     if (!E->getBlockDecl()->hasCaptures())
8223       return Success(E);
8224     return Error(E);
8225   }
8226   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8227     // Can't look at 'this' when checking a potential constant expression.
8228     if (Info.checkingPotentialConstantExpression())
8229       return false;
8230     if (!Info.CurrentCall->This) {
8231       if (Info.getLangOpts().CPlusPlus11)
8232         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8233       else
8234         Info.FFDiag(E);
8235       return false;
8236     }
8237     Result = *Info.CurrentCall->This;
8238     // If we are inside a lambda's call operator, the 'this' expression refers
8239     // to the enclosing '*this' object (either by value or reference) which is
8240     // either copied into the closure object's field that represents the '*this'
8241     // or refers to '*this'.
8242     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8243       // Ensure we actually have captured 'this'. (an error will have
8244       // been previously reported if not).
8245       if (!Info.CurrentCall->LambdaThisCaptureField)
8246         return false;
8247 
8248       // Update 'Result' to refer to the data member/field of the closure object
8249       // that represents the '*this' capture.
8250       if (!HandleLValueMember(Info, E, Result,
8251                              Info.CurrentCall->LambdaThisCaptureField))
8252         return false;
8253       // If we captured '*this' by reference, replace the field with its referent.
8254       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8255               ->isPointerType()) {
8256         APValue RVal;
8257         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8258                                             RVal))
8259           return false;
8260 
8261         Result.setFrom(Info.Ctx, RVal);
8262       }
8263     }
8264     return true;
8265   }
8266 
8267   bool VisitCXXNewExpr(const CXXNewExpr *E);
8268 
8269   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8270     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8271     APValue LValResult = E->EvaluateInContext(
8272         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8273     Result.setFrom(Info.Ctx, LValResult);
8274     return true;
8275   }
8276 
8277   // FIXME: Missing: @protocol, @selector
8278 };
8279 } // end anonymous namespace
8280 
8281 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8282                             bool InvalidBaseOK) {
8283   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8284   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8285 }
8286 
8287 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8288   if (E->getOpcode() != BO_Add &&
8289       E->getOpcode() != BO_Sub)
8290     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8291 
8292   const Expr *PExp = E->getLHS();
8293   const Expr *IExp = E->getRHS();
8294   if (IExp->getType()->isPointerType())
8295     std::swap(PExp, IExp);
8296 
8297   bool EvalPtrOK = evaluatePointer(PExp, Result);
8298   if (!EvalPtrOK && !Info.noteFailure())
8299     return false;
8300 
8301   llvm::APSInt Offset;
8302   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8303     return false;
8304 
8305   if (E->getOpcode() == BO_Sub)
8306     negateAsSigned(Offset);
8307 
8308   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8309   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8310 }
8311 
8312 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8313   return evaluateLValue(E->getSubExpr(), Result);
8314 }
8315 
8316 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8317   const Expr *SubExpr = E->getSubExpr();
8318 
8319   switch (E->getCastKind()) {
8320   default:
8321     break;
8322   case CK_BitCast:
8323   case CK_CPointerToObjCPointerCast:
8324   case CK_BlockPointerToObjCPointerCast:
8325   case CK_AnyPointerToBlockPointerCast:
8326   case CK_AddressSpaceConversion:
8327     if (!Visit(SubExpr))
8328       return false;
8329     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8330     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8331     // also static_casts, but we disallow them as a resolution to DR1312.
8332     if (!E->getType()->isVoidPointerType()) {
8333       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8334           !Result.IsNullPtr &&
8335           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8336                                           E->getType()->getPointeeType()) &&
8337           Info.getStdAllocatorCaller("allocate")) {
8338         // Inside a call to std::allocator::allocate and friends, we permit
8339         // casting from void* back to cv1 T* for a pointer that points to a
8340         // cv2 T.
8341       } else {
8342         Result.Designator.setInvalid();
8343         if (SubExpr->getType()->isVoidPointerType())
8344           CCEDiag(E, diag::note_constexpr_invalid_cast)
8345             << 3 << SubExpr->getType();
8346         else
8347           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8348       }
8349     }
8350     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8351       ZeroInitialization(E);
8352     return true;
8353 
8354   case CK_DerivedToBase:
8355   case CK_UncheckedDerivedToBase:
8356     if (!evaluatePointer(E->getSubExpr(), Result))
8357       return false;
8358     if (!Result.Base && Result.Offset.isZero())
8359       return true;
8360 
8361     // Now figure out the necessary offset to add to the base LV to get from
8362     // the derived class to the base class.
8363     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8364                                   castAs<PointerType>()->getPointeeType(),
8365                                 Result);
8366 
8367   case CK_BaseToDerived:
8368     if (!Visit(E->getSubExpr()))
8369       return false;
8370     if (!Result.Base && Result.Offset.isZero())
8371       return true;
8372     return HandleBaseToDerivedCast(Info, E, Result);
8373 
8374   case CK_Dynamic:
8375     if (!Visit(E->getSubExpr()))
8376       return false;
8377     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8378 
8379   case CK_NullToPointer:
8380     VisitIgnoredValue(E->getSubExpr());
8381     return ZeroInitialization(E);
8382 
8383   case CK_IntegralToPointer: {
8384     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8385 
8386     APValue Value;
8387     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8388       break;
8389 
8390     if (Value.isInt()) {
8391       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8392       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8393       Result.Base = (Expr*)nullptr;
8394       Result.InvalidBase = false;
8395       Result.Offset = CharUnits::fromQuantity(N);
8396       Result.Designator.setInvalid();
8397       Result.IsNullPtr = false;
8398       return true;
8399     } else {
8400       // Cast is of an lvalue, no need to change value.
8401       Result.setFrom(Info.Ctx, Value);
8402       return true;
8403     }
8404   }
8405 
8406   case CK_ArrayToPointerDecay: {
8407     if (SubExpr->isGLValue()) {
8408       if (!evaluateLValue(SubExpr, Result))
8409         return false;
8410     } else {
8411       APValue &Value = Info.CurrentCall->createTemporary(
8412           SubExpr, SubExpr->getType(), false, Result);
8413       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8414         return false;
8415     }
8416     // The result is a pointer to the first element of the array.
8417     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8418     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8419       Result.addArray(Info, E, CAT);
8420     else
8421       Result.addUnsizedArray(Info, E, AT->getElementType());
8422     return true;
8423   }
8424 
8425   case CK_FunctionToPointerDecay:
8426     return evaluateLValue(SubExpr, Result);
8427 
8428   case CK_LValueToRValue: {
8429     LValue LVal;
8430     if (!evaluateLValue(E->getSubExpr(), LVal))
8431       return false;
8432 
8433     APValue RVal;
8434     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8435     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8436                                         LVal, RVal))
8437       return InvalidBaseOK &&
8438              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8439     return Success(RVal, E);
8440   }
8441   }
8442 
8443   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8444 }
8445 
8446 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8447                                 UnaryExprOrTypeTrait ExprKind) {
8448   // C++ [expr.alignof]p3:
8449   //     When alignof is applied to a reference type, the result is the
8450   //     alignment of the referenced type.
8451   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8452     T = Ref->getPointeeType();
8453 
8454   if (T.getQualifiers().hasUnaligned())
8455     return CharUnits::One();
8456 
8457   const bool AlignOfReturnsPreferred =
8458       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8459 
8460   // __alignof is defined to return the preferred alignment.
8461   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8462   // as well.
8463   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8464     return Info.Ctx.toCharUnitsFromBits(
8465       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8466   // alignof and _Alignof are defined to return the ABI alignment.
8467   else if (ExprKind == UETT_AlignOf)
8468     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8469   else
8470     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8471 }
8472 
8473 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8474                                 UnaryExprOrTypeTrait ExprKind) {
8475   E = E->IgnoreParens();
8476 
8477   // The kinds of expressions that we have special-case logic here for
8478   // should be kept up to date with the special checks for those
8479   // expressions in Sema.
8480 
8481   // alignof decl is always accepted, even if it doesn't make sense: we default
8482   // to 1 in those cases.
8483   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8484     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8485                                  /*RefAsPointee*/true);
8486 
8487   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8488     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8489                                  /*RefAsPointee*/true);
8490 
8491   return GetAlignOfType(Info, E->getType(), ExprKind);
8492 }
8493 
8494 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8495   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8496     return Info.Ctx.getDeclAlign(VD);
8497   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8498     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8499   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8500 }
8501 
8502 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8503 /// __builtin_is_aligned and __builtin_assume_aligned.
8504 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8505                                  EvalInfo &Info, APSInt &Alignment) {
8506   if (!EvaluateInteger(E, Alignment, Info))
8507     return false;
8508   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8509     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8510     return false;
8511   }
8512   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8513   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8514   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8515     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8516         << MaxValue << ForType << Alignment;
8517     return false;
8518   }
8519   // Ensure both alignment and source value have the same bit width so that we
8520   // don't assert when computing the resulting value.
8521   APSInt ExtAlignment =
8522       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8523   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8524          "Alignment should not be changed by ext/trunc");
8525   Alignment = ExtAlignment;
8526   assert(Alignment.getBitWidth() == SrcWidth);
8527   return true;
8528 }
8529 
8530 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8531 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8532   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8533     return true;
8534 
8535   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8536     return false;
8537 
8538   Result.setInvalid(E);
8539   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8540   Result.addUnsizedArray(Info, E, PointeeTy);
8541   return true;
8542 }
8543 
8544 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8545   if (IsStringLiteralCall(E))
8546     return Success(E);
8547 
8548   if (unsigned BuiltinOp = E->getBuiltinCallee())
8549     return VisitBuiltinCallExpr(E, BuiltinOp);
8550 
8551   return visitNonBuiltinCallExpr(E);
8552 }
8553 
8554 // Determine if T is a character type for which we guarantee that
8555 // sizeof(T) == 1.
8556 static bool isOneByteCharacterType(QualType T) {
8557   return T->isCharType() || T->isChar8Type();
8558 }
8559 
8560 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8561                                                 unsigned BuiltinOp) {
8562   switch (BuiltinOp) {
8563   case Builtin::BI__builtin_addressof:
8564     return evaluateLValue(E->getArg(0), Result);
8565   case Builtin::BI__builtin_assume_aligned: {
8566     // We need to be very careful here because: if the pointer does not have the
8567     // asserted alignment, then the behavior is undefined, and undefined
8568     // behavior is non-constant.
8569     if (!evaluatePointer(E->getArg(0), Result))
8570       return false;
8571 
8572     LValue OffsetResult(Result);
8573     APSInt Alignment;
8574     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8575                               Alignment))
8576       return false;
8577     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8578 
8579     if (E->getNumArgs() > 2) {
8580       APSInt Offset;
8581       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8582         return false;
8583 
8584       int64_t AdditionalOffset = -Offset.getZExtValue();
8585       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8586     }
8587 
8588     // If there is a base object, then it must have the correct alignment.
8589     if (OffsetResult.Base) {
8590       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8591 
8592       if (BaseAlignment < Align) {
8593         Result.Designator.setInvalid();
8594         // FIXME: Add support to Diagnostic for long / long long.
8595         CCEDiag(E->getArg(0),
8596                 diag::note_constexpr_baa_insufficient_alignment) << 0
8597           << (unsigned)BaseAlignment.getQuantity()
8598           << (unsigned)Align.getQuantity();
8599         return false;
8600       }
8601     }
8602 
8603     // The offset must also have the correct alignment.
8604     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8605       Result.Designator.setInvalid();
8606 
8607       (OffsetResult.Base
8608            ? CCEDiag(E->getArg(0),
8609                      diag::note_constexpr_baa_insufficient_alignment) << 1
8610            : CCEDiag(E->getArg(0),
8611                      diag::note_constexpr_baa_value_insufficient_alignment))
8612         << (int)OffsetResult.Offset.getQuantity()
8613         << (unsigned)Align.getQuantity();
8614       return false;
8615     }
8616 
8617     return true;
8618   }
8619   case Builtin::BI__builtin_align_up:
8620   case Builtin::BI__builtin_align_down: {
8621     if (!evaluatePointer(E->getArg(0), Result))
8622       return false;
8623     APSInt Alignment;
8624     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8625                               Alignment))
8626       return false;
8627     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8628     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8629     // For align_up/align_down, we can return the same value if the alignment
8630     // is known to be greater or equal to the requested value.
8631     if (PtrAlign.getQuantity() >= Alignment)
8632       return true;
8633 
8634     // The alignment could be greater than the minimum at run-time, so we cannot
8635     // infer much about the resulting pointer value. One case is possible:
8636     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8637     // can infer the correct index if the requested alignment is smaller than
8638     // the base alignment so we can perform the computation on the offset.
8639     if (BaseAlignment.getQuantity() >= Alignment) {
8640       assert(Alignment.getBitWidth() <= 64 &&
8641              "Cannot handle > 64-bit address-space");
8642       uint64_t Alignment64 = Alignment.getZExtValue();
8643       CharUnits NewOffset = CharUnits::fromQuantity(
8644           BuiltinOp == Builtin::BI__builtin_align_down
8645               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8646               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8647       Result.adjustOffset(NewOffset - Result.Offset);
8648       // TODO: diagnose out-of-bounds values/only allow for arrays?
8649       return true;
8650     }
8651     // Otherwise, we cannot constant-evaluate the result.
8652     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8653         << Alignment;
8654     return false;
8655   }
8656   case Builtin::BI__builtin_operator_new:
8657     return HandleOperatorNewCall(Info, E, Result);
8658   case Builtin::BI__builtin_launder:
8659     return evaluatePointer(E->getArg(0), Result);
8660   case Builtin::BIstrchr:
8661   case Builtin::BIwcschr:
8662   case Builtin::BImemchr:
8663   case Builtin::BIwmemchr:
8664     if (Info.getLangOpts().CPlusPlus11)
8665       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8666         << /*isConstexpr*/0 << /*isConstructor*/0
8667         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8668     else
8669       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8670     LLVM_FALLTHROUGH;
8671   case Builtin::BI__builtin_strchr:
8672   case Builtin::BI__builtin_wcschr:
8673   case Builtin::BI__builtin_memchr:
8674   case Builtin::BI__builtin_char_memchr:
8675   case Builtin::BI__builtin_wmemchr: {
8676     if (!Visit(E->getArg(0)))
8677       return false;
8678     APSInt Desired;
8679     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8680       return false;
8681     uint64_t MaxLength = uint64_t(-1);
8682     if (BuiltinOp != Builtin::BIstrchr &&
8683         BuiltinOp != Builtin::BIwcschr &&
8684         BuiltinOp != Builtin::BI__builtin_strchr &&
8685         BuiltinOp != Builtin::BI__builtin_wcschr) {
8686       APSInt N;
8687       if (!EvaluateInteger(E->getArg(2), N, Info))
8688         return false;
8689       MaxLength = N.getExtValue();
8690     }
8691     // We cannot find the value if there are no candidates to match against.
8692     if (MaxLength == 0u)
8693       return ZeroInitialization(E);
8694     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8695         Result.Designator.Invalid)
8696       return false;
8697     QualType CharTy = Result.Designator.getType(Info.Ctx);
8698     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8699                      BuiltinOp == Builtin::BI__builtin_memchr;
8700     assert(IsRawByte ||
8701            Info.Ctx.hasSameUnqualifiedType(
8702                CharTy, E->getArg(0)->getType()->getPointeeType()));
8703     // Pointers to const void may point to objects of incomplete type.
8704     if (IsRawByte && CharTy->isIncompleteType()) {
8705       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8706       return false;
8707     }
8708     // Give up on byte-oriented matching against multibyte elements.
8709     // FIXME: We can compare the bytes in the correct order.
8710     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
8711       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
8712           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
8713           << CharTy;
8714       return false;
8715     }
8716     // Figure out what value we're actually looking for (after converting to
8717     // the corresponding unsigned type if necessary).
8718     uint64_t DesiredVal;
8719     bool StopAtNull = false;
8720     switch (BuiltinOp) {
8721     case Builtin::BIstrchr:
8722     case Builtin::BI__builtin_strchr:
8723       // strchr compares directly to the passed integer, and therefore
8724       // always fails if given an int that is not a char.
8725       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8726                                                   E->getArg(1)->getType(),
8727                                                   Desired),
8728                                Desired))
8729         return ZeroInitialization(E);
8730       StopAtNull = true;
8731       LLVM_FALLTHROUGH;
8732     case Builtin::BImemchr:
8733     case Builtin::BI__builtin_memchr:
8734     case Builtin::BI__builtin_char_memchr:
8735       // memchr compares by converting both sides to unsigned char. That's also
8736       // correct for strchr if we get this far (to cope with plain char being
8737       // unsigned in the strchr case).
8738       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8739       break;
8740 
8741     case Builtin::BIwcschr:
8742     case Builtin::BI__builtin_wcschr:
8743       StopAtNull = true;
8744       LLVM_FALLTHROUGH;
8745     case Builtin::BIwmemchr:
8746     case Builtin::BI__builtin_wmemchr:
8747       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8748       DesiredVal = Desired.getZExtValue();
8749       break;
8750     }
8751 
8752     for (; MaxLength; --MaxLength) {
8753       APValue Char;
8754       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8755           !Char.isInt())
8756         return false;
8757       if (Char.getInt().getZExtValue() == DesiredVal)
8758         return true;
8759       if (StopAtNull && !Char.getInt())
8760         break;
8761       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8762         return false;
8763     }
8764     // Not found: return nullptr.
8765     return ZeroInitialization(E);
8766   }
8767 
8768   case Builtin::BImemcpy:
8769   case Builtin::BImemmove:
8770   case Builtin::BIwmemcpy:
8771   case Builtin::BIwmemmove:
8772     if (Info.getLangOpts().CPlusPlus11)
8773       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8774         << /*isConstexpr*/0 << /*isConstructor*/0
8775         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8776     else
8777       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8778     LLVM_FALLTHROUGH;
8779   case Builtin::BI__builtin_memcpy:
8780   case Builtin::BI__builtin_memmove:
8781   case Builtin::BI__builtin_wmemcpy:
8782   case Builtin::BI__builtin_wmemmove: {
8783     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8784                  BuiltinOp == Builtin::BIwmemmove ||
8785                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8786                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8787     bool Move = BuiltinOp == Builtin::BImemmove ||
8788                 BuiltinOp == Builtin::BIwmemmove ||
8789                 BuiltinOp == Builtin::BI__builtin_memmove ||
8790                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8791 
8792     // The result of mem* is the first argument.
8793     if (!Visit(E->getArg(0)))
8794       return false;
8795     LValue Dest = Result;
8796 
8797     LValue Src;
8798     if (!EvaluatePointer(E->getArg(1), Src, Info))
8799       return false;
8800 
8801     APSInt N;
8802     if (!EvaluateInteger(E->getArg(2), N, Info))
8803       return false;
8804     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8805 
8806     // If the size is zero, we treat this as always being a valid no-op.
8807     // (Even if one of the src and dest pointers is null.)
8808     if (!N)
8809       return true;
8810 
8811     // Otherwise, if either of the operands is null, we can't proceed. Don't
8812     // try to determine the type of the copied objects, because there aren't
8813     // any.
8814     if (!Src.Base || !Dest.Base) {
8815       APValue Val;
8816       (!Src.Base ? Src : Dest).moveInto(Val);
8817       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8818           << Move << WChar << !!Src.Base
8819           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8820       return false;
8821     }
8822     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8823       return false;
8824 
8825     // We require that Src and Dest are both pointers to arrays of
8826     // trivially-copyable type. (For the wide version, the designator will be
8827     // invalid if the designated object is not a wchar_t.)
8828     QualType T = Dest.Designator.getType(Info.Ctx);
8829     QualType SrcT = Src.Designator.getType(Info.Ctx);
8830     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8831       // FIXME: Consider using our bit_cast implementation to support this.
8832       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8833       return false;
8834     }
8835     if (T->isIncompleteType()) {
8836       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8837       return false;
8838     }
8839     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8840       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8841       return false;
8842     }
8843 
8844     // Figure out how many T's we're copying.
8845     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8846     if (!WChar) {
8847       uint64_t Remainder;
8848       llvm::APInt OrigN = N;
8849       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8850       if (Remainder) {
8851         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8852             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8853             << (unsigned)TSize;
8854         return false;
8855       }
8856     }
8857 
8858     // Check that the copying will remain within the arrays, just so that we
8859     // can give a more meaningful diagnostic. This implicitly also checks that
8860     // N fits into 64 bits.
8861     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8862     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8863     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8864       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8865           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8866           << N.toString(10, /*Signed*/false);
8867       return false;
8868     }
8869     uint64_t NElems = N.getZExtValue();
8870     uint64_t NBytes = NElems * TSize;
8871 
8872     // Check for overlap.
8873     int Direction = 1;
8874     if (HasSameBase(Src, Dest)) {
8875       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8876       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8877       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8878         // Dest is inside the source region.
8879         if (!Move) {
8880           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8881           return false;
8882         }
8883         // For memmove and friends, copy backwards.
8884         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8885             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8886           return false;
8887         Direction = -1;
8888       } else if (!Move && SrcOffset >= DestOffset &&
8889                  SrcOffset - DestOffset < NBytes) {
8890         // Src is inside the destination region for memcpy: invalid.
8891         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8892         return false;
8893       }
8894     }
8895 
8896     while (true) {
8897       APValue Val;
8898       // FIXME: Set WantObjectRepresentation to true if we're copying a
8899       // char-like type?
8900       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8901           !handleAssignment(Info, E, Dest, T, Val))
8902         return false;
8903       // Do not iterate past the last element; if we're copying backwards, that
8904       // might take us off the start of the array.
8905       if (--NElems == 0)
8906         return true;
8907       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8908           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8909         return false;
8910     }
8911   }
8912 
8913   default:
8914     break;
8915   }
8916 
8917   return visitNonBuiltinCallExpr(E);
8918 }
8919 
8920 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8921                                      APValue &Result, const InitListExpr *ILE,
8922                                      QualType AllocType);
8923 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
8924                                           APValue &Result,
8925                                           const CXXConstructExpr *CCE,
8926                                           QualType AllocType);
8927 
8928 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8929   if (!Info.getLangOpts().CPlusPlus20)
8930     Info.CCEDiag(E, diag::note_constexpr_new);
8931 
8932   // We cannot speculatively evaluate a delete expression.
8933   if (Info.SpeculativeEvaluationDepth)
8934     return false;
8935 
8936   FunctionDecl *OperatorNew = E->getOperatorNew();
8937 
8938   bool IsNothrow = false;
8939   bool IsPlacement = false;
8940   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8941       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8942     // FIXME Support array placement new.
8943     assert(E->getNumPlacementArgs() == 1);
8944     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8945       return false;
8946     if (Result.Designator.Invalid)
8947       return false;
8948     IsPlacement = true;
8949   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8950     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8951         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8952     return false;
8953   } else if (E->getNumPlacementArgs()) {
8954     // The only new-placement list we support is of the form (std::nothrow).
8955     //
8956     // FIXME: There is no restriction on this, but it's not clear that any
8957     // other form makes any sense. We get here for cases such as:
8958     //
8959     //   new (std::align_val_t{N}) X(int)
8960     //
8961     // (which should presumably be valid only if N is a multiple of
8962     // alignof(int), and in any case can't be deallocated unless N is
8963     // alignof(X) and X has new-extended alignment).
8964     if (E->getNumPlacementArgs() != 1 ||
8965         !E->getPlacementArg(0)->getType()->isNothrowT())
8966       return Error(E, diag::note_constexpr_new_placement);
8967 
8968     LValue Nothrow;
8969     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8970       return false;
8971     IsNothrow = true;
8972   }
8973 
8974   const Expr *Init = E->getInitializer();
8975   const InitListExpr *ResizedArrayILE = nullptr;
8976   const CXXConstructExpr *ResizedArrayCCE = nullptr;
8977   bool ValueInit = false;
8978 
8979   QualType AllocType = E->getAllocatedType();
8980   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8981     const Expr *Stripped = *ArraySize;
8982     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8983          Stripped = ICE->getSubExpr())
8984       if (ICE->getCastKind() != CK_NoOp &&
8985           ICE->getCastKind() != CK_IntegralCast)
8986         break;
8987 
8988     llvm::APSInt ArrayBound;
8989     if (!EvaluateInteger(Stripped, ArrayBound, Info))
8990       return false;
8991 
8992     // C++ [expr.new]p9:
8993     //   The expression is erroneous if:
8994     //   -- [...] its value before converting to size_t [or] applying the
8995     //      second standard conversion sequence is less than zero
8996     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8997       if (IsNothrow)
8998         return ZeroInitialization(E);
8999 
9000       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9001           << ArrayBound << (*ArraySize)->getSourceRange();
9002       return false;
9003     }
9004 
9005     //   -- its value is such that the size of the allocated object would
9006     //      exceed the implementation-defined limit
9007     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9008                                                 ArrayBound) >
9009         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9010       if (IsNothrow)
9011         return ZeroInitialization(E);
9012 
9013       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9014         << ArrayBound << (*ArraySize)->getSourceRange();
9015       return false;
9016     }
9017 
9018     //   -- the new-initializer is a braced-init-list and the number of
9019     //      array elements for which initializers are provided [...]
9020     //      exceeds the number of elements to initialize
9021     if (!Init) {
9022       // No initialization is performed.
9023     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9024                isa<ImplicitValueInitExpr>(Init)) {
9025       ValueInit = true;
9026     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9027       ResizedArrayCCE = CCE;
9028     } else {
9029       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9030       assert(CAT && "unexpected type for array initializer");
9031 
9032       unsigned Bits =
9033           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9034       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9035       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9036       if (InitBound.ugt(AllocBound)) {
9037         if (IsNothrow)
9038           return ZeroInitialization(E);
9039 
9040         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9041             << AllocBound.toString(10, /*Signed=*/false)
9042             << InitBound.toString(10, /*Signed=*/false)
9043             << (*ArraySize)->getSourceRange();
9044         return false;
9045       }
9046 
9047       // If the sizes differ, we must have an initializer list, and we need
9048       // special handling for this case when we initialize.
9049       if (InitBound != AllocBound)
9050         ResizedArrayILE = cast<InitListExpr>(Init);
9051     }
9052 
9053     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9054                                               ArrayType::Normal, 0);
9055   } else {
9056     assert(!AllocType->isArrayType() &&
9057            "array allocation with non-array new");
9058   }
9059 
9060   APValue *Val;
9061   if (IsPlacement) {
9062     AccessKinds AK = AK_Construct;
9063     struct FindObjectHandler {
9064       EvalInfo &Info;
9065       const Expr *E;
9066       QualType AllocType;
9067       const AccessKinds AccessKind;
9068       APValue *Value;
9069 
9070       typedef bool result_type;
9071       bool failed() { return false; }
9072       bool found(APValue &Subobj, QualType SubobjType) {
9073         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9074         // old name of the object to be used to name the new object.
9075         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9076           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9077             SubobjType << AllocType;
9078           return false;
9079         }
9080         Value = &Subobj;
9081         return true;
9082       }
9083       bool found(APSInt &Value, QualType SubobjType) {
9084         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9085         return false;
9086       }
9087       bool found(APFloat &Value, QualType SubobjType) {
9088         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9089         return false;
9090       }
9091     } Handler = {Info, E, AllocType, AK, nullptr};
9092 
9093     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9094     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9095       return false;
9096 
9097     Val = Handler.Value;
9098 
9099     // [basic.life]p1:
9100     //   The lifetime of an object o of type T ends when [...] the storage
9101     //   which the object occupies is [...] reused by an object that is not
9102     //   nested within o (6.6.2).
9103     *Val = APValue();
9104   } else {
9105     // Perform the allocation and obtain a pointer to the resulting object.
9106     Val = Info.createHeapAlloc(E, AllocType, Result);
9107     if (!Val)
9108       return false;
9109   }
9110 
9111   if (ValueInit) {
9112     ImplicitValueInitExpr VIE(AllocType);
9113     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9114       return false;
9115   } else if (ResizedArrayILE) {
9116     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9117                                   AllocType))
9118       return false;
9119   } else if (ResizedArrayCCE) {
9120     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9121                                        AllocType))
9122       return false;
9123   } else if (Init) {
9124     if (!EvaluateInPlace(*Val, Info, Result, Init))
9125       return false;
9126   } else if (!getDefaultInitValue(AllocType, *Val)) {
9127     return false;
9128   }
9129 
9130   // Array new returns a pointer to the first element, not a pointer to the
9131   // array.
9132   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9133     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9134 
9135   return true;
9136 }
9137 //===----------------------------------------------------------------------===//
9138 // Member Pointer Evaluation
9139 //===----------------------------------------------------------------------===//
9140 
9141 namespace {
9142 class MemberPointerExprEvaluator
9143   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9144   MemberPtr &Result;
9145 
9146   bool Success(const ValueDecl *D) {
9147     Result = MemberPtr(D);
9148     return true;
9149   }
9150 public:
9151 
9152   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9153     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9154 
9155   bool Success(const APValue &V, const Expr *E) {
9156     Result.setFrom(V);
9157     return true;
9158   }
9159   bool ZeroInitialization(const Expr *E) {
9160     return Success((const ValueDecl*)nullptr);
9161   }
9162 
9163   bool VisitCastExpr(const CastExpr *E);
9164   bool VisitUnaryAddrOf(const UnaryOperator *E);
9165 };
9166 } // end anonymous namespace
9167 
9168 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9169                                   EvalInfo &Info) {
9170   assert(E->isRValue() && E->getType()->isMemberPointerType());
9171   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9172 }
9173 
9174 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9175   switch (E->getCastKind()) {
9176   default:
9177     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9178 
9179   case CK_NullToMemberPointer:
9180     VisitIgnoredValue(E->getSubExpr());
9181     return ZeroInitialization(E);
9182 
9183   case CK_BaseToDerivedMemberPointer: {
9184     if (!Visit(E->getSubExpr()))
9185       return false;
9186     if (E->path_empty())
9187       return true;
9188     // Base-to-derived member pointer casts store the path in derived-to-base
9189     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9190     // the wrong end of the derived->base arc, so stagger the path by one class.
9191     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9192     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9193          PathI != PathE; ++PathI) {
9194       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9195       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9196       if (!Result.castToDerived(Derived))
9197         return Error(E);
9198     }
9199     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9200     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9201       return Error(E);
9202     return true;
9203   }
9204 
9205   case CK_DerivedToBaseMemberPointer:
9206     if (!Visit(E->getSubExpr()))
9207       return false;
9208     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9209          PathE = E->path_end(); PathI != PathE; ++PathI) {
9210       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9211       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9212       if (!Result.castToBase(Base))
9213         return Error(E);
9214     }
9215     return true;
9216   }
9217 }
9218 
9219 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9220   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9221   // member can be formed.
9222   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9223 }
9224 
9225 //===----------------------------------------------------------------------===//
9226 // Record Evaluation
9227 //===----------------------------------------------------------------------===//
9228 
9229 namespace {
9230   class RecordExprEvaluator
9231   : public ExprEvaluatorBase<RecordExprEvaluator> {
9232     const LValue &This;
9233     APValue &Result;
9234   public:
9235 
9236     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9237       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9238 
9239     bool Success(const APValue &V, const Expr *E) {
9240       Result = V;
9241       return true;
9242     }
9243     bool ZeroInitialization(const Expr *E) {
9244       return ZeroInitialization(E, E->getType());
9245     }
9246     bool ZeroInitialization(const Expr *E, QualType T);
9247 
9248     bool VisitCallExpr(const CallExpr *E) {
9249       return handleCallExpr(E, Result, &This);
9250     }
9251     bool VisitCastExpr(const CastExpr *E);
9252     bool VisitInitListExpr(const InitListExpr *E);
9253     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9254       return VisitCXXConstructExpr(E, E->getType());
9255     }
9256     bool VisitLambdaExpr(const LambdaExpr *E);
9257     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9258     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9259     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9260     bool VisitBinCmp(const BinaryOperator *E);
9261   };
9262 }
9263 
9264 /// Perform zero-initialization on an object of non-union class type.
9265 /// C++11 [dcl.init]p5:
9266 ///  To zero-initialize an object or reference of type T means:
9267 ///    [...]
9268 ///    -- if T is a (possibly cv-qualified) non-union class type,
9269 ///       each non-static data member and each base-class subobject is
9270 ///       zero-initialized
9271 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9272                                           const RecordDecl *RD,
9273                                           const LValue &This, APValue &Result) {
9274   assert(!RD->isUnion() && "Expected non-union class type");
9275   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9276   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9277                    std::distance(RD->field_begin(), RD->field_end()));
9278 
9279   if (RD->isInvalidDecl()) return false;
9280   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9281 
9282   if (CD) {
9283     unsigned Index = 0;
9284     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9285            End = CD->bases_end(); I != End; ++I, ++Index) {
9286       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9287       LValue Subobject = This;
9288       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9289         return false;
9290       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9291                                          Result.getStructBase(Index)))
9292         return false;
9293     }
9294   }
9295 
9296   for (const auto *I : RD->fields()) {
9297     // -- if T is a reference type, no initialization is performed.
9298     if (I->getType()->isReferenceType())
9299       continue;
9300 
9301     LValue Subobject = This;
9302     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9303       return false;
9304 
9305     ImplicitValueInitExpr VIE(I->getType());
9306     if (!EvaluateInPlace(
9307           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9308       return false;
9309   }
9310 
9311   return true;
9312 }
9313 
9314 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9315   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9316   if (RD->isInvalidDecl()) return false;
9317   if (RD->isUnion()) {
9318     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9319     // object's first non-static named data member is zero-initialized
9320     RecordDecl::field_iterator I = RD->field_begin();
9321     if (I == RD->field_end()) {
9322       Result = APValue((const FieldDecl*)nullptr);
9323       return true;
9324     }
9325 
9326     LValue Subobject = This;
9327     if (!HandleLValueMember(Info, E, Subobject, *I))
9328       return false;
9329     Result = APValue(*I);
9330     ImplicitValueInitExpr VIE(I->getType());
9331     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9332   }
9333 
9334   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9335     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9336     return false;
9337   }
9338 
9339   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9340 }
9341 
9342 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9343   switch (E->getCastKind()) {
9344   default:
9345     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9346 
9347   case CK_ConstructorConversion:
9348     return Visit(E->getSubExpr());
9349 
9350   case CK_DerivedToBase:
9351   case CK_UncheckedDerivedToBase: {
9352     APValue DerivedObject;
9353     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9354       return false;
9355     if (!DerivedObject.isStruct())
9356       return Error(E->getSubExpr());
9357 
9358     // Derived-to-base rvalue conversion: just slice off the derived part.
9359     APValue *Value = &DerivedObject;
9360     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9361     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9362          PathE = E->path_end(); PathI != PathE; ++PathI) {
9363       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9364       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9365       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9366       RD = Base;
9367     }
9368     Result = *Value;
9369     return true;
9370   }
9371   }
9372 }
9373 
9374 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9375   if (E->isTransparent())
9376     return Visit(E->getInit(0));
9377 
9378   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9379   if (RD->isInvalidDecl()) return false;
9380   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9381   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9382 
9383   EvalInfo::EvaluatingConstructorRAII EvalObj(
9384       Info,
9385       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9386       CXXRD && CXXRD->getNumBases());
9387 
9388   if (RD->isUnion()) {
9389     const FieldDecl *Field = E->getInitializedFieldInUnion();
9390     Result = APValue(Field);
9391     if (!Field)
9392       return true;
9393 
9394     // If the initializer list for a union does not contain any elements, the
9395     // first element of the union is value-initialized.
9396     // FIXME: The element should be initialized from an initializer list.
9397     //        Is this difference ever observable for initializer lists which
9398     //        we don't build?
9399     ImplicitValueInitExpr VIE(Field->getType());
9400     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9401 
9402     LValue Subobject = This;
9403     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9404       return false;
9405 
9406     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9407     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9408                                   isa<CXXDefaultInitExpr>(InitExpr));
9409 
9410     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9411   }
9412 
9413   if (!Result.hasValue())
9414     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9415                      std::distance(RD->field_begin(), RD->field_end()));
9416   unsigned ElementNo = 0;
9417   bool Success = true;
9418 
9419   // Initialize base classes.
9420   if (CXXRD && CXXRD->getNumBases()) {
9421     for (const auto &Base : CXXRD->bases()) {
9422       assert(ElementNo < E->getNumInits() && "missing init for base class");
9423       const Expr *Init = E->getInit(ElementNo);
9424 
9425       LValue Subobject = This;
9426       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9427         return false;
9428 
9429       APValue &FieldVal = Result.getStructBase(ElementNo);
9430       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9431         if (!Info.noteFailure())
9432           return false;
9433         Success = false;
9434       }
9435       ++ElementNo;
9436     }
9437 
9438     EvalObj.finishedConstructingBases();
9439   }
9440 
9441   // Initialize members.
9442   for (const auto *Field : RD->fields()) {
9443     // Anonymous bit-fields are not considered members of the class for
9444     // purposes of aggregate initialization.
9445     if (Field->isUnnamedBitfield())
9446       continue;
9447 
9448     LValue Subobject = This;
9449 
9450     bool HaveInit = ElementNo < E->getNumInits();
9451 
9452     // FIXME: Diagnostics here should point to the end of the initializer
9453     // list, not the start.
9454     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9455                             Subobject, Field, &Layout))
9456       return false;
9457 
9458     // Perform an implicit value-initialization for members beyond the end of
9459     // the initializer list.
9460     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9461     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9462 
9463     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9464     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9465                                   isa<CXXDefaultInitExpr>(Init));
9466 
9467     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9468     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9469         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9470                                                        FieldVal, Field))) {
9471       if (!Info.noteFailure())
9472         return false;
9473       Success = false;
9474     }
9475   }
9476 
9477   EvalObj.finishedConstructingFields();
9478 
9479   return Success;
9480 }
9481 
9482 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9483                                                 QualType T) {
9484   // Note that E's type is not necessarily the type of our class here; we might
9485   // be initializing an array element instead.
9486   const CXXConstructorDecl *FD = E->getConstructor();
9487   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9488 
9489   bool ZeroInit = E->requiresZeroInitialization();
9490   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9491     // If we've already performed zero-initialization, we're already done.
9492     if (Result.hasValue())
9493       return true;
9494 
9495     if (ZeroInit)
9496       return ZeroInitialization(E, T);
9497 
9498     return getDefaultInitValue(T, Result);
9499   }
9500 
9501   const FunctionDecl *Definition = nullptr;
9502   auto Body = FD->getBody(Definition);
9503 
9504   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9505     return false;
9506 
9507   // Avoid materializing a temporary for an elidable copy/move constructor.
9508   if (E->isElidable() && !ZeroInit)
9509     if (const MaterializeTemporaryExpr *ME
9510           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9511       return Visit(ME->getSubExpr());
9512 
9513   if (ZeroInit && !ZeroInitialization(E, T))
9514     return false;
9515 
9516   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9517   return HandleConstructorCall(E, This, Args,
9518                                cast<CXXConstructorDecl>(Definition), Info,
9519                                Result);
9520 }
9521 
9522 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9523     const CXXInheritedCtorInitExpr *E) {
9524   if (!Info.CurrentCall) {
9525     assert(Info.checkingPotentialConstantExpression());
9526     return false;
9527   }
9528 
9529   const CXXConstructorDecl *FD = E->getConstructor();
9530   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9531     return false;
9532 
9533   const FunctionDecl *Definition = nullptr;
9534   auto Body = FD->getBody(Definition);
9535 
9536   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9537     return false;
9538 
9539   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9540                                cast<CXXConstructorDecl>(Definition), Info,
9541                                Result);
9542 }
9543 
9544 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9545     const CXXStdInitializerListExpr *E) {
9546   const ConstantArrayType *ArrayType =
9547       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9548 
9549   LValue Array;
9550   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9551     return false;
9552 
9553   // Get a pointer to the first element of the array.
9554   Array.addArray(Info, E, ArrayType);
9555 
9556   auto InvalidType = [&] {
9557     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9558       << E->getType();
9559     return false;
9560   };
9561 
9562   // FIXME: Perform the checks on the field types in SemaInit.
9563   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9564   RecordDecl::field_iterator Field = Record->field_begin();
9565   if (Field == Record->field_end())
9566     return InvalidType();
9567 
9568   // Start pointer.
9569   if (!Field->getType()->isPointerType() ||
9570       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9571                             ArrayType->getElementType()))
9572     return InvalidType();
9573 
9574   // FIXME: What if the initializer_list type has base classes, etc?
9575   Result = APValue(APValue::UninitStruct(), 0, 2);
9576   Array.moveInto(Result.getStructField(0));
9577 
9578   if (++Field == Record->field_end())
9579     return InvalidType();
9580 
9581   if (Field->getType()->isPointerType() &&
9582       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9583                            ArrayType->getElementType())) {
9584     // End pointer.
9585     if (!HandleLValueArrayAdjustment(Info, E, Array,
9586                                      ArrayType->getElementType(),
9587                                      ArrayType->getSize().getZExtValue()))
9588       return false;
9589     Array.moveInto(Result.getStructField(1));
9590   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9591     // Length.
9592     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9593   else
9594     return InvalidType();
9595 
9596   if (++Field != Record->field_end())
9597     return InvalidType();
9598 
9599   return true;
9600 }
9601 
9602 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9603   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9604   if (ClosureClass->isInvalidDecl())
9605     return false;
9606 
9607   const size_t NumFields =
9608       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9609 
9610   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9611                                             E->capture_init_end()) &&
9612          "The number of lambda capture initializers should equal the number of "
9613          "fields within the closure type");
9614 
9615   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9616   // Iterate through all the lambda's closure object's fields and initialize
9617   // them.
9618   auto *CaptureInitIt = E->capture_init_begin();
9619   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9620   bool Success = true;
9621   for (const auto *Field : ClosureClass->fields()) {
9622     assert(CaptureInitIt != E->capture_init_end());
9623     // Get the initializer for this field
9624     Expr *const CurFieldInit = *CaptureInitIt++;
9625 
9626     // If there is no initializer, either this is a VLA or an error has
9627     // occurred.
9628     if (!CurFieldInit)
9629       return Error(E);
9630 
9631     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9632     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9633       if (!Info.keepEvaluatingAfterFailure())
9634         return false;
9635       Success = false;
9636     }
9637     ++CaptureIt;
9638   }
9639   return Success;
9640 }
9641 
9642 static bool EvaluateRecord(const Expr *E, const LValue &This,
9643                            APValue &Result, EvalInfo &Info) {
9644   assert(E->isRValue() && E->getType()->isRecordType() &&
9645          "can't evaluate expression as a record rvalue");
9646   return RecordExprEvaluator(Info, This, Result).Visit(E);
9647 }
9648 
9649 //===----------------------------------------------------------------------===//
9650 // Temporary Evaluation
9651 //
9652 // Temporaries are represented in the AST as rvalues, but generally behave like
9653 // lvalues. The full-object of which the temporary is a subobject is implicitly
9654 // materialized so that a reference can bind to it.
9655 //===----------------------------------------------------------------------===//
9656 namespace {
9657 class TemporaryExprEvaluator
9658   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9659 public:
9660   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9661     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9662 
9663   /// Visit an expression which constructs the value of this temporary.
9664   bool VisitConstructExpr(const Expr *E) {
9665     APValue &Value =
9666         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9667     return EvaluateInPlace(Value, Info, Result, E);
9668   }
9669 
9670   bool VisitCastExpr(const CastExpr *E) {
9671     switch (E->getCastKind()) {
9672     default:
9673       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9674 
9675     case CK_ConstructorConversion:
9676       return VisitConstructExpr(E->getSubExpr());
9677     }
9678   }
9679   bool VisitInitListExpr(const InitListExpr *E) {
9680     return VisitConstructExpr(E);
9681   }
9682   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9683     return VisitConstructExpr(E);
9684   }
9685   bool VisitCallExpr(const CallExpr *E) {
9686     return VisitConstructExpr(E);
9687   }
9688   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9689     return VisitConstructExpr(E);
9690   }
9691   bool VisitLambdaExpr(const LambdaExpr *E) {
9692     return VisitConstructExpr(E);
9693   }
9694 };
9695 } // end anonymous namespace
9696 
9697 /// Evaluate an expression of record type as a temporary.
9698 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9699   assert(E->isRValue() && E->getType()->isRecordType());
9700   return TemporaryExprEvaluator(Info, Result).Visit(E);
9701 }
9702 
9703 //===----------------------------------------------------------------------===//
9704 // Vector Evaluation
9705 //===----------------------------------------------------------------------===//
9706 
9707 namespace {
9708   class VectorExprEvaluator
9709   : public ExprEvaluatorBase<VectorExprEvaluator> {
9710     APValue &Result;
9711   public:
9712 
9713     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9714       : ExprEvaluatorBaseTy(info), Result(Result) {}
9715 
9716     bool Success(ArrayRef<APValue> V, const Expr *E) {
9717       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9718       // FIXME: remove this APValue copy.
9719       Result = APValue(V.data(), V.size());
9720       return true;
9721     }
9722     bool Success(const APValue &V, const Expr *E) {
9723       assert(V.isVector());
9724       Result = V;
9725       return true;
9726     }
9727     bool ZeroInitialization(const Expr *E);
9728 
9729     bool VisitUnaryReal(const UnaryOperator *E)
9730       { return Visit(E->getSubExpr()); }
9731     bool VisitCastExpr(const CastExpr* E);
9732     bool VisitInitListExpr(const InitListExpr *E);
9733     bool VisitUnaryImag(const UnaryOperator *E);
9734     bool VisitBinaryOperator(const BinaryOperator *E);
9735     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
9736     //                 conditional select), shufflevector, ExtVectorElementExpr
9737   };
9738 } // end anonymous namespace
9739 
9740 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9741   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9742   return VectorExprEvaluator(Info, Result).Visit(E);
9743 }
9744 
9745 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9746   const VectorType *VTy = E->getType()->castAs<VectorType>();
9747   unsigned NElts = VTy->getNumElements();
9748 
9749   const Expr *SE = E->getSubExpr();
9750   QualType SETy = SE->getType();
9751 
9752   switch (E->getCastKind()) {
9753   case CK_VectorSplat: {
9754     APValue Val = APValue();
9755     if (SETy->isIntegerType()) {
9756       APSInt IntResult;
9757       if (!EvaluateInteger(SE, IntResult, Info))
9758         return false;
9759       Val = APValue(std::move(IntResult));
9760     } else if (SETy->isRealFloatingType()) {
9761       APFloat FloatResult(0.0);
9762       if (!EvaluateFloat(SE, FloatResult, Info))
9763         return false;
9764       Val = APValue(std::move(FloatResult));
9765     } else {
9766       return Error(E);
9767     }
9768 
9769     // Splat and create vector APValue.
9770     SmallVector<APValue, 4> Elts(NElts, Val);
9771     return Success(Elts, E);
9772   }
9773   case CK_BitCast: {
9774     // Evaluate the operand into an APInt we can extract from.
9775     llvm::APInt SValInt;
9776     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9777       return false;
9778     // Extract the elements
9779     QualType EltTy = VTy->getElementType();
9780     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9781     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9782     SmallVector<APValue, 4> Elts;
9783     if (EltTy->isRealFloatingType()) {
9784       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9785       unsigned FloatEltSize = EltSize;
9786       if (&Sem == &APFloat::x87DoubleExtended())
9787         FloatEltSize = 80;
9788       for (unsigned i = 0; i < NElts; i++) {
9789         llvm::APInt Elt;
9790         if (BigEndian)
9791           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9792         else
9793           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9794         Elts.push_back(APValue(APFloat(Sem, Elt)));
9795       }
9796     } else if (EltTy->isIntegerType()) {
9797       for (unsigned i = 0; i < NElts; i++) {
9798         llvm::APInt Elt;
9799         if (BigEndian)
9800           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9801         else
9802           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9803         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9804       }
9805     } else {
9806       return Error(E);
9807     }
9808     return Success(Elts, E);
9809   }
9810   default:
9811     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9812   }
9813 }
9814 
9815 bool
9816 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9817   const VectorType *VT = E->getType()->castAs<VectorType>();
9818   unsigned NumInits = E->getNumInits();
9819   unsigned NumElements = VT->getNumElements();
9820 
9821   QualType EltTy = VT->getElementType();
9822   SmallVector<APValue, 4> Elements;
9823 
9824   // The number of initializers can be less than the number of
9825   // vector elements. For OpenCL, this can be due to nested vector
9826   // initialization. For GCC compatibility, missing trailing elements
9827   // should be initialized with zeroes.
9828   unsigned CountInits = 0, CountElts = 0;
9829   while (CountElts < NumElements) {
9830     // Handle nested vector initialization.
9831     if (CountInits < NumInits
9832         && E->getInit(CountInits)->getType()->isVectorType()) {
9833       APValue v;
9834       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9835         return Error(E);
9836       unsigned vlen = v.getVectorLength();
9837       for (unsigned j = 0; j < vlen; j++)
9838         Elements.push_back(v.getVectorElt(j));
9839       CountElts += vlen;
9840     } else if (EltTy->isIntegerType()) {
9841       llvm::APSInt sInt(32);
9842       if (CountInits < NumInits) {
9843         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9844           return false;
9845       } else // trailing integer zero.
9846         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9847       Elements.push_back(APValue(sInt));
9848       CountElts++;
9849     } else {
9850       llvm::APFloat f(0.0);
9851       if (CountInits < NumInits) {
9852         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9853           return false;
9854       } else // trailing float zero.
9855         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9856       Elements.push_back(APValue(f));
9857       CountElts++;
9858     }
9859     CountInits++;
9860   }
9861   return Success(Elements, E);
9862 }
9863 
9864 bool
9865 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9866   const auto *VT = E->getType()->castAs<VectorType>();
9867   QualType EltTy = VT->getElementType();
9868   APValue ZeroElement;
9869   if (EltTy->isIntegerType())
9870     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9871   else
9872     ZeroElement =
9873         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9874 
9875   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9876   return Success(Elements, E);
9877 }
9878 
9879 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9880   VisitIgnoredValue(E->getSubExpr());
9881   return ZeroInitialization(E);
9882 }
9883 
9884 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9885   BinaryOperatorKind Op = E->getOpcode();
9886   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
9887          "Operation not supported on vector types");
9888 
9889   if (Op == BO_Comma)
9890     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9891 
9892   Expr *LHS = E->getLHS();
9893   Expr *RHS = E->getRHS();
9894 
9895   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
9896          "Must both be vector types");
9897   // Checking JUST the types are the same would be fine, except shifts don't
9898   // need to have their types be the same (since you always shift by an int).
9899   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
9900              E->getType()->getAs<VectorType>()->getNumElements() &&
9901          RHS->getType()->getAs<VectorType>()->getNumElements() ==
9902              E->getType()->getAs<VectorType>()->getNumElements() &&
9903          "All operands must be the same size.");
9904 
9905   APValue LHSValue;
9906   APValue RHSValue;
9907   bool LHSOK = Evaluate(LHSValue, Info, LHS);
9908   if (!LHSOK && !Info.noteFailure())
9909     return false;
9910   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
9911     return false;
9912 
9913   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
9914     return false;
9915 
9916   return Success(LHSValue, E);
9917 }
9918 
9919 //===----------------------------------------------------------------------===//
9920 // Array Evaluation
9921 //===----------------------------------------------------------------------===//
9922 
9923 namespace {
9924   class ArrayExprEvaluator
9925   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9926     const LValue &This;
9927     APValue &Result;
9928   public:
9929 
9930     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9931       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9932 
9933     bool Success(const APValue &V, const Expr *E) {
9934       assert(V.isArray() && "expected array");
9935       Result = V;
9936       return true;
9937     }
9938 
9939     bool ZeroInitialization(const Expr *E) {
9940       const ConstantArrayType *CAT =
9941           Info.Ctx.getAsConstantArrayType(E->getType());
9942       if (!CAT) {
9943         if (E->getType()->isIncompleteArrayType()) {
9944           // We can be asked to zero-initialize a flexible array member; this
9945           // is represented as an ImplicitValueInitExpr of incomplete array
9946           // type. In this case, the array has zero elements.
9947           Result = APValue(APValue::UninitArray(), 0, 0);
9948           return true;
9949         }
9950         // FIXME: We could handle VLAs here.
9951         return Error(E);
9952       }
9953 
9954       Result = APValue(APValue::UninitArray(), 0,
9955                        CAT->getSize().getZExtValue());
9956       if (!Result.hasArrayFiller()) return true;
9957 
9958       // Zero-initialize all elements.
9959       LValue Subobject = This;
9960       Subobject.addArray(Info, E, CAT);
9961       ImplicitValueInitExpr VIE(CAT->getElementType());
9962       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9963     }
9964 
9965     bool VisitCallExpr(const CallExpr *E) {
9966       return handleCallExpr(E, Result, &This);
9967     }
9968     bool VisitInitListExpr(const InitListExpr *E,
9969                            QualType AllocType = QualType());
9970     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9971     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9972     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9973                                const LValue &Subobject,
9974                                APValue *Value, QualType Type);
9975     bool VisitStringLiteral(const StringLiteral *E,
9976                             QualType AllocType = QualType()) {
9977       expandStringLiteral(Info, E, Result, AllocType);
9978       return true;
9979     }
9980   };
9981 } // end anonymous namespace
9982 
9983 static bool EvaluateArray(const Expr *E, const LValue &This,
9984                           APValue &Result, EvalInfo &Info) {
9985   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9986   return ArrayExprEvaluator(Info, This, Result).Visit(E);
9987 }
9988 
9989 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9990                                      APValue &Result, const InitListExpr *ILE,
9991                                      QualType AllocType) {
9992   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9993          "not an array rvalue");
9994   return ArrayExprEvaluator(Info, This, Result)
9995       .VisitInitListExpr(ILE, AllocType);
9996 }
9997 
9998 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9999                                           APValue &Result,
10000                                           const CXXConstructExpr *CCE,
10001                                           QualType AllocType) {
10002   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10003          "not an array rvalue");
10004   return ArrayExprEvaluator(Info, This, Result)
10005       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10006 }
10007 
10008 // Return true iff the given array filler may depend on the element index.
10009 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10010   // For now, just allow non-class value-initialization and initialization
10011   // lists comprised of them.
10012   if (isa<ImplicitValueInitExpr>(FillerExpr))
10013     return false;
10014   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10015     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10016       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10017         return true;
10018     }
10019     return false;
10020   }
10021   return true;
10022 }
10023 
10024 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10025                                            QualType AllocType) {
10026   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10027       AllocType.isNull() ? E->getType() : AllocType);
10028   if (!CAT)
10029     return Error(E);
10030 
10031   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10032   // an appropriately-typed string literal enclosed in braces.
10033   if (E->isStringLiteralInit()) {
10034     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10035     // FIXME: Support ObjCEncodeExpr here once we support it in
10036     // ArrayExprEvaluator generally.
10037     if (!SL)
10038       return Error(E);
10039     return VisitStringLiteral(SL, AllocType);
10040   }
10041 
10042   bool Success = true;
10043 
10044   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10045          "zero-initialized array shouldn't have any initialized elts");
10046   APValue Filler;
10047   if (Result.isArray() && Result.hasArrayFiller())
10048     Filler = Result.getArrayFiller();
10049 
10050   unsigned NumEltsToInit = E->getNumInits();
10051   unsigned NumElts = CAT->getSize().getZExtValue();
10052   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10053 
10054   // If the initializer might depend on the array index, run it for each
10055   // array element.
10056   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10057     NumEltsToInit = NumElts;
10058 
10059   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10060                           << NumEltsToInit << ".\n");
10061 
10062   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10063 
10064   // If the array was previously zero-initialized, preserve the
10065   // zero-initialized values.
10066   if (Filler.hasValue()) {
10067     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10068       Result.getArrayInitializedElt(I) = Filler;
10069     if (Result.hasArrayFiller())
10070       Result.getArrayFiller() = Filler;
10071   }
10072 
10073   LValue Subobject = This;
10074   Subobject.addArray(Info, E, CAT);
10075   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10076     const Expr *Init =
10077         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10078     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10079                          Info, Subobject, Init) ||
10080         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10081                                      CAT->getElementType(), 1)) {
10082       if (!Info.noteFailure())
10083         return false;
10084       Success = false;
10085     }
10086   }
10087 
10088   if (!Result.hasArrayFiller())
10089     return Success;
10090 
10091   // If we get here, we have a trivial filler, which we can just evaluate
10092   // once and splat over the rest of the array elements.
10093   assert(FillerExpr && "no array filler for incomplete init list");
10094   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10095                          FillerExpr) && Success;
10096 }
10097 
10098 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10099   LValue CommonLV;
10100   if (E->getCommonExpr() &&
10101       !Evaluate(Info.CurrentCall->createTemporary(
10102                     E->getCommonExpr(),
10103                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
10104                     CommonLV),
10105                 Info, E->getCommonExpr()->getSourceExpr()))
10106     return false;
10107 
10108   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10109 
10110   uint64_t Elements = CAT->getSize().getZExtValue();
10111   Result = APValue(APValue::UninitArray(), Elements, Elements);
10112 
10113   LValue Subobject = This;
10114   Subobject.addArray(Info, E, CAT);
10115 
10116   bool Success = true;
10117   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10118     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10119                          Info, Subobject, E->getSubExpr()) ||
10120         !HandleLValueArrayAdjustment(Info, E, Subobject,
10121                                      CAT->getElementType(), 1)) {
10122       if (!Info.noteFailure())
10123         return false;
10124       Success = false;
10125     }
10126   }
10127 
10128   return Success;
10129 }
10130 
10131 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10132   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10133 }
10134 
10135 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10136                                                const LValue &Subobject,
10137                                                APValue *Value,
10138                                                QualType Type) {
10139   bool HadZeroInit = Value->hasValue();
10140 
10141   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10142     unsigned N = CAT->getSize().getZExtValue();
10143 
10144     // Preserve the array filler if we had prior zero-initialization.
10145     APValue Filler =
10146       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10147                                              : APValue();
10148 
10149     *Value = APValue(APValue::UninitArray(), N, N);
10150 
10151     if (HadZeroInit)
10152       for (unsigned I = 0; I != N; ++I)
10153         Value->getArrayInitializedElt(I) = Filler;
10154 
10155     // Initialize the elements.
10156     LValue ArrayElt = Subobject;
10157     ArrayElt.addArray(Info, E, CAT);
10158     for (unsigned I = 0; I != N; ++I)
10159       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10160                                  CAT->getElementType()) ||
10161           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10162                                        CAT->getElementType(), 1))
10163         return false;
10164 
10165     return true;
10166   }
10167 
10168   if (!Type->isRecordType())
10169     return Error(E);
10170 
10171   return RecordExprEvaluator(Info, Subobject, *Value)
10172              .VisitCXXConstructExpr(E, Type);
10173 }
10174 
10175 //===----------------------------------------------------------------------===//
10176 // Integer Evaluation
10177 //
10178 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10179 // types and back in constant folding. Integer values are thus represented
10180 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10181 //===----------------------------------------------------------------------===//
10182 
10183 namespace {
10184 class IntExprEvaluator
10185         : public ExprEvaluatorBase<IntExprEvaluator> {
10186   APValue &Result;
10187 public:
10188   IntExprEvaluator(EvalInfo &info, APValue &result)
10189       : ExprEvaluatorBaseTy(info), Result(result) {}
10190 
10191   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10192     assert(E->getType()->isIntegralOrEnumerationType() &&
10193            "Invalid evaluation result.");
10194     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10195            "Invalid evaluation result.");
10196     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10197            "Invalid evaluation result.");
10198     Result = APValue(SI);
10199     return true;
10200   }
10201   bool Success(const llvm::APSInt &SI, const Expr *E) {
10202     return Success(SI, E, Result);
10203   }
10204 
10205   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10206     assert(E->getType()->isIntegralOrEnumerationType() &&
10207            "Invalid evaluation result.");
10208     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10209            "Invalid evaluation result.");
10210     Result = APValue(APSInt(I));
10211     Result.getInt().setIsUnsigned(
10212                             E->getType()->isUnsignedIntegerOrEnumerationType());
10213     return true;
10214   }
10215   bool Success(const llvm::APInt &I, const Expr *E) {
10216     return Success(I, E, Result);
10217   }
10218 
10219   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10220     assert(E->getType()->isIntegralOrEnumerationType() &&
10221            "Invalid evaluation result.");
10222     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10223     return true;
10224   }
10225   bool Success(uint64_t Value, const Expr *E) {
10226     return Success(Value, E, Result);
10227   }
10228 
10229   bool Success(CharUnits Size, const Expr *E) {
10230     return Success(Size.getQuantity(), E);
10231   }
10232 
10233   bool Success(const APValue &V, const Expr *E) {
10234     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10235       Result = V;
10236       return true;
10237     }
10238     return Success(V.getInt(), E);
10239   }
10240 
10241   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10242 
10243   //===--------------------------------------------------------------------===//
10244   //                            Visitor Methods
10245   //===--------------------------------------------------------------------===//
10246 
10247   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10248     return Success(E->getValue(), E);
10249   }
10250   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10251     return Success(E->getValue(), E);
10252   }
10253 
10254   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10255   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10256     if (CheckReferencedDecl(E, E->getDecl()))
10257       return true;
10258 
10259     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10260   }
10261   bool VisitMemberExpr(const MemberExpr *E) {
10262     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10263       VisitIgnoredBaseExpression(E->getBase());
10264       return true;
10265     }
10266 
10267     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10268   }
10269 
10270   bool VisitCallExpr(const CallExpr *E);
10271   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10272   bool VisitBinaryOperator(const BinaryOperator *E);
10273   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10274   bool VisitUnaryOperator(const UnaryOperator *E);
10275 
10276   bool VisitCastExpr(const CastExpr* E);
10277   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10278 
10279   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10280     return Success(E->getValue(), E);
10281   }
10282 
10283   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10284     return Success(E->getValue(), E);
10285   }
10286 
10287   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10288     if (Info.ArrayInitIndex == uint64_t(-1)) {
10289       // We were asked to evaluate this subexpression independent of the
10290       // enclosing ArrayInitLoopExpr. We can't do that.
10291       Info.FFDiag(E);
10292       return false;
10293     }
10294     return Success(Info.ArrayInitIndex, E);
10295   }
10296 
10297   // Note, GNU defines __null as an integer, not a pointer.
10298   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10299     return ZeroInitialization(E);
10300   }
10301 
10302   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10303     return Success(E->getValue(), E);
10304   }
10305 
10306   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10307     return Success(E->getValue(), E);
10308   }
10309 
10310   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10311     return Success(E->getValue(), E);
10312   }
10313 
10314   bool VisitUnaryReal(const UnaryOperator *E);
10315   bool VisitUnaryImag(const UnaryOperator *E);
10316 
10317   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10318   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10319   bool VisitSourceLocExpr(const SourceLocExpr *E);
10320   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10321   bool VisitRequiresExpr(const RequiresExpr *E);
10322   // FIXME: Missing: array subscript of vector, member of vector
10323 };
10324 
10325 class FixedPointExprEvaluator
10326     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10327   APValue &Result;
10328 
10329  public:
10330   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10331       : ExprEvaluatorBaseTy(info), Result(result) {}
10332 
10333   bool Success(const llvm::APInt &I, const Expr *E) {
10334     return Success(
10335         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10336   }
10337 
10338   bool Success(uint64_t Value, const Expr *E) {
10339     return Success(
10340         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10341   }
10342 
10343   bool Success(const APValue &V, const Expr *E) {
10344     return Success(V.getFixedPoint(), E);
10345   }
10346 
10347   bool Success(const APFixedPoint &V, const Expr *E) {
10348     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10349     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10350            "Invalid evaluation result.");
10351     Result = APValue(V);
10352     return true;
10353   }
10354 
10355   //===--------------------------------------------------------------------===//
10356   //                            Visitor Methods
10357   //===--------------------------------------------------------------------===//
10358 
10359   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10360     return Success(E->getValue(), E);
10361   }
10362 
10363   bool VisitCastExpr(const CastExpr *E);
10364   bool VisitUnaryOperator(const UnaryOperator *E);
10365   bool VisitBinaryOperator(const BinaryOperator *E);
10366 };
10367 } // end anonymous namespace
10368 
10369 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10370 /// produce either the integer value or a pointer.
10371 ///
10372 /// GCC has a heinous extension which folds casts between pointer types and
10373 /// pointer-sized integral types. We support this by allowing the evaluation of
10374 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10375 /// Some simple arithmetic on such values is supported (they are treated much
10376 /// like char*).
10377 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10378                                     EvalInfo &Info) {
10379   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10380   return IntExprEvaluator(Info, Result).Visit(E);
10381 }
10382 
10383 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10384   APValue Val;
10385   if (!EvaluateIntegerOrLValue(E, Val, Info))
10386     return false;
10387   if (!Val.isInt()) {
10388     // FIXME: It would be better to produce the diagnostic for casting
10389     //        a pointer to an integer.
10390     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10391     return false;
10392   }
10393   Result = Val.getInt();
10394   return true;
10395 }
10396 
10397 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10398   APValue Evaluated = E->EvaluateInContext(
10399       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10400   return Success(Evaluated, E);
10401 }
10402 
10403 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10404                                EvalInfo &Info) {
10405   if (E->getType()->isFixedPointType()) {
10406     APValue Val;
10407     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10408       return false;
10409     if (!Val.isFixedPoint())
10410       return false;
10411 
10412     Result = Val.getFixedPoint();
10413     return true;
10414   }
10415   return false;
10416 }
10417 
10418 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10419                                         EvalInfo &Info) {
10420   if (E->getType()->isIntegerType()) {
10421     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10422     APSInt Val;
10423     if (!EvaluateInteger(E, Val, Info))
10424       return false;
10425     Result = APFixedPoint(Val, FXSema);
10426     return true;
10427   } else if (E->getType()->isFixedPointType()) {
10428     return EvaluateFixedPoint(E, Result, Info);
10429   }
10430   return false;
10431 }
10432 
10433 /// Check whether the given declaration can be directly converted to an integral
10434 /// rvalue. If not, no diagnostic is produced; there are other things we can
10435 /// try.
10436 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10437   // Enums are integer constant exprs.
10438   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10439     // Check for signedness/width mismatches between E type and ECD value.
10440     bool SameSign = (ECD->getInitVal().isSigned()
10441                      == E->getType()->isSignedIntegerOrEnumerationType());
10442     bool SameWidth = (ECD->getInitVal().getBitWidth()
10443                       == Info.Ctx.getIntWidth(E->getType()));
10444     if (SameSign && SameWidth)
10445       return Success(ECD->getInitVal(), E);
10446     else {
10447       // Get rid of mismatch (otherwise Success assertions will fail)
10448       // by computing a new value matching the type of E.
10449       llvm::APSInt Val = ECD->getInitVal();
10450       if (!SameSign)
10451         Val.setIsSigned(!ECD->getInitVal().isSigned());
10452       if (!SameWidth)
10453         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10454       return Success(Val, E);
10455     }
10456   }
10457   return false;
10458 }
10459 
10460 /// Values returned by __builtin_classify_type, chosen to match the values
10461 /// produced by GCC's builtin.
10462 enum class GCCTypeClass {
10463   None = -1,
10464   Void = 0,
10465   Integer = 1,
10466   // GCC reserves 2 for character types, but instead classifies them as
10467   // integers.
10468   Enum = 3,
10469   Bool = 4,
10470   Pointer = 5,
10471   // GCC reserves 6 for references, but appears to never use it (because
10472   // expressions never have reference type, presumably).
10473   PointerToDataMember = 7,
10474   RealFloat = 8,
10475   Complex = 9,
10476   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10477   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10478   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10479   // uses 12 for that purpose, same as for a class or struct. Maybe it
10480   // internally implements a pointer to member as a struct?  Who knows.
10481   PointerToMemberFunction = 12, // Not a bug, see above.
10482   ClassOrStruct = 12,
10483   Union = 13,
10484   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10485   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10486   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10487   // literals.
10488 };
10489 
10490 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10491 /// as GCC.
10492 static GCCTypeClass
10493 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10494   assert(!T->isDependentType() && "unexpected dependent type");
10495 
10496   QualType CanTy = T.getCanonicalType();
10497   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10498 
10499   switch (CanTy->getTypeClass()) {
10500 #define TYPE(ID, BASE)
10501 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10502 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10503 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10504 #include "clang/AST/TypeNodes.inc"
10505   case Type::Auto:
10506   case Type::DeducedTemplateSpecialization:
10507       llvm_unreachable("unexpected non-canonical or dependent type");
10508 
10509   case Type::Builtin:
10510     switch (BT->getKind()) {
10511 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10512 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10513     case BuiltinType::ID: return GCCTypeClass::Integer;
10514 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10515     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10516 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10517     case BuiltinType::ID: break;
10518 #include "clang/AST/BuiltinTypes.def"
10519     case BuiltinType::Void:
10520       return GCCTypeClass::Void;
10521 
10522     case BuiltinType::Bool:
10523       return GCCTypeClass::Bool;
10524 
10525     case BuiltinType::Char_U:
10526     case BuiltinType::UChar:
10527     case BuiltinType::WChar_U:
10528     case BuiltinType::Char8:
10529     case BuiltinType::Char16:
10530     case BuiltinType::Char32:
10531     case BuiltinType::UShort:
10532     case BuiltinType::UInt:
10533     case BuiltinType::ULong:
10534     case BuiltinType::ULongLong:
10535     case BuiltinType::UInt128:
10536       return GCCTypeClass::Integer;
10537 
10538     case BuiltinType::UShortAccum:
10539     case BuiltinType::UAccum:
10540     case BuiltinType::ULongAccum:
10541     case BuiltinType::UShortFract:
10542     case BuiltinType::UFract:
10543     case BuiltinType::ULongFract:
10544     case BuiltinType::SatUShortAccum:
10545     case BuiltinType::SatUAccum:
10546     case BuiltinType::SatULongAccum:
10547     case BuiltinType::SatUShortFract:
10548     case BuiltinType::SatUFract:
10549     case BuiltinType::SatULongFract:
10550       return GCCTypeClass::None;
10551 
10552     case BuiltinType::NullPtr:
10553 
10554     case BuiltinType::ObjCId:
10555     case BuiltinType::ObjCClass:
10556     case BuiltinType::ObjCSel:
10557 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10558     case BuiltinType::Id:
10559 #include "clang/Basic/OpenCLImageTypes.def"
10560 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10561     case BuiltinType::Id:
10562 #include "clang/Basic/OpenCLExtensionTypes.def"
10563     case BuiltinType::OCLSampler:
10564     case BuiltinType::OCLEvent:
10565     case BuiltinType::OCLClkEvent:
10566     case BuiltinType::OCLQueue:
10567     case BuiltinType::OCLReserveID:
10568 #define SVE_TYPE(Name, Id, SingletonId) \
10569     case BuiltinType::Id:
10570 #include "clang/Basic/AArch64SVEACLETypes.def"
10571       return GCCTypeClass::None;
10572 
10573     case BuiltinType::Dependent:
10574       llvm_unreachable("unexpected dependent type");
10575     };
10576     llvm_unreachable("unexpected placeholder type");
10577 
10578   case Type::Enum:
10579     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10580 
10581   case Type::Pointer:
10582   case Type::ConstantArray:
10583   case Type::VariableArray:
10584   case Type::IncompleteArray:
10585   case Type::FunctionNoProto:
10586   case Type::FunctionProto:
10587     return GCCTypeClass::Pointer;
10588 
10589   case Type::MemberPointer:
10590     return CanTy->isMemberDataPointerType()
10591                ? GCCTypeClass::PointerToDataMember
10592                : GCCTypeClass::PointerToMemberFunction;
10593 
10594   case Type::Complex:
10595     return GCCTypeClass::Complex;
10596 
10597   case Type::Record:
10598     return CanTy->isUnionType() ? GCCTypeClass::Union
10599                                 : GCCTypeClass::ClassOrStruct;
10600 
10601   case Type::Atomic:
10602     // GCC classifies _Atomic T the same as T.
10603     return EvaluateBuiltinClassifyType(
10604         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10605 
10606   case Type::BlockPointer:
10607   case Type::Vector:
10608   case Type::ExtVector:
10609   case Type::ConstantMatrix:
10610   case Type::ObjCObject:
10611   case Type::ObjCInterface:
10612   case Type::ObjCObjectPointer:
10613   case Type::Pipe:
10614   case Type::ExtInt:
10615     // GCC classifies vectors as None. We follow its lead and classify all
10616     // other types that don't fit into the regular classification the same way.
10617     return GCCTypeClass::None;
10618 
10619   case Type::LValueReference:
10620   case Type::RValueReference:
10621     llvm_unreachable("invalid type for expression");
10622   }
10623 
10624   llvm_unreachable("unexpected type class");
10625 }
10626 
10627 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10628 /// as GCC.
10629 static GCCTypeClass
10630 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10631   // If no argument was supplied, default to None. This isn't
10632   // ideal, however it is what gcc does.
10633   if (E->getNumArgs() == 0)
10634     return GCCTypeClass::None;
10635 
10636   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10637   // being an ICE, but still folds it to a constant using the type of the first
10638   // argument.
10639   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10640 }
10641 
10642 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10643 /// __builtin_constant_p when applied to the given pointer.
10644 ///
10645 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10646 /// or it points to the first character of a string literal.
10647 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10648   APValue::LValueBase Base = LV.getLValueBase();
10649   if (Base.isNull()) {
10650     // A null base is acceptable.
10651     return true;
10652   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10653     if (!isa<StringLiteral>(E))
10654       return false;
10655     return LV.getLValueOffset().isZero();
10656   } else if (Base.is<TypeInfoLValue>()) {
10657     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10658     // evaluate to true.
10659     return true;
10660   } else {
10661     // Any other base is not constant enough for GCC.
10662     return false;
10663   }
10664 }
10665 
10666 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10667 /// GCC as we can manage.
10668 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10669   // This evaluation is not permitted to have side-effects, so evaluate it in
10670   // a speculative evaluation context.
10671   SpeculativeEvaluationRAII SpeculativeEval(Info);
10672 
10673   // Constant-folding is always enabled for the operand of __builtin_constant_p
10674   // (even when the enclosing evaluation context otherwise requires a strict
10675   // language-specific constant expression).
10676   FoldConstant Fold(Info, true);
10677 
10678   QualType ArgType = Arg->getType();
10679 
10680   // __builtin_constant_p always has one operand. The rules which gcc follows
10681   // are not precisely documented, but are as follows:
10682   //
10683   //  - If the operand is of integral, floating, complex or enumeration type,
10684   //    and can be folded to a known value of that type, it returns 1.
10685   //  - If the operand can be folded to a pointer to the first character
10686   //    of a string literal (or such a pointer cast to an integral type)
10687   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10688   //
10689   // Otherwise, it returns 0.
10690   //
10691   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10692   // its support for this did not work prior to GCC 9 and is not yet well
10693   // understood.
10694   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10695       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10696       ArgType->isNullPtrType()) {
10697     APValue V;
10698     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
10699       Fold.keepDiagnostics();
10700       return false;
10701     }
10702 
10703     // For a pointer (possibly cast to integer), there are special rules.
10704     if (V.getKind() == APValue::LValue)
10705       return EvaluateBuiltinConstantPForLValue(V);
10706 
10707     // Otherwise, any constant value is good enough.
10708     return V.hasValue();
10709   }
10710 
10711   // Anything else isn't considered to be sufficiently constant.
10712   return false;
10713 }
10714 
10715 /// Retrieves the "underlying object type" of the given expression,
10716 /// as used by __builtin_object_size.
10717 static QualType getObjectType(APValue::LValueBase B) {
10718   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10719     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10720       return VD->getType();
10721   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10722     if (isa<CompoundLiteralExpr>(E))
10723       return E->getType();
10724   } else if (B.is<TypeInfoLValue>()) {
10725     return B.getTypeInfoType();
10726   } else if (B.is<DynamicAllocLValue>()) {
10727     return B.getDynamicAllocType();
10728   }
10729 
10730   return QualType();
10731 }
10732 
10733 /// A more selective version of E->IgnoreParenCasts for
10734 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10735 /// to change the type of E.
10736 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10737 ///
10738 /// Always returns an RValue with a pointer representation.
10739 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10740   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10741 
10742   auto *NoParens = E->IgnoreParens();
10743   auto *Cast = dyn_cast<CastExpr>(NoParens);
10744   if (Cast == nullptr)
10745     return NoParens;
10746 
10747   // We only conservatively allow a few kinds of casts, because this code is
10748   // inherently a simple solution that seeks to support the common case.
10749   auto CastKind = Cast->getCastKind();
10750   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10751       CastKind != CK_AddressSpaceConversion)
10752     return NoParens;
10753 
10754   auto *SubExpr = Cast->getSubExpr();
10755   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10756     return NoParens;
10757   return ignorePointerCastsAndParens(SubExpr);
10758 }
10759 
10760 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10761 /// record layout. e.g.
10762 ///   struct { struct { int a, b; } fst, snd; } obj;
10763 ///   obj.fst   // no
10764 ///   obj.snd   // yes
10765 ///   obj.fst.a // no
10766 ///   obj.fst.b // no
10767 ///   obj.snd.a // no
10768 ///   obj.snd.b // yes
10769 ///
10770 /// Please note: this function is specialized for how __builtin_object_size
10771 /// views "objects".
10772 ///
10773 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10774 /// correct result, it will always return true.
10775 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10776   assert(!LVal.Designator.Invalid);
10777 
10778   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10779     const RecordDecl *Parent = FD->getParent();
10780     Invalid = Parent->isInvalidDecl();
10781     if (Invalid || Parent->isUnion())
10782       return true;
10783     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10784     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10785   };
10786 
10787   auto &Base = LVal.getLValueBase();
10788   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10789     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10790       bool Invalid;
10791       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10792         return Invalid;
10793     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10794       for (auto *FD : IFD->chain()) {
10795         bool Invalid;
10796         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10797           return Invalid;
10798       }
10799     }
10800   }
10801 
10802   unsigned I = 0;
10803   QualType BaseType = getType(Base);
10804   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10805     // If we don't know the array bound, conservatively assume we're looking at
10806     // the final array element.
10807     ++I;
10808     if (BaseType->isIncompleteArrayType())
10809       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10810     else
10811       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10812   }
10813 
10814   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10815     const auto &Entry = LVal.Designator.Entries[I];
10816     if (BaseType->isArrayType()) {
10817       // Because __builtin_object_size treats arrays as objects, we can ignore
10818       // the index iff this is the last array in the Designator.
10819       if (I + 1 == E)
10820         return true;
10821       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10822       uint64_t Index = Entry.getAsArrayIndex();
10823       if (Index + 1 != CAT->getSize())
10824         return false;
10825       BaseType = CAT->getElementType();
10826     } else if (BaseType->isAnyComplexType()) {
10827       const auto *CT = BaseType->castAs<ComplexType>();
10828       uint64_t Index = Entry.getAsArrayIndex();
10829       if (Index != 1)
10830         return false;
10831       BaseType = CT->getElementType();
10832     } else if (auto *FD = getAsField(Entry)) {
10833       bool Invalid;
10834       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10835         return Invalid;
10836       BaseType = FD->getType();
10837     } else {
10838       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10839       return false;
10840     }
10841   }
10842   return true;
10843 }
10844 
10845 /// Tests to see if the LValue has a user-specified designator (that isn't
10846 /// necessarily valid). Note that this always returns 'true' if the LValue has
10847 /// an unsized array as its first designator entry, because there's currently no
10848 /// way to tell if the user typed *foo or foo[0].
10849 static bool refersToCompleteObject(const LValue &LVal) {
10850   if (LVal.Designator.Invalid)
10851     return false;
10852 
10853   if (!LVal.Designator.Entries.empty())
10854     return LVal.Designator.isMostDerivedAnUnsizedArray();
10855 
10856   if (!LVal.InvalidBase)
10857     return true;
10858 
10859   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10860   // the LValueBase.
10861   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10862   return !E || !isa<MemberExpr>(E);
10863 }
10864 
10865 /// Attempts to detect a user writing into a piece of memory that's impossible
10866 /// to figure out the size of by just using types.
10867 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10868   const SubobjectDesignator &Designator = LVal.Designator;
10869   // Notes:
10870   // - Users can only write off of the end when we have an invalid base. Invalid
10871   //   bases imply we don't know where the memory came from.
10872   // - We used to be a bit more aggressive here; we'd only be conservative if
10873   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10874   //   broke some common standard library extensions (PR30346), but was
10875   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10876   //   with some sort of list. OTOH, it seems that GCC is always
10877   //   conservative with the last element in structs (if it's an array), so our
10878   //   current behavior is more compatible than an explicit list approach would
10879   //   be.
10880   return LVal.InvalidBase &&
10881          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10882          Designator.MostDerivedIsArrayElement &&
10883          isDesignatorAtObjectEnd(Ctx, LVal);
10884 }
10885 
10886 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10887 /// Fails if the conversion would cause loss of precision.
10888 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10889                                             CharUnits &Result) {
10890   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10891   if (Int.ugt(CharUnitsMax))
10892     return false;
10893   Result = CharUnits::fromQuantity(Int.getZExtValue());
10894   return true;
10895 }
10896 
10897 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10898 /// determine how many bytes exist from the beginning of the object to either
10899 /// the end of the current subobject, or the end of the object itself, depending
10900 /// on what the LValue looks like + the value of Type.
10901 ///
10902 /// If this returns false, the value of Result is undefined.
10903 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10904                                unsigned Type, const LValue &LVal,
10905                                CharUnits &EndOffset) {
10906   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10907 
10908   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10909     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10910       return false;
10911     return HandleSizeof(Info, ExprLoc, Ty, Result);
10912   };
10913 
10914   // We want to evaluate the size of the entire object. This is a valid fallback
10915   // for when Type=1 and the designator is invalid, because we're asked for an
10916   // upper-bound.
10917   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10918     // Type=3 wants a lower bound, so we can't fall back to this.
10919     if (Type == 3 && !DetermineForCompleteObject)
10920       return false;
10921 
10922     llvm::APInt APEndOffset;
10923     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10924         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10925       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10926 
10927     if (LVal.InvalidBase)
10928       return false;
10929 
10930     QualType BaseTy = getObjectType(LVal.getLValueBase());
10931     return CheckedHandleSizeof(BaseTy, EndOffset);
10932   }
10933 
10934   // We want to evaluate the size of a subobject.
10935   const SubobjectDesignator &Designator = LVal.Designator;
10936 
10937   // The following is a moderately common idiom in C:
10938   //
10939   // struct Foo { int a; char c[1]; };
10940   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10941   // strcpy(&F->c[0], Bar);
10942   //
10943   // In order to not break too much legacy code, we need to support it.
10944   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10945     // If we can resolve this to an alloc_size call, we can hand that back,
10946     // because we know for certain how many bytes there are to write to.
10947     llvm::APInt APEndOffset;
10948     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10949         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10950       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10951 
10952     // If we cannot determine the size of the initial allocation, then we can't
10953     // given an accurate upper-bound. However, we are still able to give
10954     // conservative lower-bounds for Type=3.
10955     if (Type == 1)
10956       return false;
10957   }
10958 
10959   CharUnits BytesPerElem;
10960   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10961     return false;
10962 
10963   // According to the GCC documentation, we want the size of the subobject
10964   // denoted by the pointer. But that's not quite right -- what we actually
10965   // want is the size of the immediately-enclosing array, if there is one.
10966   int64_t ElemsRemaining;
10967   if (Designator.MostDerivedIsArrayElement &&
10968       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10969     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10970     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10971     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10972   } else {
10973     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10974   }
10975 
10976   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10977   return true;
10978 }
10979 
10980 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10981 /// returns true and stores the result in @p Size.
10982 ///
10983 /// If @p WasError is non-null, this will report whether the failure to evaluate
10984 /// is to be treated as an Error in IntExprEvaluator.
10985 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10986                                          EvalInfo &Info, uint64_t &Size) {
10987   // Determine the denoted object.
10988   LValue LVal;
10989   {
10990     // The operand of __builtin_object_size is never evaluated for side-effects.
10991     // If there are any, but we can determine the pointed-to object anyway, then
10992     // ignore the side-effects.
10993     SpeculativeEvaluationRAII SpeculativeEval(Info);
10994     IgnoreSideEffectsRAII Fold(Info);
10995 
10996     if (E->isGLValue()) {
10997       // It's possible for us to be given GLValues if we're called via
10998       // Expr::tryEvaluateObjectSize.
10999       APValue RVal;
11000       if (!EvaluateAsRValue(Info, E, RVal))
11001         return false;
11002       LVal.setFrom(Info.Ctx, RVal);
11003     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11004                                 /*InvalidBaseOK=*/true))
11005       return false;
11006   }
11007 
11008   // If we point to before the start of the object, there are no accessible
11009   // bytes.
11010   if (LVal.getLValueOffset().isNegative()) {
11011     Size = 0;
11012     return true;
11013   }
11014 
11015   CharUnits EndOffset;
11016   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11017     return false;
11018 
11019   // If we've fallen outside of the end offset, just pretend there's nothing to
11020   // write to/read from.
11021   if (EndOffset <= LVal.getLValueOffset())
11022     Size = 0;
11023   else
11024     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11025   return true;
11026 }
11027 
11028 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11029   if (unsigned BuiltinOp = E->getBuiltinCallee())
11030     return VisitBuiltinCallExpr(E, BuiltinOp);
11031 
11032   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11033 }
11034 
11035 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11036                                      APValue &Val, APSInt &Alignment) {
11037   QualType SrcTy = E->getArg(0)->getType();
11038   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11039     return false;
11040   // Even though we are evaluating integer expressions we could get a pointer
11041   // argument for the __builtin_is_aligned() case.
11042   if (SrcTy->isPointerType()) {
11043     LValue Ptr;
11044     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11045       return false;
11046     Ptr.moveInto(Val);
11047   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11048     Info.FFDiag(E->getArg(0));
11049     return false;
11050   } else {
11051     APSInt SrcInt;
11052     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11053       return false;
11054     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11055            "Bit widths must be the same");
11056     Val = APValue(SrcInt);
11057   }
11058   assert(Val.hasValue());
11059   return true;
11060 }
11061 
11062 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11063                                             unsigned BuiltinOp) {
11064   switch (BuiltinOp) {
11065   default:
11066     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11067 
11068   case Builtin::BI__builtin_dynamic_object_size:
11069   case Builtin::BI__builtin_object_size: {
11070     // The type was checked when we built the expression.
11071     unsigned Type =
11072         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11073     assert(Type <= 3 && "unexpected type");
11074 
11075     uint64_t Size;
11076     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11077       return Success(Size, E);
11078 
11079     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11080       return Success((Type & 2) ? 0 : -1, E);
11081 
11082     // Expression had no side effects, but we couldn't statically determine the
11083     // size of the referenced object.
11084     switch (Info.EvalMode) {
11085     case EvalInfo::EM_ConstantExpression:
11086     case EvalInfo::EM_ConstantFold:
11087     case EvalInfo::EM_IgnoreSideEffects:
11088       // Leave it to IR generation.
11089       return Error(E);
11090     case EvalInfo::EM_ConstantExpressionUnevaluated:
11091       // Reduce it to a constant now.
11092       return Success((Type & 2) ? 0 : -1, E);
11093     }
11094 
11095     llvm_unreachable("unexpected EvalMode");
11096   }
11097 
11098   case Builtin::BI__builtin_os_log_format_buffer_size: {
11099     analyze_os_log::OSLogBufferLayout Layout;
11100     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11101     return Success(Layout.size().getQuantity(), E);
11102   }
11103 
11104   case Builtin::BI__builtin_is_aligned: {
11105     APValue Src;
11106     APSInt Alignment;
11107     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11108       return false;
11109     if (Src.isLValue()) {
11110       // If we evaluated a pointer, check the minimum known alignment.
11111       LValue Ptr;
11112       Ptr.setFrom(Info.Ctx, Src);
11113       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11114       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11115       // We can return true if the known alignment at the computed offset is
11116       // greater than the requested alignment.
11117       assert(PtrAlign.isPowerOfTwo());
11118       assert(Alignment.isPowerOf2());
11119       if (PtrAlign.getQuantity() >= Alignment)
11120         return Success(1, E);
11121       // If the alignment is not known to be sufficient, some cases could still
11122       // be aligned at run time. However, if the requested alignment is less or
11123       // equal to the base alignment and the offset is not aligned, we know that
11124       // the run-time value can never be aligned.
11125       if (BaseAlignment.getQuantity() >= Alignment &&
11126           PtrAlign.getQuantity() < Alignment)
11127         return Success(0, E);
11128       // Otherwise we can't infer whether the value is sufficiently aligned.
11129       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11130       //  in cases where we can't fully evaluate the pointer.
11131       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11132           << Alignment;
11133       return false;
11134     }
11135     assert(Src.isInt());
11136     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11137   }
11138   case Builtin::BI__builtin_align_up: {
11139     APValue Src;
11140     APSInt Alignment;
11141     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11142       return false;
11143     if (!Src.isInt())
11144       return Error(E);
11145     APSInt AlignedVal =
11146         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11147                Src.getInt().isUnsigned());
11148     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11149     return Success(AlignedVal, E);
11150   }
11151   case Builtin::BI__builtin_align_down: {
11152     APValue Src;
11153     APSInt Alignment;
11154     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11155       return false;
11156     if (!Src.isInt())
11157       return Error(E);
11158     APSInt AlignedVal =
11159         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11160     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11161     return Success(AlignedVal, E);
11162   }
11163 
11164   case Builtin::BI__builtin_bswap16:
11165   case Builtin::BI__builtin_bswap32:
11166   case Builtin::BI__builtin_bswap64: {
11167     APSInt Val;
11168     if (!EvaluateInteger(E->getArg(0), Val, Info))
11169       return false;
11170 
11171     return Success(Val.byteSwap(), E);
11172   }
11173 
11174   case Builtin::BI__builtin_classify_type:
11175     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11176 
11177   case Builtin::BI__builtin_clrsb:
11178   case Builtin::BI__builtin_clrsbl:
11179   case Builtin::BI__builtin_clrsbll: {
11180     APSInt Val;
11181     if (!EvaluateInteger(E->getArg(0), Val, Info))
11182       return false;
11183 
11184     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11185   }
11186 
11187   case Builtin::BI__builtin_clz:
11188   case Builtin::BI__builtin_clzl:
11189   case Builtin::BI__builtin_clzll:
11190   case Builtin::BI__builtin_clzs: {
11191     APSInt Val;
11192     if (!EvaluateInteger(E->getArg(0), Val, Info))
11193       return false;
11194     if (!Val)
11195       return Error(E);
11196 
11197     return Success(Val.countLeadingZeros(), E);
11198   }
11199 
11200   case Builtin::BI__builtin_constant_p: {
11201     const Expr *Arg = E->getArg(0);
11202     if (EvaluateBuiltinConstantP(Info, Arg))
11203       return Success(true, E);
11204     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11205       // Outside a constant context, eagerly evaluate to false in the presence
11206       // of side-effects in order to avoid -Wunsequenced false-positives in
11207       // a branch on __builtin_constant_p(expr).
11208       return Success(false, E);
11209     }
11210     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11211     return false;
11212   }
11213 
11214   case Builtin::BI__builtin_is_constant_evaluated: {
11215     const auto *Callee = Info.CurrentCall->getCallee();
11216     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11217         (Info.CallStackDepth == 1 ||
11218          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11219           Callee->getIdentifier() &&
11220           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11221       // FIXME: Find a better way to avoid duplicated diagnostics.
11222       if (Info.EvalStatus.Diag)
11223         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11224                                                : Info.CurrentCall->CallLoc,
11225                     diag::warn_is_constant_evaluated_always_true_constexpr)
11226             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11227                                          : "std::is_constant_evaluated");
11228     }
11229 
11230     return Success(Info.InConstantContext, E);
11231   }
11232 
11233   case Builtin::BI__builtin_ctz:
11234   case Builtin::BI__builtin_ctzl:
11235   case Builtin::BI__builtin_ctzll:
11236   case Builtin::BI__builtin_ctzs: {
11237     APSInt Val;
11238     if (!EvaluateInteger(E->getArg(0), Val, Info))
11239       return false;
11240     if (!Val)
11241       return Error(E);
11242 
11243     return Success(Val.countTrailingZeros(), E);
11244   }
11245 
11246   case Builtin::BI__builtin_eh_return_data_regno: {
11247     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11248     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11249     return Success(Operand, E);
11250   }
11251 
11252   case Builtin::BI__builtin_expect:
11253   case Builtin::BI__builtin_expect_with_probability:
11254     return Visit(E->getArg(0));
11255 
11256   case Builtin::BI__builtin_ffs:
11257   case Builtin::BI__builtin_ffsl:
11258   case Builtin::BI__builtin_ffsll: {
11259     APSInt Val;
11260     if (!EvaluateInteger(E->getArg(0), Val, Info))
11261       return false;
11262 
11263     unsigned N = Val.countTrailingZeros();
11264     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11265   }
11266 
11267   case Builtin::BI__builtin_fpclassify: {
11268     APFloat Val(0.0);
11269     if (!EvaluateFloat(E->getArg(5), Val, Info))
11270       return false;
11271     unsigned Arg;
11272     switch (Val.getCategory()) {
11273     case APFloat::fcNaN: Arg = 0; break;
11274     case APFloat::fcInfinity: Arg = 1; break;
11275     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11276     case APFloat::fcZero: Arg = 4; break;
11277     }
11278     return Visit(E->getArg(Arg));
11279   }
11280 
11281   case Builtin::BI__builtin_isinf_sign: {
11282     APFloat Val(0.0);
11283     return EvaluateFloat(E->getArg(0), Val, Info) &&
11284            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11285   }
11286 
11287   case Builtin::BI__builtin_isinf: {
11288     APFloat Val(0.0);
11289     return EvaluateFloat(E->getArg(0), Val, Info) &&
11290            Success(Val.isInfinity() ? 1 : 0, E);
11291   }
11292 
11293   case Builtin::BI__builtin_isfinite: {
11294     APFloat Val(0.0);
11295     return EvaluateFloat(E->getArg(0), Val, Info) &&
11296            Success(Val.isFinite() ? 1 : 0, E);
11297   }
11298 
11299   case Builtin::BI__builtin_isnan: {
11300     APFloat Val(0.0);
11301     return EvaluateFloat(E->getArg(0), Val, Info) &&
11302            Success(Val.isNaN() ? 1 : 0, E);
11303   }
11304 
11305   case Builtin::BI__builtin_isnormal: {
11306     APFloat Val(0.0);
11307     return EvaluateFloat(E->getArg(0), Val, Info) &&
11308            Success(Val.isNormal() ? 1 : 0, E);
11309   }
11310 
11311   case Builtin::BI__builtin_parity:
11312   case Builtin::BI__builtin_parityl:
11313   case Builtin::BI__builtin_parityll: {
11314     APSInt Val;
11315     if (!EvaluateInteger(E->getArg(0), Val, Info))
11316       return false;
11317 
11318     return Success(Val.countPopulation() % 2, E);
11319   }
11320 
11321   case Builtin::BI__builtin_popcount:
11322   case Builtin::BI__builtin_popcountl:
11323   case Builtin::BI__builtin_popcountll: {
11324     APSInt Val;
11325     if (!EvaluateInteger(E->getArg(0), Val, Info))
11326       return false;
11327 
11328     return Success(Val.countPopulation(), E);
11329   }
11330 
11331   case Builtin::BIstrlen:
11332   case Builtin::BIwcslen:
11333     // A call to strlen is not a constant expression.
11334     if (Info.getLangOpts().CPlusPlus11)
11335       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11336         << /*isConstexpr*/0 << /*isConstructor*/0
11337         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11338     else
11339       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11340     LLVM_FALLTHROUGH;
11341   case Builtin::BI__builtin_strlen:
11342   case Builtin::BI__builtin_wcslen: {
11343     // As an extension, we support __builtin_strlen() as a constant expression,
11344     // and support folding strlen() to a constant.
11345     LValue String;
11346     if (!EvaluatePointer(E->getArg(0), String, Info))
11347       return false;
11348 
11349     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11350 
11351     // Fast path: if it's a string literal, search the string value.
11352     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11353             String.getLValueBase().dyn_cast<const Expr *>())) {
11354       // The string literal may have embedded null characters. Find the first
11355       // one and truncate there.
11356       StringRef Str = S->getBytes();
11357       int64_t Off = String.Offset.getQuantity();
11358       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11359           S->getCharByteWidth() == 1 &&
11360           // FIXME: Add fast-path for wchar_t too.
11361           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11362         Str = Str.substr(Off);
11363 
11364         StringRef::size_type Pos = Str.find(0);
11365         if (Pos != StringRef::npos)
11366           Str = Str.substr(0, Pos);
11367 
11368         return Success(Str.size(), E);
11369       }
11370 
11371       // Fall through to slow path to issue appropriate diagnostic.
11372     }
11373 
11374     // Slow path: scan the bytes of the string looking for the terminating 0.
11375     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11376       APValue Char;
11377       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11378           !Char.isInt())
11379         return false;
11380       if (!Char.getInt())
11381         return Success(Strlen, E);
11382       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11383         return false;
11384     }
11385   }
11386 
11387   case Builtin::BIstrcmp:
11388   case Builtin::BIwcscmp:
11389   case Builtin::BIstrncmp:
11390   case Builtin::BIwcsncmp:
11391   case Builtin::BImemcmp:
11392   case Builtin::BIbcmp:
11393   case Builtin::BIwmemcmp:
11394     // A call to strlen is not a constant expression.
11395     if (Info.getLangOpts().CPlusPlus11)
11396       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11397         << /*isConstexpr*/0 << /*isConstructor*/0
11398         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11399     else
11400       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11401     LLVM_FALLTHROUGH;
11402   case Builtin::BI__builtin_strcmp:
11403   case Builtin::BI__builtin_wcscmp:
11404   case Builtin::BI__builtin_strncmp:
11405   case Builtin::BI__builtin_wcsncmp:
11406   case Builtin::BI__builtin_memcmp:
11407   case Builtin::BI__builtin_bcmp:
11408   case Builtin::BI__builtin_wmemcmp: {
11409     LValue String1, String2;
11410     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11411         !EvaluatePointer(E->getArg(1), String2, Info))
11412       return false;
11413 
11414     uint64_t MaxLength = uint64_t(-1);
11415     if (BuiltinOp != Builtin::BIstrcmp &&
11416         BuiltinOp != Builtin::BIwcscmp &&
11417         BuiltinOp != Builtin::BI__builtin_strcmp &&
11418         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11419       APSInt N;
11420       if (!EvaluateInteger(E->getArg(2), N, Info))
11421         return false;
11422       MaxLength = N.getExtValue();
11423     }
11424 
11425     // Empty substrings compare equal by definition.
11426     if (MaxLength == 0u)
11427       return Success(0, E);
11428 
11429     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11430         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11431         String1.Designator.Invalid || String2.Designator.Invalid)
11432       return false;
11433 
11434     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11435     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11436 
11437     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11438                      BuiltinOp == Builtin::BIbcmp ||
11439                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11440                      BuiltinOp == Builtin::BI__builtin_bcmp;
11441 
11442     assert(IsRawByte ||
11443            (Info.Ctx.hasSameUnqualifiedType(
11444                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11445             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11446 
11447     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11448     // 'char8_t', but no other types.
11449     if (IsRawByte &&
11450         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11451       // FIXME: Consider using our bit_cast implementation to support this.
11452       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11453           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11454           << CharTy1 << CharTy2;
11455       return false;
11456     }
11457 
11458     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11459       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11460              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11461              Char1.isInt() && Char2.isInt();
11462     };
11463     const auto &AdvanceElems = [&] {
11464       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11465              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11466     };
11467 
11468     bool StopAtNull =
11469         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11470          BuiltinOp != Builtin::BIwmemcmp &&
11471          BuiltinOp != Builtin::BI__builtin_memcmp &&
11472          BuiltinOp != Builtin::BI__builtin_bcmp &&
11473          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11474     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11475                   BuiltinOp == Builtin::BIwcsncmp ||
11476                   BuiltinOp == Builtin::BIwmemcmp ||
11477                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11478                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11479                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11480 
11481     for (; MaxLength; --MaxLength) {
11482       APValue Char1, Char2;
11483       if (!ReadCurElems(Char1, Char2))
11484         return false;
11485       if (Char1.getInt().ne(Char2.getInt())) {
11486         if (IsWide) // wmemcmp compares with wchar_t signedness.
11487           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11488         // memcmp always compares unsigned chars.
11489         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11490       }
11491       if (StopAtNull && !Char1.getInt())
11492         return Success(0, E);
11493       assert(!(StopAtNull && !Char2.getInt()));
11494       if (!AdvanceElems())
11495         return false;
11496     }
11497     // We hit the strncmp / memcmp limit.
11498     return Success(0, E);
11499   }
11500 
11501   case Builtin::BI__atomic_always_lock_free:
11502   case Builtin::BI__atomic_is_lock_free:
11503   case Builtin::BI__c11_atomic_is_lock_free: {
11504     APSInt SizeVal;
11505     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11506       return false;
11507 
11508     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11509     // of two less than the maximum inline atomic width, we know it is
11510     // lock-free.  If the size isn't a power of two, or greater than the
11511     // maximum alignment where we promote atomics, we know it is not lock-free
11512     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11513     // the answer can only be determined at runtime; for example, 16-byte
11514     // atomics have lock-free implementations on some, but not all,
11515     // x86-64 processors.
11516 
11517     // Check power-of-two.
11518     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11519     if (Size.isPowerOfTwo()) {
11520       // Check against inlining width.
11521       unsigned InlineWidthBits =
11522           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11523       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11524         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11525             Size == CharUnits::One() ||
11526             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11527                                                 Expr::NPC_NeverValueDependent))
11528           // OK, we will inline appropriately-aligned operations of this size,
11529           // and _Atomic(T) is appropriately-aligned.
11530           return Success(1, E);
11531 
11532         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11533           castAs<PointerType>()->getPointeeType();
11534         if (!PointeeType->isIncompleteType() &&
11535             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11536           // OK, we will inline operations on this object.
11537           return Success(1, E);
11538         }
11539       }
11540     }
11541 
11542     // Avoid emiting call for runtime decision on PowerPC 32-bit
11543     // The lock free possibilities on this platform are covered by the lines
11544     // above and we know in advance other cases require lock
11545     if (Info.Ctx.getTargetInfo().getTriple().getArch() == llvm::Triple::ppc) {
11546         return Success(0, E);
11547     }
11548 
11549     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11550         Success(0, E) : Error(E);
11551   }
11552   case Builtin::BIomp_is_initial_device:
11553     // We can decide statically which value the runtime would return if called.
11554     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11555   case Builtin::BI__builtin_add_overflow:
11556   case Builtin::BI__builtin_sub_overflow:
11557   case Builtin::BI__builtin_mul_overflow:
11558   case Builtin::BI__builtin_sadd_overflow:
11559   case Builtin::BI__builtin_uadd_overflow:
11560   case Builtin::BI__builtin_uaddl_overflow:
11561   case Builtin::BI__builtin_uaddll_overflow:
11562   case Builtin::BI__builtin_usub_overflow:
11563   case Builtin::BI__builtin_usubl_overflow:
11564   case Builtin::BI__builtin_usubll_overflow:
11565   case Builtin::BI__builtin_umul_overflow:
11566   case Builtin::BI__builtin_umull_overflow:
11567   case Builtin::BI__builtin_umulll_overflow:
11568   case Builtin::BI__builtin_saddl_overflow:
11569   case Builtin::BI__builtin_saddll_overflow:
11570   case Builtin::BI__builtin_ssub_overflow:
11571   case Builtin::BI__builtin_ssubl_overflow:
11572   case Builtin::BI__builtin_ssubll_overflow:
11573   case Builtin::BI__builtin_smul_overflow:
11574   case Builtin::BI__builtin_smull_overflow:
11575   case Builtin::BI__builtin_smulll_overflow: {
11576     LValue ResultLValue;
11577     APSInt LHS, RHS;
11578 
11579     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11580     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11581         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11582         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11583       return false;
11584 
11585     APSInt Result;
11586     bool DidOverflow = false;
11587 
11588     // If the types don't have to match, enlarge all 3 to the largest of them.
11589     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11590         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11591         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11592       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11593                       ResultType->isSignedIntegerOrEnumerationType();
11594       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11595                       ResultType->isSignedIntegerOrEnumerationType();
11596       uint64_t LHSSize = LHS.getBitWidth();
11597       uint64_t RHSSize = RHS.getBitWidth();
11598       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11599       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11600 
11601       // Add an additional bit if the signedness isn't uniformly agreed to. We
11602       // could do this ONLY if there is a signed and an unsigned that both have
11603       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11604       // caught in the shrink-to-result later anyway.
11605       if (IsSigned && !AllSigned)
11606         ++MaxBits;
11607 
11608       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11609       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11610       Result = APSInt(MaxBits, !IsSigned);
11611     }
11612 
11613     // Find largest int.
11614     switch (BuiltinOp) {
11615     default:
11616       llvm_unreachable("Invalid value for BuiltinOp");
11617     case Builtin::BI__builtin_add_overflow:
11618     case Builtin::BI__builtin_sadd_overflow:
11619     case Builtin::BI__builtin_saddl_overflow:
11620     case Builtin::BI__builtin_saddll_overflow:
11621     case Builtin::BI__builtin_uadd_overflow:
11622     case Builtin::BI__builtin_uaddl_overflow:
11623     case Builtin::BI__builtin_uaddll_overflow:
11624       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11625                               : LHS.uadd_ov(RHS, DidOverflow);
11626       break;
11627     case Builtin::BI__builtin_sub_overflow:
11628     case Builtin::BI__builtin_ssub_overflow:
11629     case Builtin::BI__builtin_ssubl_overflow:
11630     case Builtin::BI__builtin_ssubll_overflow:
11631     case Builtin::BI__builtin_usub_overflow:
11632     case Builtin::BI__builtin_usubl_overflow:
11633     case Builtin::BI__builtin_usubll_overflow:
11634       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11635                               : LHS.usub_ov(RHS, DidOverflow);
11636       break;
11637     case Builtin::BI__builtin_mul_overflow:
11638     case Builtin::BI__builtin_smul_overflow:
11639     case Builtin::BI__builtin_smull_overflow:
11640     case Builtin::BI__builtin_smulll_overflow:
11641     case Builtin::BI__builtin_umul_overflow:
11642     case Builtin::BI__builtin_umull_overflow:
11643     case Builtin::BI__builtin_umulll_overflow:
11644       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11645                               : LHS.umul_ov(RHS, DidOverflow);
11646       break;
11647     }
11648 
11649     // In the case where multiple sizes are allowed, truncate and see if
11650     // the values are the same.
11651     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11652         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11653         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11654       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11655       // since it will give us the behavior of a TruncOrSelf in the case where
11656       // its parameter <= its size.  We previously set Result to be at least the
11657       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11658       // will work exactly like TruncOrSelf.
11659       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11660       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11661 
11662       if (!APSInt::isSameValue(Temp, Result))
11663         DidOverflow = true;
11664       Result = Temp;
11665     }
11666 
11667     APValue APV{Result};
11668     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11669       return false;
11670     return Success(DidOverflow, E);
11671   }
11672   }
11673 }
11674 
11675 /// Determine whether this is a pointer past the end of the complete
11676 /// object referred to by the lvalue.
11677 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11678                                             const LValue &LV) {
11679   // A null pointer can be viewed as being "past the end" but we don't
11680   // choose to look at it that way here.
11681   if (!LV.getLValueBase())
11682     return false;
11683 
11684   // If the designator is valid and refers to a subobject, we're not pointing
11685   // past the end.
11686   if (!LV.getLValueDesignator().Invalid &&
11687       !LV.getLValueDesignator().isOnePastTheEnd())
11688     return false;
11689 
11690   // A pointer to an incomplete type might be past-the-end if the type's size is
11691   // zero.  We cannot tell because the type is incomplete.
11692   QualType Ty = getType(LV.getLValueBase());
11693   if (Ty->isIncompleteType())
11694     return true;
11695 
11696   // We're a past-the-end pointer if we point to the byte after the object,
11697   // no matter what our type or path is.
11698   auto Size = Ctx.getTypeSizeInChars(Ty);
11699   return LV.getLValueOffset() == Size;
11700 }
11701 
11702 namespace {
11703 
11704 /// Data recursive integer evaluator of certain binary operators.
11705 ///
11706 /// We use a data recursive algorithm for binary operators so that we are able
11707 /// to handle extreme cases of chained binary operators without causing stack
11708 /// overflow.
11709 class DataRecursiveIntBinOpEvaluator {
11710   struct EvalResult {
11711     APValue Val;
11712     bool Failed;
11713 
11714     EvalResult() : Failed(false) { }
11715 
11716     void swap(EvalResult &RHS) {
11717       Val.swap(RHS.Val);
11718       Failed = RHS.Failed;
11719       RHS.Failed = false;
11720     }
11721   };
11722 
11723   struct Job {
11724     const Expr *E;
11725     EvalResult LHSResult; // meaningful only for binary operator expression.
11726     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11727 
11728     Job() = default;
11729     Job(Job &&) = default;
11730 
11731     void startSpeculativeEval(EvalInfo &Info) {
11732       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11733     }
11734 
11735   private:
11736     SpeculativeEvaluationRAII SpecEvalRAII;
11737   };
11738 
11739   SmallVector<Job, 16> Queue;
11740 
11741   IntExprEvaluator &IntEval;
11742   EvalInfo &Info;
11743   APValue &FinalResult;
11744 
11745 public:
11746   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11747     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11748 
11749   /// True if \param E is a binary operator that we are going to handle
11750   /// data recursively.
11751   /// We handle binary operators that are comma, logical, or that have operands
11752   /// with integral or enumeration type.
11753   static bool shouldEnqueue(const BinaryOperator *E) {
11754     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11755            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11756             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11757             E->getRHS()->getType()->isIntegralOrEnumerationType());
11758   }
11759 
11760   bool Traverse(const BinaryOperator *E) {
11761     enqueue(E);
11762     EvalResult PrevResult;
11763     while (!Queue.empty())
11764       process(PrevResult);
11765 
11766     if (PrevResult.Failed) return false;
11767 
11768     FinalResult.swap(PrevResult.Val);
11769     return true;
11770   }
11771 
11772 private:
11773   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11774     return IntEval.Success(Value, E, Result);
11775   }
11776   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11777     return IntEval.Success(Value, E, Result);
11778   }
11779   bool Error(const Expr *E) {
11780     return IntEval.Error(E);
11781   }
11782   bool Error(const Expr *E, diag::kind D) {
11783     return IntEval.Error(E, D);
11784   }
11785 
11786   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11787     return Info.CCEDiag(E, D);
11788   }
11789 
11790   // Returns true if visiting the RHS is necessary, false otherwise.
11791   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11792                          bool &SuppressRHSDiags);
11793 
11794   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11795                   const BinaryOperator *E, APValue &Result);
11796 
11797   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11798     Result.Failed = !Evaluate(Result.Val, Info, E);
11799     if (Result.Failed)
11800       Result.Val = APValue();
11801   }
11802 
11803   void process(EvalResult &Result);
11804 
11805   void enqueue(const Expr *E) {
11806     E = E->IgnoreParens();
11807     Queue.resize(Queue.size()+1);
11808     Queue.back().E = E;
11809     Queue.back().Kind = Job::AnyExprKind;
11810   }
11811 };
11812 
11813 }
11814 
11815 bool DataRecursiveIntBinOpEvaluator::
11816        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11817                          bool &SuppressRHSDiags) {
11818   if (E->getOpcode() == BO_Comma) {
11819     // Ignore LHS but note if we could not evaluate it.
11820     if (LHSResult.Failed)
11821       return Info.noteSideEffect();
11822     return true;
11823   }
11824 
11825   if (E->isLogicalOp()) {
11826     bool LHSAsBool;
11827     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11828       // We were able to evaluate the LHS, see if we can get away with not
11829       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11830       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11831         Success(LHSAsBool, E, LHSResult.Val);
11832         return false; // Ignore RHS
11833       }
11834     } else {
11835       LHSResult.Failed = true;
11836 
11837       // Since we weren't able to evaluate the left hand side, it
11838       // might have had side effects.
11839       if (!Info.noteSideEffect())
11840         return false;
11841 
11842       // We can't evaluate the LHS; however, sometimes the result
11843       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11844       // Don't ignore RHS and suppress diagnostics from this arm.
11845       SuppressRHSDiags = true;
11846     }
11847 
11848     return true;
11849   }
11850 
11851   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11852          E->getRHS()->getType()->isIntegralOrEnumerationType());
11853 
11854   if (LHSResult.Failed && !Info.noteFailure())
11855     return false; // Ignore RHS;
11856 
11857   return true;
11858 }
11859 
11860 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11861                                     bool IsSub) {
11862   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11863   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11864   // offsets.
11865   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11866   CharUnits &Offset = LVal.getLValueOffset();
11867   uint64_t Offset64 = Offset.getQuantity();
11868   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11869   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11870                                          : Offset64 + Index64);
11871 }
11872 
11873 bool DataRecursiveIntBinOpEvaluator::
11874        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11875                   const BinaryOperator *E, APValue &Result) {
11876   if (E->getOpcode() == BO_Comma) {
11877     if (RHSResult.Failed)
11878       return false;
11879     Result = RHSResult.Val;
11880     return true;
11881   }
11882 
11883   if (E->isLogicalOp()) {
11884     bool lhsResult, rhsResult;
11885     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11886     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11887 
11888     if (LHSIsOK) {
11889       if (RHSIsOK) {
11890         if (E->getOpcode() == BO_LOr)
11891           return Success(lhsResult || rhsResult, E, Result);
11892         else
11893           return Success(lhsResult && rhsResult, E, Result);
11894       }
11895     } else {
11896       if (RHSIsOK) {
11897         // We can't evaluate the LHS; however, sometimes the result
11898         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11899         if (rhsResult == (E->getOpcode() == BO_LOr))
11900           return Success(rhsResult, E, Result);
11901       }
11902     }
11903 
11904     return false;
11905   }
11906 
11907   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11908          E->getRHS()->getType()->isIntegralOrEnumerationType());
11909 
11910   if (LHSResult.Failed || RHSResult.Failed)
11911     return false;
11912 
11913   const APValue &LHSVal = LHSResult.Val;
11914   const APValue &RHSVal = RHSResult.Val;
11915 
11916   // Handle cases like (unsigned long)&a + 4.
11917   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11918     Result = LHSVal;
11919     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11920     return true;
11921   }
11922 
11923   // Handle cases like 4 + (unsigned long)&a
11924   if (E->getOpcode() == BO_Add &&
11925       RHSVal.isLValue() && LHSVal.isInt()) {
11926     Result = RHSVal;
11927     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11928     return true;
11929   }
11930 
11931   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11932     // Handle (intptr_t)&&A - (intptr_t)&&B.
11933     if (!LHSVal.getLValueOffset().isZero() ||
11934         !RHSVal.getLValueOffset().isZero())
11935       return false;
11936     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11937     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11938     if (!LHSExpr || !RHSExpr)
11939       return false;
11940     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11941     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11942     if (!LHSAddrExpr || !RHSAddrExpr)
11943       return false;
11944     // Make sure both labels come from the same function.
11945     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11946         RHSAddrExpr->getLabel()->getDeclContext())
11947       return false;
11948     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11949     return true;
11950   }
11951 
11952   // All the remaining cases expect both operands to be an integer
11953   if (!LHSVal.isInt() || !RHSVal.isInt())
11954     return Error(E);
11955 
11956   // Set up the width and signedness manually, in case it can't be deduced
11957   // from the operation we're performing.
11958   // FIXME: Don't do this in the cases where we can deduce it.
11959   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11960                E->getType()->isUnsignedIntegerOrEnumerationType());
11961   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11962                          RHSVal.getInt(), Value))
11963     return false;
11964   return Success(Value, E, Result);
11965 }
11966 
11967 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11968   Job &job = Queue.back();
11969 
11970   switch (job.Kind) {
11971     case Job::AnyExprKind: {
11972       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11973         if (shouldEnqueue(Bop)) {
11974           job.Kind = Job::BinOpKind;
11975           enqueue(Bop->getLHS());
11976           return;
11977         }
11978       }
11979 
11980       EvaluateExpr(job.E, Result);
11981       Queue.pop_back();
11982       return;
11983     }
11984 
11985     case Job::BinOpKind: {
11986       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11987       bool SuppressRHSDiags = false;
11988       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11989         Queue.pop_back();
11990         return;
11991       }
11992       if (SuppressRHSDiags)
11993         job.startSpeculativeEval(Info);
11994       job.LHSResult.swap(Result);
11995       job.Kind = Job::BinOpVisitedLHSKind;
11996       enqueue(Bop->getRHS());
11997       return;
11998     }
11999 
12000     case Job::BinOpVisitedLHSKind: {
12001       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12002       EvalResult RHS;
12003       RHS.swap(Result);
12004       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12005       Queue.pop_back();
12006       return;
12007     }
12008   }
12009 
12010   llvm_unreachable("Invalid Job::Kind!");
12011 }
12012 
12013 namespace {
12014 /// Used when we determine that we should fail, but can keep evaluating prior to
12015 /// noting that we had a failure.
12016 class DelayedNoteFailureRAII {
12017   EvalInfo &Info;
12018   bool NoteFailure;
12019 
12020 public:
12021   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12022       : Info(Info), NoteFailure(NoteFailure) {}
12023   ~DelayedNoteFailureRAII() {
12024     if (NoteFailure) {
12025       bool ContinueAfterFailure = Info.noteFailure();
12026       (void)ContinueAfterFailure;
12027       assert(ContinueAfterFailure &&
12028              "Shouldn't have kept evaluating on failure.");
12029     }
12030   }
12031 };
12032 
12033 enum class CmpResult {
12034   Unequal,
12035   Less,
12036   Equal,
12037   Greater,
12038   Unordered,
12039 };
12040 }
12041 
12042 template <class SuccessCB, class AfterCB>
12043 static bool
12044 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12045                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12046   assert(E->isComparisonOp() && "expected comparison operator");
12047   assert((E->getOpcode() == BO_Cmp ||
12048           E->getType()->isIntegralOrEnumerationType()) &&
12049          "unsupported binary expression evaluation");
12050   auto Error = [&](const Expr *E) {
12051     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12052     return false;
12053   };
12054 
12055   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12056   bool IsEquality = E->isEqualityOp();
12057 
12058   QualType LHSTy = E->getLHS()->getType();
12059   QualType RHSTy = E->getRHS()->getType();
12060 
12061   if (LHSTy->isIntegralOrEnumerationType() &&
12062       RHSTy->isIntegralOrEnumerationType()) {
12063     APSInt LHS, RHS;
12064     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12065     if (!LHSOK && !Info.noteFailure())
12066       return false;
12067     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12068       return false;
12069     if (LHS < RHS)
12070       return Success(CmpResult::Less, E);
12071     if (LHS > RHS)
12072       return Success(CmpResult::Greater, E);
12073     return Success(CmpResult::Equal, E);
12074   }
12075 
12076   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12077     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12078     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12079 
12080     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12081     if (!LHSOK && !Info.noteFailure())
12082       return false;
12083     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12084       return false;
12085     if (LHSFX < RHSFX)
12086       return Success(CmpResult::Less, E);
12087     if (LHSFX > RHSFX)
12088       return Success(CmpResult::Greater, E);
12089     return Success(CmpResult::Equal, E);
12090   }
12091 
12092   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12093     ComplexValue LHS, RHS;
12094     bool LHSOK;
12095     if (E->isAssignmentOp()) {
12096       LValue LV;
12097       EvaluateLValue(E->getLHS(), LV, Info);
12098       LHSOK = false;
12099     } else if (LHSTy->isRealFloatingType()) {
12100       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12101       if (LHSOK) {
12102         LHS.makeComplexFloat();
12103         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12104       }
12105     } else {
12106       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12107     }
12108     if (!LHSOK && !Info.noteFailure())
12109       return false;
12110 
12111     if (E->getRHS()->getType()->isRealFloatingType()) {
12112       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12113         return false;
12114       RHS.makeComplexFloat();
12115       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12116     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12117       return false;
12118 
12119     if (LHS.isComplexFloat()) {
12120       APFloat::cmpResult CR_r =
12121         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12122       APFloat::cmpResult CR_i =
12123         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12124       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12125       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12126     } else {
12127       assert(IsEquality && "invalid complex comparison");
12128       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12129                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12130       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12131     }
12132   }
12133 
12134   if (LHSTy->isRealFloatingType() &&
12135       RHSTy->isRealFloatingType()) {
12136     APFloat RHS(0.0), LHS(0.0);
12137 
12138     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12139     if (!LHSOK && !Info.noteFailure())
12140       return false;
12141 
12142     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12143       return false;
12144 
12145     assert(E->isComparisonOp() && "Invalid binary operator!");
12146     auto GetCmpRes = [&]() {
12147       switch (LHS.compare(RHS)) {
12148       case APFloat::cmpEqual:
12149         return CmpResult::Equal;
12150       case APFloat::cmpLessThan:
12151         return CmpResult::Less;
12152       case APFloat::cmpGreaterThan:
12153         return CmpResult::Greater;
12154       case APFloat::cmpUnordered:
12155         return CmpResult::Unordered;
12156       }
12157       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12158     };
12159     return Success(GetCmpRes(), E);
12160   }
12161 
12162   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12163     LValue LHSValue, RHSValue;
12164 
12165     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12166     if (!LHSOK && !Info.noteFailure())
12167       return false;
12168 
12169     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12170       return false;
12171 
12172     // Reject differing bases from the normal codepath; we special-case
12173     // comparisons to null.
12174     if (!HasSameBase(LHSValue, RHSValue)) {
12175       // Inequalities and subtractions between unrelated pointers have
12176       // unspecified or undefined behavior.
12177       if (!IsEquality) {
12178         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12179         return false;
12180       }
12181       // A constant address may compare equal to the address of a symbol.
12182       // The one exception is that address of an object cannot compare equal
12183       // to a null pointer constant.
12184       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12185           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12186         return Error(E);
12187       // It's implementation-defined whether distinct literals will have
12188       // distinct addresses. In clang, the result of such a comparison is
12189       // unspecified, so it is not a constant expression. However, we do know
12190       // that the address of a literal will be non-null.
12191       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12192           LHSValue.Base && RHSValue.Base)
12193         return Error(E);
12194       // We can't tell whether weak symbols will end up pointing to the same
12195       // object.
12196       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12197         return Error(E);
12198       // We can't compare the address of the start of one object with the
12199       // past-the-end address of another object, per C++ DR1652.
12200       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12201            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12202           (RHSValue.Base && RHSValue.Offset.isZero() &&
12203            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12204         return Error(E);
12205       // We can't tell whether an object is at the same address as another
12206       // zero sized object.
12207       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12208           (LHSValue.Base && isZeroSized(RHSValue)))
12209         return Error(E);
12210       return Success(CmpResult::Unequal, E);
12211     }
12212 
12213     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12214     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12215 
12216     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12217     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12218 
12219     // C++11 [expr.rel]p3:
12220     //   Pointers to void (after pointer conversions) can be compared, with a
12221     //   result defined as follows: If both pointers represent the same
12222     //   address or are both the null pointer value, the result is true if the
12223     //   operator is <= or >= and false otherwise; otherwise the result is
12224     //   unspecified.
12225     // We interpret this as applying to pointers to *cv* void.
12226     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12227       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12228 
12229     // C++11 [expr.rel]p2:
12230     // - If two pointers point to non-static data members of the same object,
12231     //   or to subobjects or array elements fo such members, recursively, the
12232     //   pointer to the later declared member compares greater provided the
12233     //   two members have the same access control and provided their class is
12234     //   not a union.
12235     //   [...]
12236     // - Otherwise pointer comparisons are unspecified.
12237     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12238       bool WasArrayIndex;
12239       unsigned Mismatch = FindDesignatorMismatch(
12240           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12241       // At the point where the designators diverge, the comparison has a
12242       // specified value if:
12243       //  - we are comparing array indices
12244       //  - we are comparing fields of a union, or fields with the same access
12245       // Otherwise, the result is unspecified and thus the comparison is not a
12246       // constant expression.
12247       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12248           Mismatch < RHSDesignator.Entries.size()) {
12249         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12250         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12251         if (!LF && !RF)
12252           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12253         else if (!LF)
12254           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12255               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12256               << RF->getParent() << RF;
12257         else if (!RF)
12258           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12259               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12260               << LF->getParent() << LF;
12261         else if (!LF->getParent()->isUnion() &&
12262                  LF->getAccess() != RF->getAccess())
12263           Info.CCEDiag(E,
12264                        diag::note_constexpr_pointer_comparison_differing_access)
12265               << LF << LF->getAccess() << RF << RF->getAccess()
12266               << LF->getParent();
12267       }
12268     }
12269 
12270     // The comparison here must be unsigned, and performed with the same
12271     // width as the pointer.
12272     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12273     uint64_t CompareLHS = LHSOffset.getQuantity();
12274     uint64_t CompareRHS = RHSOffset.getQuantity();
12275     assert(PtrSize <= 64 && "Unexpected pointer width");
12276     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12277     CompareLHS &= Mask;
12278     CompareRHS &= Mask;
12279 
12280     // If there is a base and this is a relational operator, we can only
12281     // compare pointers within the object in question; otherwise, the result
12282     // depends on where the object is located in memory.
12283     if (!LHSValue.Base.isNull() && IsRelational) {
12284       QualType BaseTy = getType(LHSValue.Base);
12285       if (BaseTy->isIncompleteType())
12286         return Error(E);
12287       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12288       uint64_t OffsetLimit = Size.getQuantity();
12289       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12290         return Error(E);
12291     }
12292 
12293     if (CompareLHS < CompareRHS)
12294       return Success(CmpResult::Less, E);
12295     if (CompareLHS > CompareRHS)
12296       return Success(CmpResult::Greater, E);
12297     return Success(CmpResult::Equal, E);
12298   }
12299 
12300   if (LHSTy->isMemberPointerType()) {
12301     assert(IsEquality && "unexpected member pointer operation");
12302     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12303 
12304     MemberPtr LHSValue, RHSValue;
12305 
12306     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12307     if (!LHSOK && !Info.noteFailure())
12308       return false;
12309 
12310     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12311       return false;
12312 
12313     // C++11 [expr.eq]p2:
12314     //   If both operands are null, they compare equal. Otherwise if only one is
12315     //   null, they compare unequal.
12316     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12317       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12318       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12319     }
12320 
12321     //   Otherwise if either is a pointer to a virtual member function, the
12322     //   result is unspecified.
12323     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12324       if (MD->isVirtual())
12325         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12326     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12327       if (MD->isVirtual())
12328         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12329 
12330     //   Otherwise they compare equal if and only if they would refer to the
12331     //   same member of the same most derived object or the same subobject if
12332     //   they were dereferenced with a hypothetical object of the associated
12333     //   class type.
12334     bool Equal = LHSValue == RHSValue;
12335     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12336   }
12337 
12338   if (LHSTy->isNullPtrType()) {
12339     assert(E->isComparisonOp() && "unexpected nullptr operation");
12340     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12341     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12342     // are compared, the result is true of the operator is <=, >= or ==, and
12343     // false otherwise.
12344     return Success(CmpResult::Equal, E);
12345   }
12346 
12347   return DoAfter();
12348 }
12349 
12350 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12351   if (!CheckLiteralType(Info, E))
12352     return false;
12353 
12354   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12355     ComparisonCategoryResult CCR;
12356     switch (CR) {
12357     case CmpResult::Unequal:
12358       llvm_unreachable("should never produce Unequal for three-way comparison");
12359     case CmpResult::Less:
12360       CCR = ComparisonCategoryResult::Less;
12361       break;
12362     case CmpResult::Equal:
12363       CCR = ComparisonCategoryResult::Equal;
12364       break;
12365     case CmpResult::Greater:
12366       CCR = ComparisonCategoryResult::Greater;
12367       break;
12368     case CmpResult::Unordered:
12369       CCR = ComparisonCategoryResult::Unordered;
12370       break;
12371     }
12372     // Evaluation succeeded. Lookup the information for the comparison category
12373     // type and fetch the VarDecl for the result.
12374     const ComparisonCategoryInfo &CmpInfo =
12375         Info.Ctx.CompCategories.getInfoForType(E->getType());
12376     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12377     // Check and evaluate the result as a constant expression.
12378     LValue LV;
12379     LV.set(VD);
12380     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12381       return false;
12382     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12383   };
12384   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12385     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12386   });
12387 }
12388 
12389 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12390   // We don't call noteFailure immediately because the assignment happens after
12391   // we evaluate LHS and RHS.
12392   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12393     return Error(E);
12394 
12395   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12396   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12397     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12398 
12399   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12400           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12401          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12402 
12403   if (E->isComparisonOp()) {
12404     // Evaluate builtin binary comparisons by evaluating them as three-way
12405     // comparisons and then translating the result.
12406     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12407       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12408              "should only produce Unequal for equality comparisons");
12409       bool IsEqual   = CR == CmpResult::Equal,
12410            IsLess    = CR == CmpResult::Less,
12411            IsGreater = CR == CmpResult::Greater;
12412       auto Op = E->getOpcode();
12413       switch (Op) {
12414       default:
12415         llvm_unreachable("unsupported binary operator");
12416       case BO_EQ:
12417       case BO_NE:
12418         return Success(IsEqual == (Op == BO_EQ), E);
12419       case BO_LT:
12420         return Success(IsLess, E);
12421       case BO_GT:
12422         return Success(IsGreater, E);
12423       case BO_LE:
12424         return Success(IsEqual || IsLess, E);
12425       case BO_GE:
12426         return Success(IsEqual || IsGreater, E);
12427       }
12428     };
12429     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12430       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12431     });
12432   }
12433 
12434   QualType LHSTy = E->getLHS()->getType();
12435   QualType RHSTy = E->getRHS()->getType();
12436 
12437   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12438       E->getOpcode() == BO_Sub) {
12439     LValue LHSValue, RHSValue;
12440 
12441     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12442     if (!LHSOK && !Info.noteFailure())
12443       return false;
12444 
12445     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12446       return false;
12447 
12448     // Reject differing bases from the normal codepath; we special-case
12449     // comparisons to null.
12450     if (!HasSameBase(LHSValue, RHSValue)) {
12451       // Handle &&A - &&B.
12452       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12453         return Error(E);
12454       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12455       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12456       if (!LHSExpr || !RHSExpr)
12457         return Error(E);
12458       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12459       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12460       if (!LHSAddrExpr || !RHSAddrExpr)
12461         return Error(E);
12462       // Make sure both labels come from the same function.
12463       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12464           RHSAddrExpr->getLabel()->getDeclContext())
12465         return Error(E);
12466       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12467     }
12468     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12469     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12470 
12471     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12472     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12473 
12474     // C++11 [expr.add]p6:
12475     //   Unless both pointers point to elements of the same array object, or
12476     //   one past the last element of the array object, the behavior is
12477     //   undefined.
12478     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12479         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12480                                 RHSDesignator))
12481       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12482 
12483     QualType Type = E->getLHS()->getType();
12484     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12485 
12486     CharUnits ElementSize;
12487     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12488       return false;
12489 
12490     // As an extension, a type may have zero size (empty struct or union in
12491     // C, array of zero length). Pointer subtraction in such cases has
12492     // undefined behavior, so is not constant.
12493     if (ElementSize.isZero()) {
12494       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12495           << ElementType;
12496       return false;
12497     }
12498 
12499     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12500     // and produce incorrect results when it overflows. Such behavior
12501     // appears to be non-conforming, but is common, so perhaps we should
12502     // assume the standard intended for such cases to be undefined behavior
12503     // and check for them.
12504 
12505     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12506     // overflow in the final conversion to ptrdiff_t.
12507     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12508     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12509     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12510                     false);
12511     APSInt TrueResult = (LHS - RHS) / ElemSize;
12512     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12513 
12514     if (Result.extend(65) != TrueResult &&
12515         !HandleOverflow(Info, E, TrueResult, E->getType()))
12516       return false;
12517     return Success(Result, E);
12518   }
12519 
12520   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12521 }
12522 
12523 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12524 /// a result as the expression's type.
12525 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12526                                     const UnaryExprOrTypeTraitExpr *E) {
12527   switch(E->getKind()) {
12528   case UETT_PreferredAlignOf:
12529   case UETT_AlignOf: {
12530     if (E->isArgumentType())
12531       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12532                      E);
12533     else
12534       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12535                      E);
12536   }
12537 
12538   case UETT_VecStep: {
12539     QualType Ty = E->getTypeOfArgument();
12540 
12541     if (Ty->isVectorType()) {
12542       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12543 
12544       // The vec_step built-in functions that take a 3-component
12545       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12546       if (n == 3)
12547         n = 4;
12548 
12549       return Success(n, E);
12550     } else
12551       return Success(1, E);
12552   }
12553 
12554   case UETT_SizeOf: {
12555     QualType SrcTy = E->getTypeOfArgument();
12556     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12557     //   the result is the size of the referenced type."
12558     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12559       SrcTy = Ref->getPointeeType();
12560 
12561     CharUnits Sizeof;
12562     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12563       return false;
12564     return Success(Sizeof, E);
12565   }
12566   case UETT_OpenMPRequiredSimdAlign:
12567     assert(E->isArgumentType());
12568     return Success(
12569         Info.Ctx.toCharUnitsFromBits(
12570                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12571             .getQuantity(),
12572         E);
12573   }
12574 
12575   llvm_unreachable("unknown expr/type trait");
12576 }
12577 
12578 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12579   CharUnits Result;
12580   unsigned n = OOE->getNumComponents();
12581   if (n == 0)
12582     return Error(OOE);
12583   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12584   for (unsigned i = 0; i != n; ++i) {
12585     OffsetOfNode ON = OOE->getComponent(i);
12586     switch (ON.getKind()) {
12587     case OffsetOfNode::Array: {
12588       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12589       APSInt IdxResult;
12590       if (!EvaluateInteger(Idx, IdxResult, Info))
12591         return false;
12592       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12593       if (!AT)
12594         return Error(OOE);
12595       CurrentType = AT->getElementType();
12596       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12597       Result += IdxResult.getSExtValue() * ElementSize;
12598       break;
12599     }
12600 
12601     case OffsetOfNode::Field: {
12602       FieldDecl *MemberDecl = ON.getField();
12603       const RecordType *RT = CurrentType->getAs<RecordType>();
12604       if (!RT)
12605         return Error(OOE);
12606       RecordDecl *RD = RT->getDecl();
12607       if (RD->isInvalidDecl()) return false;
12608       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12609       unsigned i = MemberDecl->getFieldIndex();
12610       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12611       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12612       CurrentType = MemberDecl->getType().getNonReferenceType();
12613       break;
12614     }
12615 
12616     case OffsetOfNode::Identifier:
12617       llvm_unreachable("dependent __builtin_offsetof");
12618 
12619     case OffsetOfNode::Base: {
12620       CXXBaseSpecifier *BaseSpec = ON.getBase();
12621       if (BaseSpec->isVirtual())
12622         return Error(OOE);
12623 
12624       // Find the layout of the class whose base we are looking into.
12625       const RecordType *RT = CurrentType->getAs<RecordType>();
12626       if (!RT)
12627         return Error(OOE);
12628       RecordDecl *RD = RT->getDecl();
12629       if (RD->isInvalidDecl()) return false;
12630       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12631 
12632       // Find the base class itself.
12633       CurrentType = BaseSpec->getType();
12634       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12635       if (!BaseRT)
12636         return Error(OOE);
12637 
12638       // Add the offset to the base.
12639       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12640       break;
12641     }
12642     }
12643   }
12644   return Success(Result, OOE);
12645 }
12646 
12647 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12648   switch (E->getOpcode()) {
12649   default:
12650     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12651     // See C99 6.6p3.
12652     return Error(E);
12653   case UO_Extension:
12654     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12655     // If so, we could clear the diagnostic ID.
12656     return Visit(E->getSubExpr());
12657   case UO_Plus:
12658     // The result is just the value.
12659     return Visit(E->getSubExpr());
12660   case UO_Minus: {
12661     if (!Visit(E->getSubExpr()))
12662       return false;
12663     if (!Result.isInt()) return Error(E);
12664     const APSInt &Value = Result.getInt();
12665     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12666         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12667                         E->getType()))
12668       return false;
12669     return Success(-Value, E);
12670   }
12671   case UO_Not: {
12672     if (!Visit(E->getSubExpr()))
12673       return false;
12674     if (!Result.isInt()) return Error(E);
12675     return Success(~Result.getInt(), E);
12676   }
12677   case UO_LNot: {
12678     bool bres;
12679     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12680       return false;
12681     return Success(!bres, E);
12682   }
12683   }
12684 }
12685 
12686 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12687 /// result type is integer.
12688 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12689   const Expr *SubExpr = E->getSubExpr();
12690   QualType DestType = E->getType();
12691   QualType SrcType = SubExpr->getType();
12692 
12693   switch (E->getCastKind()) {
12694   case CK_BaseToDerived:
12695   case CK_DerivedToBase:
12696   case CK_UncheckedDerivedToBase:
12697   case CK_Dynamic:
12698   case CK_ToUnion:
12699   case CK_ArrayToPointerDecay:
12700   case CK_FunctionToPointerDecay:
12701   case CK_NullToPointer:
12702   case CK_NullToMemberPointer:
12703   case CK_BaseToDerivedMemberPointer:
12704   case CK_DerivedToBaseMemberPointer:
12705   case CK_ReinterpretMemberPointer:
12706   case CK_ConstructorConversion:
12707   case CK_IntegralToPointer:
12708   case CK_ToVoid:
12709   case CK_VectorSplat:
12710   case CK_IntegralToFloating:
12711   case CK_FloatingCast:
12712   case CK_CPointerToObjCPointerCast:
12713   case CK_BlockPointerToObjCPointerCast:
12714   case CK_AnyPointerToBlockPointerCast:
12715   case CK_ObjCObjectLValueCast:
12716   case CK_FloatingRealToComplex:
12717   case CK_FloatingComplexToReal:
12718   case CK_FloatingComplexCast:
12719   case CK_FloatingComplexToIntegralComplex:
12720   case CK_IntegralRealToComplex:
12721   case CK_IntegralComplexCast:
12722   case CK_IntegralComplexToFloatingComplex:
12723   case CK_BuiltinFnToFnPtr:
12724   case CK_ZeroToOCLOpaqueType:
12725   case CK_NonAtomicToAtomic:
12726   case CK_AddressSpaceConversion:
12727   case CK_IntToOCLSampler:
12728   case CK_FixedPointCast:
12729   case CK_IntegralToFixedPoint:
12730     llvm_unreachable("invalid cast kind for integral value");
12731 
12732   case CK_BitCast:
12733   case CK_Dependent:
12734   case CK_LValueBitCast:
12735   case CK_ARCProduceObject:
12736   case CK_ARCConsumeObject:
12737   case CK_ARCReclaimReturnedObject:
12738   case CK_ARCExtendBlockObject:
12739   case CK_CopyAndAutoreleaseBlockObject:
12740     return Error(E);
12741 
12742   case CK_UserDefinedConversion:
12743   case CK_LValueToRValue:
12744   case CK_AtomicToNonAtomic:
12745   case CK_NoOp:
12746   case CK_LValueToRValueBitCast:
12747     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12748 
12749   case CK_MemberPointerToBoolean:
12750   case CK_PointerToBoolean:
12751   case CK_IntegralToBoolean:
12752   case CK_FloatingToBoolean:
12753   case CK_BooleanToSignedIntegral:
12754   case CK_FloatingComplexToBoolean:
12755   case CK_IntegralComplexToBoolean: {
12756     bool BoolResult;
12757     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12758       return false;
12759     uint64_t IntResult = BoolResult;
12760     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12761       IntResult = (uint64_t)-1;
12762     return Success(IntResult, E);
12763   }
12764 
12765   case CK_FixedPointToIntegral: {
12766     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12767     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12768       return false;
12769     bool Overflowed;
12770     llvm::APSInt Result = Src.convertToInt(
12771         Info.Ctx.getIntWidth(DestType),
12772         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12773     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12774       return false;
12775     return Success(Result, E);
12776   }
12777 
12778   case CK_FixedPointToBoolean: {
12779     // Unsigned padding does not affect this.
12780     APValue Val;
12781     if (!Evaluate(Val, Info, SubExpr))
12782       return false;
12783     return Success(Val.getFixedPoint().getBoolValue(), E);
12784   }
12785 
12786   case CK_IntegralCast: {
12787     if (!Visit(SubExpr))
12788       return false;
12789 
12790     if (!Result.isInt()) {
12791       // Allow casts of address-of-label differences if they are no-ops
12792       // or narrowing.  (The narrowing case isn't actually guaranteed to
12793       // be constant-evaluatable except in some narrow cases which are hard
12794       // to detect here.  We let it through on the assumption the user knows
12795       // what they are doing.)
12796       if (Result.isAddrLabelDiff())
12797         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12798       // Only allow casts of lvalues if they are lossless.
12799       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12800     }
12801 
12802     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12803                                       Result.getInt()), E);
12804   }
12805 
12806   case CK_PointerToIntegral: {
12807     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12808 
12809     LValue LV;
12810     if (!EvaluatePointer(SubExpr, LV, Info))
12811       return false;
12812 
12813     if (LV.getLValueBase()) {
12814       // Only allow based lvalue casts if they are lossless.
12815       // FIXME: Allow a larger integer size than the pointer size, and allow
12816       // narrowing back down to pointer width in subsequent integral casts.
12817       // FIXME: Check integer type's active bits, not its type size.
12818       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12819         return Error(E);
12820 
12821       LV.Designator.setInvalid();
12822       LV.moveInto(Result);
12823       return true;
12824     }
12825 
12826     APSInt AsInt;
12827     APValue V;
12828     LV.moveInto(V);
12829     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12830       llvm_unreachable("Can't cast this!");
12831 
12832     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12833   }
12834 
12835   case CK_IntegralComplexToReal: {
12836     ComplexValue C;
12837     if (!EvaluateComplex(SubExpr, C, Info))
12838       return false;
12839     return Success(C.getComplexIntReal(), E);
12840   }
12841 
12842   case CK_FloatingToIntegral: {
12843     APFloat F(0.0);
12844     if (!EvaluateFloat(SubExpr, F, Info))
12845       return false;
12846 
12847     APSInt Value;
12848     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12849       return false;
12850     return Success(Value, E);
12851   }
12852   }
12853 
12854   llvm_unreachable("unknown cast resulting in integral value");
12855 }
12856 
12857 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12858   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12859     ComplexValue LV;
12860     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12861       return false;
12862     if (!LV.isComplexInt())
12863       return Error(E);
12864     return Success(LV.getComplexIntReal(), E);
12865   }
12866 
12867   return Visit(E->getSubExpr());
12868 }
12869 
12870 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12871   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12872     ComplexValue LV;
12873     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12874       return false;
12875     if (!LV.isComplexInt())
12876       return Error(E);
12877     return Success(LV.getComplexIntImag(), E);
12878   }
12879 
12880   VisitIgnoredValue(E->getSubExpr());
12881   return Success(0, E);
12882 }
12883 
12884 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12885   return Success(E->getPackLength(), E);
12886 }
12887 
12888 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12889   return Success(E->getValue(), E);
12890 }
12891 
12892 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12893        const ConceptSpecializationExpr *E) {
12894   return Success(E->isSatisfied(), E);
12895 }
12896 
12897 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12898   return Success(E->isSatisfied(), E);
12899 }
12900 
12901 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12902   switch (E->getOpcode()) {
12903     default:
12904       // Invalid unary operators
12905       return Error(E);
12906     case UO_Plus:
12907       // The result is just the value.
12908       return Visit(E->getSubExpr());
12909     case UO_Minus: {
12910       if (!Visit(E->getSubExpr())) return false;
12911       if (!Result.isFixedPoint())
12912         return Error(E);
12913       bool Overflowed;
12914       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12915       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12916         return false;
12917       return Success(Negated, E);
12918     }
12919     case UO_LNot: {
12920       bool bres;
12921       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12922         return false;
12923       return Success(!bres, E);
12924     }
12925   }
12926 }
12927 
12928 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12929   const Expr *SubExpr = E->getSubExpr();
12930   QualType DestType = E->getType();
12931   assert(DestType->isFixedPointType() &&
12932          "Expected destination type to be a fixed point type");
12933   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12934 
12935   switch (E->getCastKind()) {
12936   case CK_FixedPointCast: {
12937     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12938     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12939       return false;
12940     bool Overflowed;
12941     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12942     if (Overflowed) {
12943       if (Info.checkingForUndefinedBehavior())
12944         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
12945                                          diag::warn_fixedpoint_constant_overflow)
12946           << Result.toString() << E->getType();
12947       else if (!HandleOverflow(Info, E, Result, E->getType()))
12948         return false;
12949     }
12950     return Success(Result, E);
12951   }
12952   case CK_IntegralToFixedPoint: {
12953     APSInt Src;
12954     if (!EvaluateInteger(SubExpr, Src, Info))
12955       return false;
12956 
12957     bool Overflowed;
12958     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12959         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12960 
12961     if (Overflowed) {
12962       if (Info.checkingForUndefinedBehavior())
12963         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
12964                                          diag::warn_fixedpoint_constant_overflow)
12965           << IntResult.toString() << E->getType();
12966       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
12967         return false;
12968     }
12969 
12970     return Success(IntResult, E);
12971   }
12972   case CK_NoOp:
12973   case CK_LValueToRValue:
12974     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12975   default:
12976     return Error(E);
12977   }
12978 }
12979 
12980 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12981   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12982     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12983 
12984   const Expr *LHS = E->getLHS();
12985   const Expr *RHS = E->getRHS();
12986   FixedPointSemantics ResultFXSema =
12987       Info.Ctx.getFixedPointSemantics(E->getType());
12988 
12989   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12990   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12991     return false;
12992   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12993   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12994     return false;
12995 
12996   bool OpOverflow = false, ConversionOverflow = false;
12997   APFixedPoint Result(LHSFX.getSemantics());
12998   switch (E->getOpcode()) {
12999   case BO_Add: {
13000     Result = LHSFX.add(RHSFX, &OpOverflow)
13001                   .convert(ResultFXSema, &ConversionOverflow);
13002     break;
13003   }
13004   case BO_Sub: {
13005     Result = LHSFX.sub(RHSFX, &OpOverflow)
13006                   .convert(ResultFXSema, &ConversionOverflow);
13007     break;
13008   }
13009   case BO_Mul: {
13010     Result = LHSFX.mul(RHSFX, &OpOverflow)
13011                   .convert(ResultFXSema, &ConversionOverflow);
13012     break;
13013   }
13014   case BO_Div: {
13015     if (RHSFX.getValue() == 0) {
13016       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13017       return false;
13018     }
13019     Result = LHSFX.div(RHSFX, &OpOverflow)
13020                   .convert(ResultFXSema, &ConversionOverflow);
13021     break;
13022   }
13023   default:
13024     return false;
13025   }
13026   if (OpOverflow || ConversionOverflow) {
13027     if (Info.checkingForUndefinedBehavior())
13028       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13029                                        diag::warn_fixedpoint_constant_overflow)
13030         << Result.toString() << E->getType();
13031     else if (!HandleOverflow(Info, E, Result, E->getType()))
13032       return false;
13033   }
13034   return Success(Result, E);
13035 }
13036 
13037 //===----------------------------------------------------------------------===//
13038 // Float Evaluation
13039 //===----------------------------------------------------------------------===//
13040 
13041 namespace {
13042 class FloatExprEvaluator
13043   : public ExprEvaluatorBase<FloatExprEvaluator> {
13044   APFloat &Result;
13045 public:
13046   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13047     : ExprEvaluatorBaseTy(info), Result(result) {}
13048 
13049   bool Success(const APValue &V, const Expr *e) {
13050     Result = V.getFloat();
13051     return true;
13052   }
13053 
13054   bool ZeroInitialization(const Expr *E) {
13055     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13056     return true;
13057   }
13058 
13059   bool VisitCallExpr(const CallExpr *E);
13060 
13061   bool VisitUnaryOperator(const UnaryOperator *E);
13062   bool VisitBinaryOperator(const BinaryOperator *E);
13063   bool VisitFloatingLiteral(const FloatingLiteral *E);
13064   bool VisitCastExpr(const CastExpr *E);
13065 
13066   bool VisitUnaryReal(const UnaryOperator *E);
13067   bool VisitUnaryImag(const UnaryOperator *E);
13068 
13069   // FIXME: Missing: array subscript of vector, member of vector
13070 };
13071 } // end anonymous namespace
13072 
13073 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13074   assert(E->isRValue() && E->getType()->isRealFloatingType());
13075   return FloatExprEvaluator(Info, Result).Visit(E);
13076 }
13077 
13078 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13079                                   QualType ResultTy,
13080                                   const Expr *Arg,
13081                                   bool SNaN,
13082                                   llvm::APFloat &Result) {
13083   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13084   if (!S) return false;
13085 
13086   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13087 
13088   llvm::APInt fill;
13089 
13090   // Treat empty strings as if they were zero.
13091   if (S->getString().empty())
13092     fill = llvm::APInt(32, 0);
13093   else if (S->getString().getAsInteger(0, fill))
13094     return false;
13095 
13096   if (Context.getTargetInfo().isNan2008()) {
13097     if (SNaN)
13098       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13099     else
13100       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13101   } else {
13102     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13103     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13104     // a different encoding to what became a standard in 2008, and for pre-
13105     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13106     // sNaN. This is now known as "legacy NaN" encoding.
13107     if (SNaN)
13108       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13109     else
13110       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13111   }
13112 
13113   return true;
13114 }
13115 
13116 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13117   switch (E->getBuiltinCallee()) {
13118   default:
13119     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13120 
13121   case Builtin::BI__builtin_huge_val:
13122   case Builtin::BI__builtin_huge_valf:
13123   case Builtin::BI__builtin_huge_vall:
13124   case Builtin::BI__builtin_huge_valf128:
13125   case Builtin::BI__builtin_inf:
13126   case Builtin::BI__builtin_inff:
13127   case Builtin::BI__builtin_infl:
13128   case Builtin::BI__builtin_inff128: {
13129     const llvm::fltSemantics &Sem =
13130       Info.Ctx.getFloatTypeSemantics(E->getType());
13131     Result = llvm::APFloat::getInf(Sem);
13132     return true;
13133   }
13134 
13135   case Builtin::BI__builtin_nans:
13136   case Builtin::BI__builtin_nansf:
13137   case Builtin::BI__builtin_nansl:
13138   case Builtin::BI__builtin_nansf128:
13139     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13140                                true, Result))
13141       return Error(E);
13142     return true;
13143 
13144   case Builtin::BI__builtin_nan:
13145   case Builtin::BI__builtin_nanf:
13146   case Builtin::BI__builtin_nanl:
13147   case Builtin::BI__builtin_nanf128:
13148     // If this is __builtin_nan() turn this into a nan, otherwise we
13149     // can't constant fold it.
13150     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13151                                false, Result))
13152       return Error(E);
13153     return true;
13154 
13155   case Builtin::BI__builtin_fabs:
13156   case Builtin::BI__builtin_fabsf:
13157   case Builtin::BI__builtin_fabsl:
13158   case Builtin::BI__builtin_fabsf128:
13159     if (!EvaluateFloat(E->getArg(0), Result, Info))
13160       return false;
13161 
13162     if (Result.isNegative())
13163       Result.changeSign();
13164     return true;
13165 
13166   // FIXME: Builtin::BI__builtin_powi
13167   // FIXME: Builtin::BI__builtin_powif
13168   // FIXME: Builtin::BI__builtin_powil
13169 
13170   case Builtin::BI__builtin_copysign:
13171   case Builtin::BI__builtin_copysignf:
13172   case Builtin::BI__builtin_copysignl:
13173   case Builtin::BI__builtin_copysignf128: {
13174     APFloat RHS(0.);
13175     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13176         !EvaluateFloat(E->getArg(1), RHS, Info))
13177       return false;
13178     Result.copySign(RHS);
13179     return true;
13180   }
13181   }
13182 }
13183 
13184 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13185   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13186     ComplexValue CV;
13187     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13188       return false;
13189     Result = CV.FloatReal;
13190     return true;
13191   }
13192 
13193   return Visit(E->getSubExpr());
13194 }
13195 
13196 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13197   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13198     ComplexValue CV;
13199     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13200       return false;
13201     Result = CV.FloatImag;
13202     return true;
13203   }
13204 
13205   VisitIgnoredValue(E->getSubExpr());
13206   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13207   Result = llvm::APFloat::getZero(Sem);
13208   return true;
13209 }
13210 
13211 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13212   switch (E->getOpcode()) {
13213   default: return Error(E);
13214   case UO_Plus:
13215     return EvaluateFloat(E->getSubExpr(), Result, Info);
13216   case UO_Minus:
13217     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13218       return false;
13219     Result.changeSign();
13220     return true;
13221   }
13222 }
13223 
13224 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13225   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13226     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13227 
13228   APFloat RHS(0.0);
13229   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13230   if (!LHSOK && !Info.noteFailure())
13231     return false;
13232   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13233          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13234 }
13235 
13236 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13237   Result = E->getValue();
13238   return true;
13239 }
13240 
13241 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13242   const Expr* SubExpr = E->getSubExpr();
13243 
13244   switch (E->getCastKind()) {
13245   default:
13246     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13247 
13248   case CK_IntegralToFloating: {
13249     APSInt IntResult;
13250     return EvaluateInteger(SubExpr, IntResult, Info) &&
13251            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
13252                                 E->getType(), Result);
13253   }
13254 
13255   case CK_FloatingCast: {
13256     if (!Visit(SubExpr))
13257       return false;
13258     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13259                                   Result);
13260   }
13261 
13262   case CK_FloatingComplexToReal: {
13263     ComplexValue V;
13264     if (!EvaluateComplex(SubExpr, V, Info))
13265       return false;
13266     Result = V.getComplexFloatReal();
13267     return true;
13268   }
13269   }
13270 }
13271 
13272 //===----------------------------------------------------------------------===//
13273 // Complex Evaluation (for float and integer)
13274 //===----------------------------------------------------------------------===//
13275 
13276 namespace {
13277 class ComplexExprEvaluator
13278   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13279   ComplexValue &Result;
13280 
13281 public:
13282   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13283     : ExprEvaluatorBaseTy(info), Result(Result) {}
13284 
13285   bool Success(const APValue &V, const Expr *e) {
13286     Result.setFrom(V);
13287     return true;
13288   }
13289 
13290   bool ZeroInitialization(const Expr *E);
13291 
13292   //===--------------------------------------------------------------------===//
13293   //                            Visitor Methods
13294   //===--------------------------------------------------------------------===//
13295 
13296   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13297   bool VisitCastExpr(const CastExpr *E);
13298   bool VisitBinaryOperator(const BinaryOperator *E);
13299   bool VisitUnaryOperator(const UnaryOperator *E);
13300   bool VisitInitListExpr(const InitListExpr *E);
13301 };
13302 } // end anonymous namespace
13303 
13304 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13305                             EvalInfo &Info) {
13306   assert(E->isRValue() && E->getType()->isAnyComplexType());
13307   return ComplexExprEvaluator(Info, Result).Visit(E);
13308 }
13309 
13310 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13311   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13312   if (ElemTy->isRealFloatingType()) {
13313     Result.makeComplexFloat();
13314     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13315     Result.FloatReal = Zero;
13316     Result.FloatImag = Zero;
13317   } else {
13318     Result.makeComplexInt();
13319     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13320     Result.IntReal = Zero;
13321     Result.IntImag = Zero;
13322   }
13323   return true;
13324 }
13325 
13326 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13327   const Expr* SubExpr = E->getSubExpr();
13328 
13329   if (SubExpr->getType()->isRealFloatingType()) {
13330     Result.makeComplexFloat();
13331     APFloat &Imag = Result.FloatImag;
13332     if (!EvaluateFloat(SubExpr, Imag, Info))
13333       return false;
13334 
13335     Result.FloatReal = APFloat(Imag.getSemantics());
13336     return true;
13337   } else {
13338     assert(SubExpr->getType()->isIntegerType() &&
13339            "Unexpected imaginary literal.");
13340 
13341     Result.makeComplexInt();
13342     APSInt &Imag = Result.IntImag;
13343     if (!EvaluateInteger(SubExpr, Imag, Info))
13344       return false;
13345 
13346     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13347     return true;
13348   }
13349 }
13350 
13351 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13352 
13353   switch (E->getCastKind()) {
13354   case CK_BitCast:
13355   case CK_BaseToDerived:
13356   case CK_DerivedToBase:
13357   case CK_UncheckedDerivedToBase:
13358   case CK_Dynamic:
13359   case CK_ToUnion:
13360   case CK_ArrayToPointerDecay:
13361   case CK_FunctionToPointerDecay:
13362   case CK_NullToPointer:
13363   case CK_NullToMemberPointer:
13364   case CK_BaseToDerivedMemberPointer:
13365   case CK_DerivedToBaseMemberPointer:
13366   case CK_MemberPointerToBoolean:
13367   case CK_ReinterpretMemberPointer:
13368   case CK_ConstructorConversion:
13369   case CK_IntegralToPointer:
13370   case CK_PointerToIntegral:
13371   case CK_PointerToBoolean:
13372   case CK_ToVoid:
13373   case CK_VectorSplat:
13374   case CK_IntegralCast:
13375   case CK_BooleanToSignedIntegral:
13376   case CK_IntegralToBoolean:
13377   case CK_IntegralToFloating:
13378   case CK_FloatingToIntegral:
13379   case CK_FloatingToBoolean:
13380   case CK_FloatingCast:
13381   case CK_CPointerToObjCPointerCast:
13382   case CK_BlockPointerToObjCPointerCast:
13383   case CK_AnyPointerToBlockPointerCast:
13384   case CK_ObjCObjectLValueCast:
13385   case CK_FloatingComplexToReal:
13386   case CK_FloatingComplexToBoolean:
13387   case CK_IntegralComplexToReal:
13388   case CK_IntegralComplexToBoolean:
13389   case CK_ARCProduceObject:
13390   case CK_ARCConsumeObject:
13391   case CK_ARCReclaimReturnedObject:
13392   case CK_ARCExtendBlockObject:
13393   case CK_CopyAndAutoreleaseBlockObject:
13394   case CK_BuiltinFnToFnPtr:
13395   case CK_ZeroToOCLOpaqueType:
13396   case CK_NonAtomicToAtomic:
13397   case CK_AddressSpaceConversion:
13398   case CK_IntToOCLSampler:
13399   case CK_FixedPointCast:
13400   case CK_FixedPointToBoolean:
13401   case CK_FixedPointToIntegral:
13402   case CK_IntegralToFixedPoint:
13403     llvm_unreachable("invalid cast kind for complex value");
13404 
13405   case CK_LValueToRValue:
13406   case CK_AtomicToNonAtomic:
13407   case CK_NoOp:
13408   case CK_LValueToRValueBitCast:
13409     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13410 
13411   case CK_Dependent:
13412   case CK_LValueBitCast:
13413   case CK_UserDefinedConversion:
13414     return Error(E);
13415 
13416   case CK_FloatingRealToComplex: {
13417     APFloat &Real = Result.FloatReal;
13418     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13419       return false;
13420 
13421     Result.makeComplexFloat();
13422     Result.FloatImag = APFloat(Real.getSemantics());
13423     return true;
13424   }
13425 
13426   case CK_FloatingComplexCast: {
13427     if (!Visit(E->getSubExpr()))
13428       return false;
13429 
13430     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13431     QualType From
13432       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13433 
13434     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13435            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13436   }
13437 
13438   case CK_FloatingComplexToIntegralComplex: {
13439     if (!Visit(E->getSubExpr()))
13440       return false;
13441 
13442     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13443     QualType From
13444       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13445     Result.makeComplexInt();
13446     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13447                                 To, Result.IntReal) &&
13448            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13449                                 To, Result.IntImag);
13450   }
13451 
13452   case CK_IntegralRealToComplex: {
13453     APSInt &Real = Result.IntReal;
13454     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13455       return false;
13456 
13457     Result.makeComplexInt();
13458     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13459     return true;
13460   }
13461 
13462   case CK_IntegralComplexCast: {
13463     if (!Visit(E->getSubExpr()))
13464       return false;
13465 
13466     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13467     QualType From
13468       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13469 
13470     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13471     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13472     return true;
13473   }
13474 
13475   case CK_IntegralComplexToFloatingComplex: {
13476     if (!Visit(E->getSubExpr()))
13477       return false;
13478 
13479     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13480     QualType From
13481       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13482     Result.makeComplexFloat();
13483     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13484                                 To, Result.FloatReal) &&
13485            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13486                                 To, Result.FloatImag);
13487   }
13488   }
13489 
13490   llvm_unreachable("unknown cast resulting in complex value");
13491 }
13492 
13493 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13494   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13495     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13496 
13497   // Track whether the LHS or RHS is real at the type system level. When this is
13498   // the case we can simplify our evaluation strategy.
13499   bool LHSReal = false, RHSReal = false;
13500 
13501   bool LHSOK;
13502   if (E->getLHS()->getType()->isRealFloatingType()) {
13503     LHSReal = true;
13504     APFloat &Real = Result.FloatReal;
13505     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13506     if (LHSOK) {
13507       Result.makeComplexFloat();
13508       Result.FloatImag = APFloat(Real.getSemantics());
13509     }
13510   } else {
13511     LHSOK = Visit(E->getLHS());
13512   }
13513   if (!LHSOK && !Info.noteFailure())
13514     return false;
13515 
13516   ComplexValue RHS;
13517   if (E->getRHS()->getType()->isRealFloatingType()) {
13518     RHSReal = true;
13519     APFloat &Real = RHS.FloatReal;
13520     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13521       return false;
13522     RHS.makeComplexFloat();
13523     RHS.FloatImag = APFloat(Real.getSemantics());
13524   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13525     return false;
13526 
13527   assert(!(LHSReal && RHSReal) &&
13528          "Cannot have both operands of a complex operation be real.");
13529   switch (E->getOpcode()) {
13530   default: return Error(E);
13531   case BO_Add:
13532     if (Result.isComplexFloat()) {
13533       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13534                                        APFloat::rmNearestTiesToEven);
13535       if (LHSReal)
13536         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13537       else if (!RHSReal)
13538         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13539                                          APFloat::rmNearestTiesToEven);
13540     } else {
13541       Result.getComplexIntReal() += RHS.getComplexIntReal();
13542       Result.getComplexIntImag() += RHS.getComplexIntImag();
13543     }
13544     break;
13545   case BO_Sub:
13546     if (Result.isComplexFloat()) {
13547       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13548                                             APFloat::rmNearestTiesToEven);
13549       if (LHSReal) {
13550         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13551         Result.getComplexFloatImag().changeSign();
13552       } else if (!RHSReal) {
13553         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13554                                               APFloat::rmNearestTiesToEven);
13555       }
13556     } else {
13557       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13558       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13559     }
13560     break;
13561   case BO_Mul:
13562     if (Result.isComplexFloat()) {
13563       // This is an implementation of complex multiplication according to the
13564       // constraints laid out in C11 Annex G. The implementation uses the
13565       // following naming scheme:
13566       //   (a + ib) * (c + id)
13567       ComplexValue LHS = Result;
13568       APFloat &A = LHS.getComplexFloatReal();
13569       APFloat &B = LHS.getComplexFloatImag();
13570       APFloat &C = RHS.getComplexFloatReal();
13571       APFloat &D = RHS.getComplexFloatImag();
13572       APFloat &ResR = Result.getComplexFloatReal();
13573       APFloat &ResI = Result.getComplexFloatImag();
13574       if (LHSReal) {
13575         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13576         ResR = A * C;
13577         ResI = A * D;
13578       } else if (RHSReal) {
13579         ResR = C * A;
13580         ResI = C * B;
13581       } else {
13582         // In the fully general case, we need to handle NaNs and infinities
13583         // robustly.
13584         APFloat AC = A * C;
13585         APFloat BD = B * D;
13586         APFloat AD = A * D;
13587         APFloat BC = B * C;
13588         ResR = AC - BD;
13589         ResI = AD + BC;
13590         if (ResR.isNaN() && ResI.isNaN()) {
13591           bool Recalc = false;
13592           if (A.isInfinity() || B.isInfinity()) {
13593             A = APFloat::copySign(
13594                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13595             B = APFloat::copySign(
13596                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13597             if (C.isNaN())
13598               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13599             if (D.isNaN())
13600               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13601             Recalc = true;
13602           }
13603           if (C.isInfinity() || D.isInfinity()) {
13604             C = APFloat::copySign(
13605                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13606             D = APFloat::copySign(
13607                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13608             if (A.isNaN())
13609               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13610             if (B.isNaN())
13611               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13612             Recalc = true;
13613           }
13614           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13615                           AD.isInfinity() || BC.isInfinity())) {
13616             if (A.isNaN())
13617               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13618             if (B.isNaN())
13619               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13620             if (C.isNaN())
13621               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13622             if (D.isNaN())
13623               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13624             Recalc = true;
13625           }
13626           if (Recalc) {
13627             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13628             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13629           }
13630         }
13631       }
13632     } else {
13633       ComplexValue LHS = Result;
13634       Result.getComplexIntReal() =
13635         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13636          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13637       Result.getComplexIntImag() =
13638         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13639          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13640     }
13641     break;
13642   case BO_Div:
13643     if (Result.isComplexFloat()) {
13644       // This is an implementation of complex division according to the
13645       // constraints laid out in C11 Annex G. The implementation uses the
13646       // following naming scheme:
13647       //   (a + ib) / (c + id)
13648       ComplexValue LHS = Result;
13649       APFloat &A = LHS.getComplexFloatReal();
13650       APFloat &B = LHS.getComplexFloatImag();
13651       APFloat &C = RHS.getComplexFloatReal();
13652       APFloat &D = RHS.getComplexFloatImag();
13653       APFloat &ResR = Result.getComplexFloatReal();
13654       APFloat &ResI = Result.getComplexFloatImag();
13655       if (RHSReal) {
13656         ResR = A / C;
13657         ResI = B / C;
13658       } else {
13659         if (LHSReal) {
13660           // No real optimizations we can do here, stub out with zero.
13661           B = APFloat::getZero(A.getSemantics());
13662         }
13663         int DenomLogB = 0;
13664         APFloat MaxCD = maxnum(abs(C), abs(D));
13665         if (MaxCD.isFinite()) {
13666           DenomLogB = ilogb(MaxCD);
13667           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13668           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13669         }
13670         APFloat Denom = C * C + D * D;
13671         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13672                       APFloat::rmNearestTiesToEven);
13673         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13674                       APFloat::rmNearestTiesToEven);
13675         if (ResR.isNaN() && ResI.isNaN()) {
13676           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13677             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13678             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13679           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13680                      D.isFinite()) {
13681             A = APFloat::copySign(
13682                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13683             B = APFloat::copySign(
13684                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13685             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13686             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13687           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13688             C = APFloat::copySign(
13689                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13690             D = APFloat::copySign(
13691                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13692             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13693             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13694           }
13695         }
13696       }
13697     } else {
13698       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13699         return Error(E, diag::note_expr_divide_by_zero);
13700 
13701       ComplexValue LHS = Result;
13702       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13703         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13704       Result.getComplexIntReal() =
13705         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13706          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13707       Result.getComplexIntImag() =
13708         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13709          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13710     }
13711     break;
13712   }
13713 
13714   return true;
13715 }
13716 
13717 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13718   // Get the operand value into 'Result'.
13719   if (!Visit(E->getSubExpr()))
13720     return false;
13721 
13722   switch (E->getOpcode()) {
13723   default:
13724     return Error(E);
13725   case UO_Extension:
13726     return true;
13727   case UO_Plus:
13728     // The result is always just the subexpr.
13729     return true;
13730   case UO_Minus:
13731     if (Result.isComplexFloat()) {
13732       Result.getComplexFloatReal().changeSign();
13733       Result.getComplexFloatImag().changeSign();
13734     }
13735     else {
13736       Result.getComplexIntReal() = -Result.getComplexIntReal();
13737       Result.getComplexIntImag() = -Result.getComplexIntImag();
13738     }
13739     return true;
13740   case UO_Not:
13741     if (Result.isComplexFloat())
13742       Result.getComplexFloatImag().changeSign();
13743     else
13744       Result.getComplexIntImag() = -Result.getComplexIntImag();
13745     return true;
13746   }
13747 }
13748 
13749 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13750   if (E->getNumInits() == 2) {
13751     if (E->getType()->isComplexType()) {
13752       Result.makeComplexFloat();
13753       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13754         return false;
13755       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13756         return false;
13757     } else {
13758       Result.makeComplexInt();
13759       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13760         return false;
13761       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13762         return false;
13763     }
13764     return true;
13765   }
13766   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13767 }
13768 
13769 //===----------------------------------------------------------------------===//
13770 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13771 // implicit conversion.
13772 //===----------------------------------------------------------------------===//
13773 
13774 namespace {
13775 class AtomicExprEvaluator :
13776     public ExprEvaluatorBase<AtomicExprEvaluator> {
13777   const LValue *This;
13778   APValue &Result;
13779 public:
13780   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13781       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13782 
13783   bool Success(const APValue &V, const Expr *E) {
13784     Result = V;
13785     return true;
13786   }
13787 
13788   bool ZeroInitialization(const Expr *E) {
13789     ImplicitValueInitExpr VIE(
13790         E->getType()->castAs<AtomicType>()->getValueType());
13791     // For atomic-qualified class (and array) types in C++, initialize the
13792     // _Atomic-wrapped subobject directly, in-place.
13793     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13794                 : Evaluate(Result, Info, &VIE);
13795   }
13796 
13797   bool VisitCastExpr(const CastExpr *E) {
13798     switch (E->getCastKind()) {
13799     default:
13800       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13801     case CK_NonAtomicToAtomic:
13802       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13803                   : Evaluate(Result, Info, E->getSubExpr());
13804     }
13805   }
13806 };
13807 } // end anonymous namespace
13808 
13809 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13810                            EvalInfo &Info) {
13811   assert(E->isRValue() && E->getType()->isAtomicType());
13812   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13813 }
13814 
13815 //===----------------------------------------------------------------------===//
13816 // Void expression evaluation, primarily for a cast to void on the LHS of a
13817 // comma operator
13818 //===----------------------------------------------------------------------===//
13819 
13820 namespace {
13821 class VoidExprEvaluator
13822   : public ExprEvaluatorBase<VoidExprEvaluator> {
13823 public:
13824   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13825 
13826   bool Success(const APValue &V, const Expr *e) { return true; }
13827 
13828   bool ZeroInitialization(const Expr *E) { return true; }
13829 
13830   bool VisitCastExpr(const CastExpr *E) {
13831     switch (E->getCastKind()) {
13832     default:
13833       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13834     case CK_ToVoid:
13835       VisitIgnoredValue(E->getSubExpr());
13836       return true;
13837     }
13838   }
13839 
13840   bool VisitCallExpr(const CallExpr *E) {
13841     switch (E->getBuiltinCallee()) {
13842     case Builtin::BI__assume:
13843     case Builtin::BI__builtin_assume:
13844       // The argument is not evaluated!
13845       return true;
13846 
13847     case Builtin::BI__builtin_operator_delete:
13848       return HandleOperatorDeleteCall(Info, E);
13849 
13850     default:
13851       break;
13852     }
13853 
13854     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13855   }
13856 
13857   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13858 };
13859 } // end anonymous namespace
13860 
13861 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13862   // We cannot speculatively evaluate a delete expression.
13863   if (Info.SpeculativeEvaluationDepth)
13864     return false;
13865 
13866   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13867   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13868     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13869         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13870     return false;
13871   }
13872 
13873   const Expr *Arg = E->getArgument();
13874 
13875   LValue Pointer;
13876   if (!EvaluatePointer(Arg, Pointer, Info))
13877     return false;
13878   if (Pointer.Designator.Invalid)
13879     return false;
13880 
13881   // Deleting a null pointer has no effect.
13882   if (Pointer.isNullPointer()) {
13883     // This is the only case where we need to produce an extension warning:
13884     // the only other way we can succeed is if we find a dynamic allocation,
13885     // and we will have warned when we allocated it in that case.
13886     if (!Info.getLangOpts().CPlusPlus20)
13887       Info.CCEDiag(E, diag::note_constexpr_new);
13888     return true;
13889   }
13890 
13891   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13892       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13893   if (!Alloc)
13894     return false;
13895   QualType AllocType = Pointer.Base.getDynamicAllocType();
13896 
13897   // For the non-array case, the designator must be empty if the static type
13898   // does not have a virtual destructor.
13899   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13900       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13901     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13902         << Arg->getType()->getPointeeType() << AllocType;
13903     return false;
13904   }
13905 
13906   // For a class type with a virtual destructor, the selected operator delete
13907   // is the one looked up when building the destructor.
13908   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13909     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13910     if (VirtualDelete &&
13911         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13912       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13913           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13914       return false;
13915     }
13916   }
13917 
13918   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13919                          (*Alloc)->Value, AllocType))
13920     return false;
13921 
13922   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13923     // The element was already erased. This means the destructor call also
13924     // deleted the object.
13925     // FIXME: This probably results in undefined behavior before we get this
13926     // far, and should be diagnosed elsewhere first.
13927     Info.FFDiag(E, diag::note_constexpr_double_delete);
13928     return false;
13929   }
13930 
13931   return true;
13932 }
13933 
13934 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13935   assert(E->isRValue() && E->getType()->isVoidType());
13936   return VoidExprEvaluator(Info).Visit(E);
13937 }
13938 
13939 //===----------------------------------------------------------------------===//
13940 // Top level Expr::EvaluateAsRValue method.
13941 //===----------------------------------------------------------------------===//
13942 
13943 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13944   // In C, function designators are not lvalues, but we evaluate them as if they
13945   // are.
13946   QualType T = E->getType();
13947   if (E->isGLValue() || T->isFunctionType()) {
13948     LValue LV;
13949     if (!EvaluateLValue(E, LV, Info))
13950       return false;
13951     LV.moveInto(Result);
13952   } else if (T->isVectorType()) {
13953     if (!EvaluateVector(E, Result, Info))
13954       return false;
13955   } else if (T->isIntegralOrEnumerationType()) {
13956     if (!IntExprEvaluator(Info, Result).Visit(E))
13957       return false;
13958   } else if (T->hasPointerRepresentation()) {
13959     LValue LV;
13960     if (!EvaluatePointer(E, LV, Info))
13961       return false;
13962     LV.moveInto(Result);
13963   } else if (T->isRealFloatingType()) {
13964     llvm::APFloat F(0.0);
13965     if (!EvaluateFloat(E, F, Info))
13966       return false;
13967     Result = APValue(F);
13968   } else if (T->isAnyComplexType()) {
13969     ComplexValue C;
13970     if (!EvaluateComplex(E, C, Info))
13971       return false;
13972     C.moveInto(Result);
13973   } else if (T->isFixedPointType()) {
13974     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13975   } else if (T->isMemberPointerType()) {
13976     MemberPtr P;
13977     if (!EvaluateMemberPointer(E, P, Info))
13978       return false;
13979     P.moveInto(Result);
13980     return true;
13981   } else if (T->isArrayType()) {
13982     LValue LV;
13983     APValue &Value =
13984         Info.CurrentCall->createTemporary(E, T, false, LV);
13985     if (!EvaluateArray(E, LV, Value, Info))
13986       return false;
13987     Result = Value;
13988   } else if (T->isRecordType()) {
13989     LValue LV;
13990     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13991     if (!EvaluateRecord(E, LV, Value, Info))
13992       return false;
13993     Result = Value;
13994   } else if (T->isVoidType()) {
13995     if (!Info.getLangOpts().CPlusPlus11)
13996       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13997         << E->getType();
13998     if (!EvaluateVoid(E, Info))
13999       return false;
14000   } else if (T->isAtomicType()) {
14001     QualType Unqual = T.getAtomicUnqualifiedType();
14002     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14003       LValue LV;
14004       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
14005       if (!EvaluateAtomic(E, &LV, Value, Info))
14006         return false;
14007     } else {
14008       if (!EvaluateAtomic(E, nullptr, Result, Info))
14009         return false;
14010     }
14011   } else if (Info.getLangOpts().CPlusPlus11) {
14012     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14013     return false;
14014   } else {
14015     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14016     return false;
14017   }
14018 
14019   return true;
14020 }
14021 
14022 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14023 /// cases, the in-place evaluation is essential, since later initializers for
14024 /// an object can indirectly refer to subobjects which were initialized earlier.
14025 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14026                             const Expr *E, bool AllowNonLiteralTypes) {
14027   assert(!E->isValueDependent());
14028 
14029   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14030     return false;
14031 
14032   if (E->isRValue()) {
14033     // Evaluate arrays and record types in-place, so that later initializers can
14034     // refer to earlier-initialized members of the object.
14035     QualType T = E->getType();
14036     if (T->isArrayType())
14037       return EvaluateArray(E, This, Result, Info);
14038     else if (T->isRecordType())
14039       return EvaluateRecord(E, This, Result, Info);
14040     else if (T->isAtomicType()) {
14041       QualType Unqual = T.getAtomicUnqualifiedType();
14042       if (Unqual->isArrayType() || Unqual->isRecordType())
14043         return EvaluateAtomic(E, &This, Result, Info);
14044     }
14045   }
14046 
14047   // For any other type, in-place evaluation is unimportant.
14048   return Evaluate(Result, Info, E);
14049 }
14050 
14051 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14052 /// lvalue-to-rvalue cast if it is an lvalue.
14053 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14054   if (Info.EnableNewConstInterp) {
14055     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14056       return false;
14057   } else {
14058     if (E->getType().isNull())
14059       return false;
14060 
14061     if (!CheckLiteralType(Info, E))
14062       return false;
14063 
14064     if (!::Evaluate(Result, Info, E))
14065       return false;
14066 
14067     if (E->isGLValue()) {
14068       LValue LV;
14069       LV.setFrom(Info.Ctx, Result);
14070       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14071         return false;
14072     }
14073   }
14074 
14075   // Check this core constant expression is a constant expression.
14076   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
14077          CheckMemoryLeaks(Info);
14078 }
14079 
14080 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14081                                  const ASTContext &Ctx, bool &IsConst) {
14082   // Fast-path evaluations of integer literals, since we sometimes see files
14083   // containing vast quantities of these.
14084   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14085     Result.Val = APValue(APSInt(L->getValue(),
14086                                 L->getType()->isUnsignedIntegerType()));
14087     IsConst = true;
14088     return true;
14089   }
14090 
14091   // This case should be rare, but we need to check it before we check on
14092   // the type below.
14093   if (Exp->getType().isNull()) {
14094     IsConst = false;
14095     return true;
14096   }
14097 
14098   // FIXME: Evaluating values of large array and record types can cause
14099   // performance problems. Only do so in C++11 for now.
14100   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14101                           Exp->getType()->isRecordType()) &&
14102       !Ctx.getLangOpts().CPlusPlus11) {
14103     IsConst = false;
14104     return true;
14105   }
14106   return false;
14107 }
14108 
14109 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14110                                       Expr::SideEffectsKind SEK) {
14111   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14112          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14113 }
14114 
14115 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14116                              const ASTContext &Ctx, EvalInfo &Info) {
14117   bool IsConst;
14118   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14119     return IsConst;
14120 
14121   return EvaluateAsRValue(Info, E, Result.Val);
14122 }
14123 
14124 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14125                           const ASTContext &Ctx,
14126                           Expr::SideEffectsKind AllowSideEffects,
14127                           EvalInfo &Info) {
14128   if (!E->getType()->isIntegralOrEnumerationType())
14129     return false;
14130 
14131   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14132       !ExprResult.Val.isInt() ||
14133       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14134     return false;
14135 
14136   return true;
14137 }
14138 
14139 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14140                                  const ASTContext &Ctx,
14141                                  Expr::SideEffectsKind AllowSideEffects,
14142                                  EvalInfo &Info) {
14143   if (!E->getType()->isFixedPointType())
14144     return false;
14145 
14146   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14147     return false;
14148 
14149   if (!ExprResult.Val.isFixedPoint() ||
14150       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14151     return false;
14152 
14153   return true;
14154 }
14155 
14156 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14157 /// any crazy technique (that has nothing to do with language standards) that
14158 /// we want to.  If this function returns true, it returns the folded constant
14159 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14160 /// will be applied to the result.
14161 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14162                             bool InConstantContext) const {
14163   assert(!isValueDependent() &&
14164          "Expression evaluator can't be called on a dependent expression.");
14165   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14166   Info.InConstantContext = InConstantContext;
14167   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14168 }
14169 
14170 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14171                                       bool InConstantContext) const {
14172   assert(!isValueDependent() &&
14173          "Expression evaluator can't be called on a dependent expression.");
14174   EvalResult Scratch;
14175   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14176          HandleConversionToBool(Scratch.Val, Result);
14177 }
14178 
14179 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14180                          SideEffectsKind AllowSideEffects,
14181                          bool InConstantContext) const {
14182   assert(!isValueDependent() &&
14183          "Expression evaluator can't be called on a dependent expression.");
14184   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14185   Info.InConstantContext = InConstantContext;
14186   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14187 }
14188 
14189 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14190                                 SideEffectsKind AllowSideEffects,
14191                                 bool InConstantContext) const {
14192   assert(!isValueDependent() &&
14193          "Expression evaluator can't be called on a dependent expression.");
14194   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14195   Info.InConstantContext = InConstantContext;
14196   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14197 }
14198 
14199 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14200                            SideEffectsKind AllowSideEffects,
14201                            bool InConstantContext) const {
14202   assert(!isValueDependent() &&
14203          "Expression evaluator can't be called on a dependent expression.");
14204 
14205   if (!getType()->isRealFloatingType())
14206     return false;
14207 
14208   EvalResult ExprResult;
14209   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14210       !ExprResult.Val.isFloat() ||
14211       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14212     return false;
14213 
14214   Result = ExprResult.Val.getFloat();
14215   return true;
14216 }
14217 
14218 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14219                             bool InConstantContext) const {
14220   assert(!isValueDependent() &&
14221          "Expression evaluator can't be called on a dependent expression.");
14222 
14223   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14224   Info.InConstantContext = InConstantContext;
14225   LValue LV;
14226   CheckedTemporaries CheckedTemps;
14227   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14228       Result.HasSideEffects ||
14229       !CheckLValueConstantExpression(Info, getExprLoc(),
14230                                      Ctx.getLValueReferenceType(getType()), LV,
14231                                      Expr::EvaluateForCodeGen, CheckedTemps))
14232     return false;
14233 
14234   LV.moveInto(Result.Val);
14235   return true;
14236 }
14237 
14238 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
14239                                   const ASTContext &Ctx, bool InPlace) const {
14240   assert(!isValueDependent() &&
14241          "Expression evaluator can't be called on a dependent expression.");
14242 
14243   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14244   EvalInfo Info(Ctx, Result, EM);
14245   Info.InConstantContext = true;
14246 
14247   if (InPlace) {
14248     Info.setEvaluatingDecl(this, Result.Val);
14249     LValue LVal;
14250     LVal.set(this);
14251     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
14252         Result.HasSideEffects)
14253       return false;
14254   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
14255     return false;
14256 
14257   if (!Info.discardCleanups())
14258     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14259 
14260   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14261                                  Result.Val, Usage) &&
14262          CheckMemoryLeaks(Info);
14263 }
14264 
14265 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14266                                  const VarDecl *VD,
14267                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14268   assert(!isValueDependent() &&
14269          "Expression evaluator can't be called on a dependent expression.");
14270 
14271   // FIXME: Evaluating initializers for large array and record types can cause
14272   // performance problems. Only do so in C++11 for now.
14273   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14274       !Ctx.getLangOpts().CPlusPlus11)
14275     return false;
14276 
14277   Expr::EvalStatus EStatus;
14278   EStatus.Diag = &Notes;
14279 
14280   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
14281                                       ? EvalInfo::EM_ConstantExpression
14282                                       : EvalInfo::EM_ConstantFold);
14283   Info.setEvaluatingDecl(VD, Value);
14284   Info.InConstantContext = true;
14285 
14286   SourceLocation DeclLoc = VD->getLocation();
14287   QualType DeclTy = VD->getType();
14288 
14289   if (Info.EnableNewConstInterp) {
14290     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14291     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14292       return false;
14293   } else {
14294     LValue LVal;
14295     LVal.set(VD);
14296 
14297     if (!EvaluateInPlace(Value, Info, LVal, this,
14298                          /*AllowNonLiteralTypes=*/true) ||
14299         EStatus.HasSideEffects)
14300       return false;
14301 
14302     // At this point, any lifetime-extended temporaries are completely
14303     // initialized.
14304     Info.performLifetimeExtension();
14305 
14306     if (!Info.discardCleanups())
14307       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14308   }
14309   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
14310          CheckMemoryLeaks(Info);
14311 }
14312 
14313 bool VarDecl::evaluateDestruction(
14314     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14315   Expr::EvalStatus EStatus;
14316   EStatus.Diag = &Notes;
14317 
14318   // Make a copy of the value for the destructor to mutate, if we know it.
14319   // Otherwise, treat the value as default-initialized; if the destructor works
14320   // anyway, then the destruction is constant (and must be essentially empty).
14321   APValue DestroyedValue;
14322   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14323     DestroyedValue = *getEvaluatedValue();
14324   else if (!getDefaultInitValue(getType(), DestroyedValue))
14325     return false;
14326 
14327   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
14328   Info.setEvaluatingDecl(this, DestroyedValue,
14329                          EvalInfo::EvaluatingDeclKind::Dtor);
14330   Info.InConstantContext = true;
14331 
14332   SourceLocation DeclLoc = getLocation();
14333   QualType DeclTy = getType();
14334 
14335   LValue LVal;
14336   LVal.set(this);
14337 
14338   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14339       EStatus.HasSideEffects)
14340     return false;
14341 
14342   if (!Info.discardCleanups())
14343     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14344 
14345   ensureEvaluatedStmt()->HasConstantDestruction = true;
14346   return true;
14347 }
14348 
14349 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14350 /// constant folded, but discard the result.
14351 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14352   assert(!isValueDependent() &&
14353          "Expression evaluator can't be called on a dependent expression.");
14354 
14355   EvalResult Result;
14356   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14357          !hasUnacceptableSideEffect(Result, SEK);
14358 }
14359 
14360 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14361                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14362   assert(!isValueDependent() &&
14363          "Expression evaluator can't be called on a dependent expression.");
14364 
14365   EvalResult EVResult;
14366   EVResult.Diag = Diag;
14367   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14368   Info.InConstantContext = true;
14369 
14370   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14371   (void)Result;
14372   assert(Result && "Could not evaluate expression");
14373   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14374 
14375   return EVResult.Val.getInt();
14376 }
14377 
14378 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14379     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14380   assert(!isValueDependent() &&
14381          "Expression evaluator can't be called on a dependent expression.");
14382 
14383   EvalResult EVResult;
14384   EVResult.Diag = Diag;
14385   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14386   Info.InConstantContext = true;
14387   Info.CheckingForUndefinedBehavior = true;
14388 
14389   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14390   (void)Result;
14391   assert(Result && "Could not evaluate expression");
14392   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14393 
14394   return EVResult.Val.getInt();
14395 }
14396 
14397 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14398   assert(!isValueDependent() &&
14399          "Expression evaluator can't be called on a dependent expression.");
14400 
14401   bool IsConst;
14402   EvalResult EVResult;
14403   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14404     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14405     Info.CheckingForUndefinedBehavior = true;
14406     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14407   }
14408 }
14409 
14410 bool Expr::EvalResult::isGlobalLValue() const {
14411   assert(Val.isLValue());
14412   return IsGlobalLValue(Val.getLValueBase());
14413 }
14414 
14415 
14416 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14417 /// an integer constant expression.
14418 
14419 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14420 /// comma, etc
14421 
14422 // CheckICE - This function does the fundamental ICE checking: the returned
14423 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14424 // and a (possibly null) SourceLocation indicating the location of the problem.
14425 //
14426 // Note that to reduce code duplication, this helper does no evaluation
14427 // itself; the caller checks whether the expression is evaluatable, and
14428 // in the rare cases where CheckICE actually cares about the evaluated
14429 // value, it calls into Evaluate.
14430 
14431 namespace {
14432 
14433 enum ICEKind {
14434   /// This expression is an ICE.
14435   IK_ICE,
14436   /// This expression is not an ICE, but if it isn't evaluated, it's
14437   /// a legal subexpression for an ICE. This return value is used to handle
14438   /// the comma operator in C99 mode, and non-constant subexpressions.
14439   IK_ICEIfUnevaluated,
14440   /// This expression is not an ICE, and is not a legal subexpression for one.
14441   IK_NotICE
14442 };
14443 
14444 struct ICEDiag {
14445   ICEKind Kind;
14446   SourceLocation Loc;
14447 
14448   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14449 };
14450 
14451 }
14452 
14453 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14454 
14455 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14456 
14457 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14458   Expr::EvalResult EVResult;
14459   Expr::EvalStatus Status;
14460   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14461 
14462   Info.InConstantContext = true;
14463   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14464       !EVResult.Val.isInt())
14465     return ICEDiag(IK_NotICE, E->getBeginLoc());
14466 
14467   return NoDiag();
14468 }
14469 
14470 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14471   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14472   if (!E->getType()->isIntegralOrEnumerationType())
14473     return ICEDiag(IK_NotICE, E->getBeginLoc());
14474 
14475   switch (E->getStmtClass()) {
14476 #define ABSTRACT_STMT(Node)
14477 #define STMT(Node, Base) case Expr::Node##Class:
14478 #define EXPR(Node, Base)
14479 #include "clang/AST/StmtNodes.inc"
14480   case Expr::PredefinedExprClass:
14481   case Expr::FloatingLiteralClass:
14482   case Expr::ImaginaryLiteralClass:
14483   case Expr::StringLiteralClass:
14484   case Expr::ArraySubscriptExprClass:
14485   case Expr::MatrixSubscriptExprClass:
14486   case Expr::OMPArraySectionExprClass:
14487   case Expr::OMPArrayShapingExprClass:
14488   case Expr::OMPIteratorExprClass:
14489   case Expr::MemberExprClass:
14490   case Expr::CompoundAssignOperatorClass:
14491   case Expr::CompoundLiteralExprClass:
14492   case Expr::ExtVectorElementExprClass:
14493   case Expr::DesignatedInitExprClass:
14494   case Expr::ArrayInitLoopExprClass:
14495   case Expr::ArrayInitIndexExprClass:
14496   case Expr::NoInitExprClass:
14497   case Expr::DesignatedInitUpdateExprClass:
14498   case Expr::ImplicitValueInitExprClass:
14499   case Expr::ParenListExprClass:
14500   case Expr::VAArgExprClass:
14501   case Expr::AddrLabelExprClass:
14502   case Expr::StmtExprClass:
14503   case Expr::CXXMemberCallExprClass:
14504   case Expr::CUDAKernelCallExprClass:
14505   case Expr::CXXAddrspaceCastExprClass:
14506   case Expr::CXXDynamicCastExprClass:
14507   case Expr::CXXTypeidExprClass:
14508   case Expr::CXXUuidofExprClass:
14509   case Expr::MSPropertyRefExprClass:
14510   case Expr::MSPropertySubscriptExprClass:
14511   case Expr::CXXNullPtrLiteralExprClass:
14512   case Expr::UserDefinedLiteralClass:
14513   case Expr::CXXThisExprClass:
14514   case Expr::CXXThrowExprClass:
14515   case Expr::CXXNewExprClass:
14516   case Expr::CXXDeleteExprClass:
14517   case Expr::CXXPseudoDestructorExprClass:
14518   case Expr::UnresolvedLookupExprClass:
14519   case Expr::TypoExprClass:
14520   case Expr::RecoveryExprClass:
14521   case Expr::DependentScopeDeclRefExprClass:
14522   case Expr::CXXConstructExprClass:
14523   case Expr::CXXInheritedCtorInitExprClass:
14524   case Expr::CXXStdInitializerListExprClass:
14525   case Expr::CXXBindTemporaryExprClass:
14526   case Expr::ExprWithCleanupsClass:
14527   case Expr::CXXTemporaryObjectExprClass:
14528   case Expr::CXXUnresolvedConstructExprClass:
14529   case Expr::CXXDependentScopeMemberExprClass:
14530   case Expr::UnresolvedMemberExprClass:
14531   case Expr::ObjCStringLiteralClass:
14532   case Expr::ObjCBoxedExprClass:
14533   case Expr::ObjCArrayLiteralClass:
14534   case Expr::ObjCDictionaryLiteralClass:
14535   case Expr::ObjCEncodeExprClass:
14536   case Expr::ObjCMessageExprClass:
14537   case Expr::ObjCSelectorExprClass:
14538   case Expr::ObjCProtocolExprClass:
14539   case Expr::ObjCIvarRefExprClass:
14540   case Expr::ObjCPropertyRefExprClass:
14541   case Expr::ObjCSubscriptRefExprClass:
14542   case Expr::ObjCIsaExprClass:
14543   case Expr::ObjCAvailabilityCheckExprClass:
14544   case Expr::ShuffleVectorExprClass:
14545   case Expr::ConvertVectorExprClass:
14546   case Expr::BlockExprClass:
14547   case Expr::NoStmtClass:
14548   case Expr::OpaqueValueExprClass:
14549   case Expr::PackExpansionExprClass:
14550   case Expr::SubstNonTypeTemplateParmPackExprClass:
14551   case Expr::FunctionParmPackExprClass:
14552   case Expr::AsTypeExprClass:
14553   case Expr::ObjCIndirectCopyRestoreExprClass:
14554   case Expr::MaterializeTemporaryExprClass:
14555   case Expr::PseudoObjectExprClass:
14556   case Expr::AtomicExprClass:
14557   case Expr::LambdaExprClass:
14558   case Expr::CXXFoldExprClass:
14559   case Expr::CoawaitExprClass:
14560   case Expr::DependentCoawaitExprClass:
14561   case Expr::CoyieldExprClass:
14562     return ICEDiag(IK_NotICE, E->getBeginLoc());
14563 
14564   case Expr::InitListExprClass: {
14565     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14566     // form "T x = { a };" is equivalent to "T x = a;".
14567     // Unless we're initializing a reference, T is a scalar as it is known to be
14568     // of integral or enumeration type.
14569     if (E->isRValue())
14570       if (cast<InitListExpr>(E)->getNumInits() == 1)
14571         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14572     return ICEDiag(IK_NotICE, E->getBeginLoc());
14573   }
14574 
14575   case Expr::SizeOfPackExprClass:
14576   case Expr::GNUNullExprClass:
14577   case Expr::SourceLocExprClass:
14578     return NoDiag();
14579 
14580   case Expr::SubstNonTypeTemplateParmExprClass:
14581     return
14582       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14583 
14584   case Expr::ConstantExprClass:
14585     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14586 
14587   case Expr::ParenExprClass:
14588     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14589   case Expr::GenericSelectionExprClass:
14590     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14591   case Expr::IntegerLiteralClass:
14592   case Expr::FixedPointLiteralClass:
14593   case Expr::CharacterLiteralClass:
14594   case Expr::ObjCBoolLiteralExprClass:
14595   case Expr::CXXBoolLiteralExprClass:
14596   case Expr::CXXScalarValueInitExprClass:
14597   case Expr::TypeTraitExprClass:
14598   case Expr::ConceptSpecializationExprClass:
14599   case Expr::RequiresExprClass:
14600   case Expr::ArrayTypeTraitExprClass:
14601   case Expr::ExpressionTraitExprClass:
14602   case Expr::CXXNoexceptExprClass:
14603     return NoDiag();
14604   case Expr::CallExprClass:
14605   case Expr::CXXOperatorCallExprClass: {
14606     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14607     // constant expressions, but they can never be ICEs because an ICE cannot
14608     // contain an operand of (pointer to) function type.
14609     const CallExpr *CE = cast<CallExpr>(E);
14610     if (CE->getBuiltinCallee())
14611       return CheckEvalInICE(E, Ctx);
14612     return ICEDiag(IK_NotICE, E->getBeginLoc());
14613   }
14614   case Expr::CXXRewrittenBinaryOperatorClass:
14615     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14616                     Ctx);
14617   case Expr::DeclRefExprClass: {
14618     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14619       return NoDiag();
14620     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14621     if (Ctx.getLangOpts().CPlusPlus &&
14622         D && IsConstNonVolatile(D->getType())) {
14623       // Parameter variables are never constants.  Without this check,
14624       // getAnyInitializer() can find a default argument, which leads
14625       // to chaos.
14626       if (isa<ParmVarDecl>(D))
14627         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14628 
14629       // C++ 7.1.5.1p2
14630       //   A variable of non-volatile const-qualified integral or enumeration
14631       //   type initialized by an ICE can be used in ICEs.
14632       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14633         if (!Dcl->getType()->isIntegralOrEnumerationType())
14634           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14635 
14636         const VarDecl *VD;
14637         // Look for a declaration of this variable that has an initializer, and
14638         // check whether it is an ICE.
14639         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14640           return NoDiag();
14641         else
14642           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14643       }
14644     }
14645     return ICEDiag(IK_NotICE, E->getBeginLoc());
14646   }
14647   case Expr::UnaryOperatorClass: {
14648     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14649     switch (Exp->getOpcode()) {
14650     case UO_PostInc:
14651     case UO_PostDec:
14652     case UO_PreInc:
14653     case UO_PreDec:
14654     case UO_AddrOf:
14655     case UO_Deref:
14656     case UO_Coawait:
14657       // C99 6.6/3 allows increment and decrement within unevaluated
14658       // subexpressions of constant expressions, but they can never be ICEs
14659       // because an ICE cannot contain an lvalue operand.
14660       return ICEDiag(IK_NotICE, E->getBeginLoc());
14661     case UO_Extension:
14662     case UO_LNot:
14663     case UO_Plus:
14664     case UO_Minus:
14665     case UO_Not:
14666     case UO_Real:
14667     case UO_Imag:
14668       return CheckICE(Exp->getSubExpr(), Ctx);
14669     }
14670     llvm_unreachable("invalid unary operator class");
14671   }
14672   case Expr::OffsetOfExprClass: {
14673     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14674     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14675     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14676     // compliance: we should warn earlier for offsetof expressions with
14677     // array subscripts that aren't ICEs, and if the array subscripts
14678     // are ICEs, the value of the offsetof must be an integer constant.
14679     return CheckEvalInICE(E, Ctx);
14680   }
14681   case Expr::UnaryExprOrTypeTraitExprClass: {
14682     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14683     if ((Exp->getKind() ==  UETT_SizeOf) &&
14684         Exp->getTypeOfArgument()->isVariableArrayType())
14685       return ICEDiag(IK_NotICE, E->getBeginLoc());
14686     return NoDiag();
14687   }
14688   case Expr::BinaryOperatorClass: {
14689     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14690     switch (Exp->getOpcode()) {
14691     case BO_PtrMemD:
14692     case BO_PtrMemI:
14693     case BO_Assign:
14694     case BO_MulAssign:
14695     case BO_DivAssign:
14696     case BO_RemAssign:
14697     case BO_AddAssign:
14698     case BO_SubAssign:
14699     case BO_ShlAssign:
14700     case BO_ShrAssign:
14701     case BO_AndAssign:
14702     case BO_XorAssign:
14703     case BO_OrAssign:
14704       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14705       // constant expressions, but they can never be ICEs because an ICE cannot
14706       // contain an lvalue operand.
14707       return ICEDiag(IK_NotICE, E->getBeginLoc());
14708 
14709     case BO_Mul:
14710     case BO_Div:
14711     case BO_Rem:
14712     case BO_Add:
14713     case BO_Sub:
14714     case BO_Shl:
14715     case BO_Shr:
14716     case BO_LT:
14717     case BO_GT:
14718     case BO_LE:
14719     case BO_GE:
14720     case BO_EQ:
14721     case BO_NE:
14722     case BO_And:
14723     case BO_Xor:
14724     case BO_Or:
14725     case BO_Comma:
14726     case BO_Cmp: {
14727       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14728       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14729       if (Exp->getOpcode() == BO_Div ||
14730           Exp->getOpcode() == BO_Rem) {
14731         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14732         // we don't evaluate one.
14733         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14734           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14735           if (REval == 0)
14736             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14737           if (REval.isSigned() && REval.isAllOnesValue()) {
14738             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14739             if (LEval.isMinSignedValue())
14740               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14741           }
14742         }
14743       }
14744       if (Exp->getOpcode() == BO_Comma) {
14745         if (Ctx.getLangOpts().C99) {
14746           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14747           // if it isn't evaluated.
14748           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14749             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14750         } else {
14751           // In both C89 and C++, commas in ICEs are illegal.
14752           return ICEDiag(IK_NotICE, E->getBeginLoc());
14753         }
14754       }
14755       return Worst(LHSResult, RHSResult);
14756     }
14757     case BO_LAnd:
14758     case BO_LOr: {
14759       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14760       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14761       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14762         // Rare case where the RHS has a comma "side-effect"; we need
14763         // to actually check the condition to see whether the side
14764         // with the comma is evaluated.
14765         if ((Exp->getOpcode() == BO_LAnd) !=
14766             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14767           return RHSResult;
14768         return NoDiag();
14769       }
14770 
14771       return Worst(LHSResult, RHSResult);
14772     }
14773     }
14774     llvm_unreachable("invalid binary operator kind");
14775   }
14776   case Expr::ImplicitCastExprClass:
14777   case Expr::CStyleCastExprClass:
14778   case Expr::CXXFunctionalCastExprClass:
14779   case Expr::CXXStaticCastExprClass:
14780   case Expr::CXXReinterpretCastExprClass:
14781   case Expr::CXXConstCastExprClass:
14782   case Expr::ObjCBridgedCastExprClass: {
14783     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14784     if (isa<ExplicitCastExpr>(E)) {
14785       if (const FloatingLiteral *FL
14786             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14787         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14788         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14789         APSInt IgnoredVal(DestWidth, !DestSigned);
14790         bool Ignored;
14791         // If the value does not fit in the destination type, the behavior is
14792         // undefined, so we are not required to treat it as a constant
14793         // expression.
14794         if (FL->getValue().convertToInteger(IgnoredVal,
14795                                             llvm::APFloat::rmTowardZero,
14796                                             &Ignored) & APFloat::opInvalidOp)
14797           return ICEDiag(IK_NotICE, E->getBeginLoc());
14798         return NoDiag();
14799       }
14800     }
14801     switch (cast<CastExpr>(E)->getCastKind()) {
14802     case CK_LValueToRValue:
14803     case CK_AtomicToNonAtomic:
14804     case CK_NonAtomicToAtomic:
14805     case CK_NoOp:
14806     case CK_IntegralToBoolean:
14807     case CK_IntegralCast:
14808       return CheckICE(SubExpr, Ctx);
14809     default:
14810       return ICEDiag(IK_NotICE, E->getBeginLoc());
14811     }
14812   }
14813   case Expr::BinaryConditionalOperatorClass: {
14814     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14815     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14816     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14817     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14818     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14819     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14820     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14821         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14822     return FalseResult;
14823   }
14824   case Expr::ConditionalOperatorClass: {
14825     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14826     // If the condition (ignoring parens) is a __builtin_constant_p call,
14827     // then only the true side is actually considered in an integer constant
14828     // expression, and it is fully evaluated.  This is an important GNU
14829     // extension.  See GCC PR38377 for discussion.
14830     if (const CallExpr *CallCE
14831         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14832       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14833         return CheckEvalInICE(E, Ctx);
14834     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14835     if (CondResult.Kind == IK_NotICE)
14836       return CondResult;
14837 
14838     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14839     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14840 
14841     if (TrueResult.Kind == IK_NotICE)
14842       return TrueResult;
14843     if (FalseResult.Kind == IK_NotICE)
14844       return FalseResult;
14845     if (CondResult.Kind == IK_ICEIfUnevaluated)
14846       return CondResult;
14847     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14848       return NoDiag();
14849     // Rare case where the diagnostics depend on which side is evaluated
14850     // Note that if we get here, CondResult is 0, and at least one of
14851     // TrueResult and FalseResult is non-zero.
14852     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14853       return FalseResult;
14854     return TrueResult;
14855   }
14856   case Expr::CXXDefaultArgExprClass:
14857     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14858   case Expr::CXXDefaultInitExprClass:
14859     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14860   case Expr::ChooseExprClass: {
14861     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14862   }
14863   case Expr::BuiltinBitCastExprClass: {
14864     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14865       return ICEDiag(IK_NotICE, E->getBeginLoc());
14866     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14867   }
14868   }
14869 
14870   llvm_unreachable("Invalid StmtClass!");
14871 }
14872 
14873 /// Evaluate an expression as a C++11 integral constant expression.
14874 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14875                                                     const Expr *E,
14876                                                     llvm::APSInt *Value,
14877                                                     SourceLocation *Loc) {
14878   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14879     if (Loc) *Loc = E->getExprLoc();
14880     return false;
14881   }
14882 
14883   APValue Result;
14884   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14885     return false;
14886 
14887   if (!Result.isInt()) {
14888     if (Loc) *Loc = E->getExprLoc();
14889     return false;
14890   }
14891 
14892   if (Value) *Value = Result.getInt();
14893   return true;
14894 }
14895 
14896 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14897                                  SourceLocation *Loc) const {
14898   assert(!isValueDependent() &&
14899          "Expression evaluator can't be called on a dependent expression.");
14900 
14901   if (Ctx.getLangOpts().CPlusPlus11)
14902     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14903 
14904   ICEDiag D = CheckICE(this, Ctx);
14905   if (D.Kind != IK_ICE) {
14906     if (Loc) *Loc = D.Loc;
14907     return false;
14908   }
14909   return true;
14910 }
14911 
14912 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14913                                  SourceLocation *Loc, bool isEvaluated) const {
14914   assert(!isValueDependent() &&
14915          "Expression evaluator can't be called on a dependent expression.");
14916 
14917   if (Ctx.getLangOpts().CPlusPlus11)
14918     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14919 
14920   if (!isIntegerConstantExpr(Ctx, Loc))
14921     return false;
14922 
14923   // The only possible side-effects here are due to UB discovered in the
14924   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14925   // required to treat the expression as an ICE, so we produce the folded
14926   // value.
14927   EvalResult ExprResult;
14928   Expr::EvalStatus Status;
14929   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14930   Info.InConstantContext = true;
14931 
14932   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14933     llvm_unreachable("ICE cannot be evaluated!");
14934 
14935   Value = ExprResult.Val.getInt();
14936   return true;
14937 }
14938 
14939 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14940   assert(!isValueDependent() &&
14941          "Expression evaluator can't be called on a dependent expression.");
14942 
14943   return CheckICE(this, Ctx).Kind == IK_ICE;
14944 }
14945 
14946 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14947                                SourceLocation *Loc) const {
14948   assert(!isValueDependent() &&
14949          "Expression evaluator can't be called on a dependent expression.");
14950 
14951   // We support this checking in C++98 mode in order to diagnose compatibility
14952   // issues.
14953   assert(Ctx.getLangOpts().CPlusPlus);
14954 
14955   // Build evaluation settings.
14956   Expr::EvalStatus Status;
14957   SmallVector<PartialDiagnosticAt, 8> Diags;
14958   Status.Diag = &Diags;
14959   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14960 
14961   APValue Scratch;
14962   bool IsConstExpr =
14963       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14964       // FIXME: We don't produce a diagnostic for this, but the callers that
14965       // call us on arbitrary full-expressions should generally not care.
14966       Info.discardCleanups() && !Status.HasSideEffects;
14967 
14968   if (!Diags.empty()) {
14969     IsConstExpr = false;
14970     if (Loc) *Loc = Diags[0].first;
14971   } else if (!IsConstExpr) {
14972     // FIXME: This shouldn't happen.
14973     if (Loc) *Loc = getExprLoc();
14974   }
14975 
14976   return IsConstExpr;
14977 }
14978 
14979 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14980                                     const FunctionDecl *Callee,
14981                                     ArrayRef<const Expr*> Args,
14982                                     const Expr *This) const {
14983   assert(!isValueDependent() &&
14984          "Expression evaluator can't be called on a dependent expression.");
14985 
14986   Expr::EvalStatus Status;
14987   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14988   Info.InConstantContext = true;
14989 
14990   LValue ThisVal;
14991   const LValue *ThisPtr = nullptr;
14992   if (This) {
14993 #ifndef NDEBUG
14994     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14995     assert(MD && "Don't provide `this` for non-methods.");
14996     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14997 #endif
14998     if (!This->isValueDependent() &&
14999         EvaluateObjectArgument(Info, This, ThisVal) &&
15000         !Info.EvalStatus.HasSideEffects)
15001       ThisPtr = &ThisVal;
15002 
15003     // Ignore any side-effects from a failed evaluation. This is safe because
15004     // they can't interfere with any other argument evaluation.
15005     Info.EvalStatus.HasSideEffects = false;
15006   }
15007 
15008   ArgVector ArgValues(Args.size());
15009   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15010        I != E; ++I) {
15011     if ((*I)->isValueDependent() ||
15012         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
15013         Info.EvalStatus.HasSideEffects)
15014       // If evaluation fails, throw away the argument entirely.
15015       ArgValues[I - Args.begin()] = APValue();
15016 
15017     // Ignore any side-effects from a failed evaluation. This is safe because
15018     // they can't interfere with any other argument evaluation.
15019     Info.EvalStatus.HasSideEffects = false;
15020   }
15021 
15022   // Parameter cleanups happen in the caller and are not part of this
15023   // evaluation.
15024   Info.discardCleanups();
15025   Info.EvalStatus.HasSideEffects = false;
15026 
15027   // Build fake call to Callee.
15028   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
15029                        ArgValues.data());
15030   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15031   FullExpressionRAII Scope(Info);
15032   return Evaluate(Value, Info, this) && Scope.destroy() &&
15033          !Info.EvalStatus.HasSideEffects;
15034 }
15035 
15036 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15037                                    SmallVectorImpl<
15038                                      PartialDiagnosticAt> &Diags) {
15039   // FIXME: It would be useful to check constexpr function templates, but at the
15040   // moment the constant expression evaluator cannot cope with the non-rigorous
15041   // ASTs which we build for dependent expressions.
15042   if (FD->isDependentContext())
15043     return true;
15044 
15045   // Bail out if a constexpr constructor has an initializer that contains an
15046   // error. We deliberately don't produce a diagnostic, as we have produced a
15047   // relevant diagnostic when parsing the error initializer.
15048   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15049     for (const auto *InitExpr : Ctor->inits()) {
15050       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
15051         return false;
15052     }
15053   }
15054   Expr::EvalStatus Status;
15055   Status.Diag = &Diags;
15056 
15057   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15058   Info.InConstantContext = true;
15059   Info.CheckingPotentialConstantExpression = true;
15060 
15061   // The constexpr VM attempts to compile all methods to bytecode here.
15062   if (Info.EnableNewConstInterp) {
15063     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15064     return Diags.empty();
15065   }
15066 
15067   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15068   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15069 
15070   // Fabricate an arbitrary expression on the stack and pretend that it
15071   // is a temporary being used as the 'this' pointer.
15072   LValue This;
15073   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15074   This.set({&VIE, Info.CurrentCall->Index});
15075 
15076   ArrayRef<const Expr*> Args;
15077 
15078   APValue Scratch;
15079   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15080     // Evaluate the call as a constant initializer, to allow the construction
15081     // of objects of non-literal types.
15082     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15083     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15084   } else {
15085     SourceLocation Loc = FD->getLocation();
15086     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15087                        Args, FD->getBody(), Info, Scratch, nullptr);
15088   }
15089 
15090   return Diags.empty();
15091 }
15092 
15093 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15094                                               const FunctionDecl *FD,
15095                                               SmallVectorImpl<
15096                                                 PartialDiagnosticAt> &Diags) {
15097   assert(!E->isValueDependent() &&
15098          "Expression evaluator can't be called on a dependent expression.");
15099 
15100   Expr::EvalStatus Status;
15101   Status.Diag = &Diags;
15102 
15103   EvalInfo Info(FD->getASTContext(), Status,
15104                 EvalInfo::EM_ConstantExpressionUnevaluated);
15105   Info.InConstantContext = true;
15106   Info.CheckingPotentialConstantExpression = true;
15107 
15108   // Fabricate a call stack frame to give the arguments a plausible cover story.
15109   ArrayRef<const Expr*> Args;
15110   ArgVector ArgValues(0);
15111   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
15112   (void)Success;
15113   assert(Success &&
15114          "Failed to set up arguments for potential constant evaluation");
15115   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
15116 
15117   APValue ResultScratch;
15118   Evaluate(ResultScratch, Info, E);
15119   return Diags.empty();
15120 }
15121 
15122 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15123                                  unsigned Type) const {
15124   if (!getType()->isPointerType())
15125     return false;
15126 
15127   Expr::EvalStatus Status;
15128   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15129   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15130 }
15131