xref: /freebsd/contrib/llvm-project/clang/lib/AST/ExprConstant.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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/DiagnosticSema.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "llvm/ADT/APFixedPoint.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/ADT/StringExtras.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/SaveAndRestore.h"
60 #include "llvm/Support/TimeProfiler.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include <cstring>
63 #include <functional>
64 #include <optional>
65 
66 #define DEBUG_TYPE "exprconstant"
67 
68 using namespace clang;
69 using llvm::APFixedPoint;
70 using llvm::APInt;
71 using llvm::APSInt;
72 using llvm::APFloat;
73 using llvm::FixedPointSemantics;
74 
75 namespace {
76   struct LValue;
77   class CallStackFrame;
78   class EvalInfo;
79 
80   using SourceLocExprScopeGuard =
81       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
82 
83   static QualType getType(APValue::LValueBase B) {
84     return B.getType();
85   }
86 
87   /// Get an LValue path entry, which is known to not be an array index, as a
88   /// field declaration.
89   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
90     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
91   }
92   /// Get an LValue path entry, which is known to not be an array index, as a
93   /// base class declaration.
94   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
95     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
96   }
97   /// Determine whether this LValue path entry for a base class names a virtual
98   /// base class.
99   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
100     return E.getAsBaseOrMember().getInt();
101   }
102 
103   /// Given an expression, determine the type used to store the result of
104   /// evaluating that expression.
105   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
106     if (E->isPRValue())
107       return E->getType();
108     return Ctx.getLValueReferenceType(E->getType());
109   }
110 
111   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
112   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
113     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
114       return DirectCallee->getAttr<AllocSizeAttr>();
115     if (const Decl *IndirectCallee = CE->getCalleeDecl())
116       return IndirectCallee->getAttr<AllocSizeAttr>();
117     return nullptr;
118   }
119 
120   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
121   /// This will look through a single cast.
122   ///
123   /// Returns null if we couldn't unwrap a function with alloc_size.
124   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
125     if (!E->getType()->isPointerType())
126       return nullptr;
127 
128     E = E->IgnoreParens();
129     // If we're doing a variable assignment from e.g. malloc(N), there will
130     // probably be a cast of some kind. In exotic cases, we might also see a
131     // top-level ExprWithCleanups. Ignore them either way.
132     if (const auto *FE = dyn_cast<FullExpr>(E))
133       E = FE->getSubExpr()->IgnoreParens();
134 
135     if (const auto *Cast = dyn_cast<CastExpr>(E))
136       E = Cast->getSubExpr()->IgnoreParens();
137 
138     if (const auto *CE = dyn_cast<CallExpr>(E))
139       return getAllocSizeAttr(CE) ? CE : nullptr;
140     return nullptr;
141   }
142 
143   /// Determines whether or not the given Base contains a call to a function
144   /// with the alloc_size attribute.
145   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
146     const auto *E = Base.dyn_cast<const Expr *>();
147     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
148   }
149 
150   /// Determines whether the given kind of constant expression is only ever
151   /// used for name mangling. If so, it's permitted to reference things that we
152   /// can't generate code for (in particular, dllimported functions).
153   static bool isForManglingOnly(ConstantExprKind Kind) {
154     switch (Kind) {
155     case ConstantExprKind::Normal:
156     case ConstantExprKind::ClassTemplateArgument:
157     case ConstantExprKind::ImmediateInvocation:
158       // Note that non-type template arguments of class type are emitted as
159       // template parameter objects.
160       return false;
161 
162     case ConstantExprKind::NonClassTemplateArgument:
163       return true;
164     }
165     llvm_unreachable("unknown ConstantExprKind");
166   }
167 
168   static bool isTemplateArgument(ConstantExprKind Kind) {
169     switch (Kind) {
170     case ConstantExprKind::Normal:
171     case ConstantExprKind::ImmediateInvocation:
172       return false;
173 
174     case ConstantExprKind::ClassTemplateArgument:
175     case ConstantExprKind::NonClassTemplateArgument:
176       return true;
177     }
178     llvm_unreachable("unknown ConstantExprKind");
179   }
180 
181   /// The bound to claim that an array of unknown bound has.
182   /// The value in MostDerivedArraySize is undefined in this case. So, set it
183   /// to an arbitrary value that's likely to loudly break things if it's used.
184   static const uint64_t AssumedSizeForUnsizedArray =
185       std::numeric_limits<uint64_t>::max() / 2;
186 
187   /// Determines if an LValue with the given LValueBase will have an unsized
188   /// array in its designator.
189   /// Find the path length and type of the most-derived subobject in the given
190   /// path, and find the size of the containing array, if any.
191   static unsigned
192   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
193                            ArrayRef<APValue::LValuePathEntry> Path,
194                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
195                            bool &FirstEntryIsUnsizedArray) {
196     // This only accepts LValueBases from APValues, and APValues don't support
197     // arrays that lack size info.
198     assert(!isBaseAnAllocSizeCall(Base) &&
199            "Unsized arrays shouldn't appear here");
200     unsigned MostDerivedLength = 0;
201     Type = getType(Base);
202 
203     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
204       if (Type->isArrayType()) {
205         const ArrayType *AT = Ctx.getAsArrayType(Type);
206         Type = AT->getElementType();
207         MostDerivedLength = I + 1;
208         IsArray = true;
209 
210         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
211           ArraySize = CAT->getSize().getZExtValue();
212         } else {
213           assert(I == 0 && "unexpected unsized array designator");
214           FirstEntryIsUnsizedArray = true;
215           ArraySize = AssumedSizeForUnsizedArray;
216         }
217       } else if (Type->isAnyComplexType()) {
218         const ComplexType *CT = Type->castAs<ComplexType>();
219         Type = CT->getElementType();
220         ArraySize = 2;
221         MostDerivedLength = I + 1;
222         IsArray = true;
223       } else if (const FieldDecl *FD = getAsField(Path[I])) {
224         Type = FD->getType();
225         ArraySize = 0;
226         MostDerivedLength = I + 1;
227         IsArray = false;
228       } else {
229         // Path[I] describes a base class.
230         ArraySize = 0;
231         IsArray = false;
232       }
233     }
234     return MostDerivedLength;
235   }
236 
237   /// A path from a glvalue to a subobject of that glvalue.
238   struct SubobjectDesignator {
239     /// True if the subobject was named in a manner not supported by C++11. Such
240     /// lvalues can still be folded, but they are not core constant expressions
241     /// and we cannot perform lvalue-to-rvalue conversions on them.
242     unsigned Invalid : 1;
243 
244     /// Is this a pointer one past the end of an object?
245     unsigned IsOnePastTheEnd : 1;
246 
247     /// Indicator of whether the first entry is an unsized array.
248     unsigned FirstEntryIsAnUnsizedArray : 1;
249 
250     /// Indicator of whether the most-derived object is an array element.
251     unsigned MostDerivedIsArrayElement : 1;
252 
253     /// The length of the path to the most-derived object of which this is a
254     /// subobject.
255     unsigned MostDerivedPathLength : 28;
256 
257     /// The size of the array of which the most-derived object is an element.
258     /// This will always be 0 if the most-derived object is not an array
259     /// element. 0 is not an indicator of whether or not the most-derived object
260     /// is an array, however, because 0-length arrays are allowed.
261     ///
262     /// If the current array is an unsized array, the value of this is
263     /// undefined.
264     uint64_t MostDerivedArraySize;
265 
266     /// The type of the most derived object referred to by this address.
267     QualType MostDerivedType;
268 
269     typedef APValue::LValuePathEntry PathEntry;
270 
271     /// The entries on the path from the glvalue to the designated subobject.
272     SmallVector<PathEntry, 8> Entries;
273 
274     SubobjectDesignator() : Invalid(true) {}
275 
276     explicit SubobjectDesignator(QualType T)
277         : Invalid(false), IsOnePastTheEnd(false),
278           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
279           MostDerivedPathLength(0), MostDerivedArraySize(0),
280           MostDerivedType(T) {}
281 
282     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
283         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
284           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
285           MostDerivedPathLength(0), MostDerivedArraySize(0) {
286       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
287       if (!Invalid) {
288         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
289         ArrayRef<PathEntry> VEntries = V.getLValuePath();
290         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
291         if (V.getLValueBase()) {
292           bool IsArray = false;
293           bool FirstIsUnsizedArray = false;
294           MostDerivedPathLength = findMostDerivedSubobject(
295               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
296               MostDerivedType, IsArray, FirstIsUnsizedArray);
297           MostDerivedIsArrayElement = IsArray;
298           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
299         }
300       }
301     }
302 
303     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
304                   unsigned NewLength) {
305       if (Invalid)
306         return;
307 
308       assert(Base && "cannot truncate path for null pointer");
309       assert(NewLength <= Entries.size() && "not a truncation");
310 
311       if (NewLength == Entries.size())
312         return;
313       Entries.resize(NewLength);
314 
315       bool IsArray = false;
316       bool FirstIsUnsizedArray = false;
317       MostDerivedPathLength = findMostDerivedSubobject(
318           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
319           FirstIsUnsizedArray);
320       MostDerivedIsArrayElement = IsArray;
321       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
322     }
323 
324     void setInvalid() {
325       Invalid = true;
326       Entries.clear();
327     }
328 
329     /// Determine whether the most derived subobject is an array without a
330     /// known bound.
331     bool isMostDerivedAnUnsizedArray() const {
332       assert(!Invalid && "Calling this makes no sense on invalid designators");
333       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
334     }
335 
336     /// Determine what the most derived array's size is. Results in an assertion
337     /// failure if the most derived array lacks a size.
338     uint64_t getMostDerivedArraySize() const {
339       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
340       return MostDerivedArraySize;
341     }
342 
343     /// Determine whether this is a one-past-the-end pointer.
344     bool isOnePastTheEnd() const {
345       assert(!Invalid);
346       if (IsOnePastTheEnd)
347         return true;
348       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
349           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
350               MostDerivedArraySize)
351         return true;
352       return false;
353     }
354 
355     /// Get the range of valid index adjustments in the form
356     ///   {maximum value that can be subtracted from this pointer,
357     ///    maximum value that can be added to this pointer}
358     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
359       if (Invalid || isMostDerivedAnUnsizedArray())
360         return {0, 0};
361 
362       // [expr.add]p4: For the purposes of these operators, a pointer to a
363       // nonarray object behaves the same as a pointer to the first element of
364       // an array of length one with the type of the object as its element type.
365       bool IsArray = MostDerivedPathLength == Entries.size() &&
366                      MostDerivedIsArrayElement;
367       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
368                                     : (uint64_t)IsOnePastTheEnd;
369       uint64_t ArraySize =
370           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
371       return {ArrayIndex, ArraySize - ArrayIndex};
372     }
373 
374     /// Check that this refers to a valid subobject.
375     bool isValidSubobject() const {
376       if (Invalid)
377         return false;
378       return !isOnePastTheEnd();
379     }
380     /// Check that this refers to a valid subobject, and if not, produce a
381     /// relevant diagnostic and set the designator as invalid.
382     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
383 
384     /// Get the type of the designated object.
385     QualType getType(ASTContext &Ctx) const {
386       assert(!Invalid && "invalid designator has no subobject type");
387       return MostDerivedPathLength == Entries.size()
388                  ? MostDerivedType
389                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
390     }
391 
392     /// Update this designator to refer to the first element within this array.
393     void addArrayUnchecked(const ConstantArrayType *CAT) {
394       Entries.push_back(PathEntry::ArrayIndex(0));
395 
396       // This is a most-derived object.
397       MostDerivedType = CAT->getElementType();
398       MostDerivedIsArrayElement = true;
399       MostDerivedArraySize = CAT->getSize().getZExtValue();
400       MostDerivedPathLength = Entries.size();
401     }
402     /// Update this designator to refer to the first element within the array of
403     /// elements of type T. This is an array of unknown size.
404     void addUnsizedArrayUnchecked(QualType ElemTy) {
405       Entries.push_back(PathEntry::ArrayIndex(0));
406 
407       MostDerivedType = ElemTy;
408       MostDerivedIsArrayElement = true;
409       // The value in MostDerivedArraySize is undefined in this case. So, set it
410       // to an arbitrary value that's likely to loudly break things if it's
411       // used.
412       MostDerivedArraySize = AssumedSizeForUnsizedArray;
413       MostDerivedPathLength = Entries.size();
414     }
415     /// Update this designator to refer to the given base or member of this
416     /// object.
417     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
418       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
419 
420       // If this isn't a base class, it's a new most-derived object.
421       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
422         MostDerivedType = FD->getType();
423         MostDerivedIsArrayElement = false;
424         MostDerivedArraySize = 0;
425         MostDerivedPathLength = Entries.size();
426       }
427     }
428     /// Update this designator to refer to the given complex component.
429     void addComplexUnchecked(QualType EltTy, bool Imag) {
430       Entries.push_back(PathEntry::ArrayIndex(Imag));
431 
432       // This is technically a most-derived object, though in practice this
433       // is unlikely to matter.
434       MostDerivedType = EltTy;
435       MostDerivedIsArrayElement = true;
436       MostDerivedArraySize = 2;
437       MostDerivedPathLength = Entries.size();
438     }
439     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
440     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
441                                    const APSInt &N);
442     /// Add N to the address of this subobject.
443     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
444       if (Invalid || !N) return;
445       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
446       if (isMostDerivedAnUnsizedArray()) {
447         diagnoseUnsizedArrayPointerArithmetic(Info, E);
448         // Can't verify -- trust that the user is doing the right thing (or if
449         // not, trust that the caller will catch the bad behavior).
450         // FIXME: Should we reject if this overflows, at least?
451         Entries.back() = PathEntry::ArrayIndex(
452             Entries.back().getAsArrayIndex() + TruncatedN);
453         return;
454       }
455 
456       // [expr.add]p4: For the purposes of these operators, a pointer to a
457       // nonarray object behaves the same as a pointer to the first element of
458       // an array of length one with the type of the object as its element type.
459       bool IsArray = MostDerivedPathLength == Entries.size() &&
460                      MostDerivedIsArrayElement;
461       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
462                                     : (uint64_t)IsOnePastTheEnd;
463       uint64_t ArraySize =
464           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
465 
466       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
467         // Calculate the actual index in a wide enough type, so we can include
468         // it in the note.
469         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
470         (llvm::APInt&)N += ArrayIndex;
471         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
472         diagnosePointerArithmetic(Info, E, N);
473         setInvalid();
474         return;
475       }
476 
477       ArrayIndex += TruncatedN;
478       assert(ArrayIndex <= ArraySize &&
479              "bounds check succeeded for out-of-bounds index");
480 
481       if (IsArray)
482         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
483       else
484         IsOnePastTheEnd = (ArrayIndex != 0);
485     }
486   };
487 
488   /// A scope at the end of which an object can need to be destroyed.
489   enum class ScopeKind {
490     Block,
491     FullExpression,
492     Call
493   };
494 
495   /// A reference to a particular call and its arguments.
496   struct CallRef {
497     CallRef() : OrigCallee(), CallIndex(0), Version() {}
498     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
499         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
500 
501     explicit operator bool() const { return OrigCallee; }
502 
503     /// Get the parameter that the caller initialized, corresponding to the
504     /// given parameter in the callee.
505     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
506       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
507                         : PVD;
508     }
509 
510     /// The callee at the point where the arguments were evaluated. This might
511     /// be different from the actual callee (a different redeclaration, or a
512     /// virtual override), but this function's parameters are the ones that
513     /// appear in the parameter map.
514     const FunctionDecl *OrigCallee;
515     /// The call index of the frame that holds the argument values.
516     unsigned CallIndex;
517     /// The version of the parameters corresponding to this call.
518     unsigned Version;
519   };
520 
521   /// A stack frame in the constexpr call stack.
522   class CallStackFrame : public interp::Frame {
523   public:
524     EvalInfo &Info;
525 
526     /// Parent - The caller of this stack frame.
527     CallStackFrame *Caller;
528 
529     /// Callee - The function which was called.
530     const FunctionDecl *Callee;
531 
532     /// This - The binding for the this pointer in this call, if any.
533     const LValue *This;
534 
535     /// CallExpr - The syntactical structure of member function calls
536     const Expr *CallExpr;
537 
538     /// Information on how to find the arguments to this call. Our arguments
539     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
540     /// key and this value as the version.
541     CallRef Arguments;
542 
543     /// Source location information about the default argument or default
544     /// initializer expression we're evaluating, if any.
545     CurrentSourceLocExprScope CurSourceLocExprScope;
546 
547     // Note that we intentionally use std::map here so that references to
548     // values are stable.
549     typedef std::pair<const void *, unsigned> MapKeyTy;
550     typedef std::map<MapKeyTy, APValue> MapTy;
551     /// Temporaries - Temporary lvalues materialized within this stack frame.
552     MapTy Temporaries;
553 
554     /// CallLoc - The location of the call expression for this call.
555     SourceLocation CallLoc;
556 
557     /// Index - The call index of this call.
558     unsigned Index;
559 
560     /// The stack of integers for tracking version numbers for temporaries.
561     SmallVector<unsigned, 2> TempVersionStack = {1};
562     unsigned CurTempVersion = TempVersionStack.back();
563 
564     unsigned getTempVersion() const { return TempVersionStack.back(); }
565 
566     void pushTempVersion() {
567       TempVersionStack.push_back(++CurTempVersion);
568     }
569 
570     void popTempVersion() {
571       TempVersionStack.pop_back();
572     }
573 
574     CallRef createCall(const FunctionDecl *Callee) {
575       return {Callee, Index, ++CurTempVersion};
576     }
577 
578     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
579     // on the overall stack usage of deeply-recursing constexpr evaluations.
580     // (We should cache this map rather than recomputing it repeatedly.)
581     // But let's try this and see how it goes; we can look into caching the map
582     // as a later change.
583 
584     /// LambdaCaptureFields - Mapping from captured variables/this to
585     /// corresponding data members in the closure class.
586     llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
587     FieldDecl *LambdaThisCaptureField = nullptr;
588 
589     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
590                    const FunctionDecl *Callee, const LValue *This,
591                    const Expr *CallExpr, CallRef Arguments);
592     ~CallStackFrame();
593 
594     // Return the temporary for Key whose version number is Version.
595     APValue *getTemporary(const void *Key, unsigned Version) {
596       MapKeyTy KV(Key, Version);
597       auto LB = Temporaries.lower_bound(KV);
598       if (LB != Temporaries.end() && LB->first == KV)
599         return &LB->second;
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) const override;
631 
632     Frame *getCaller() const override { return Caller; }
633     SourceLocation getCallLocation() const override { return CallLoc; }
634     const FunctionDecl *getCallee() const override { return Callee; }
635 
636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 
664   // A shorthand time trace scope struct, prints source range, for example
665   // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
666   class ExprTimeTraceScope {
667   public:
668     ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
669         : TimeScope(Name, [E, &Ctx] {
670             return E->getSourceRange().printToString(Ctx.getSourceManager());
671           }) {}
672 
673   private:
674     llvm::TimeTraceScope TimeScope;
675   };
676 }
677 
678 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
679                               const LValue &This, QualType ThisType);
680 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
681                               APValue::LValueBase LVBase, APValue &Value,
682                               QualType T);
683 
684 namespace {
685   /// A cleanup, and a flag indicating whether it is lifetime-extended.
686   class Cleanup {
687     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
688     APValue::LValueBase Base;
689     QualType T;
690 
691   public:
692     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
693             ScopeKind Scope)
694         : Value(Val, Scope), Base(Base), T(T) {}
695 
696     /// Determine whether this cleanup should be performed at the end of the
697     /// given kind of scope.
698     bool isDestroyedAtEndOf(ScopeKind K) const {
699       return (int)Value.getInt() >= (int)K;
700     }
701     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
702       if (RunDestructors) {
703         SourceLocation Loc;
704         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
705           Loc = VD->getLocation();
706         else if (const Expr *E = Base.dyn_cast<const Expr*>())
707           Loc = E->getExprLoc();
708         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
709       }
710       *Value.getPointer() = APValue();
711       return true;
712     }
713 
714     bool hasSideEffect() {
715       return T.isDestructedType();
716     }
717   };
718 
719   /// A reference to an object whose construction we are currently evaluating.
720   struct ObjectUnderConstruction {
721     APValue::LValueBase Base;
722     ArrayRef<APValue::LValuePathEntry> Path;
723     friend bool operator==(const ObjectUnderConstruction &LHS,
724                            const ObjectUnderConstruction &RHS) {
725       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
726     }
727     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
728       return llvm::hash_combine(Obj.Base, Obj.Path);
729     }
730   };
731   enum class ConstructionPhase {
732     None,
733     Bases,
734     AfterBases,
735     AfterFields,
736     Destroying,
737     DestroyingBases
738   };
739 }
740 
741 namespace llvm {
742 template<> struct DenseMapInfo<ObjectUnderConstruction> {
743   using Base = DenseMapInfo<APValue::LValueBase>;
744   static ObjectUnderConstruction getEmptyKey() {
745     return {Base::getEmptyKey(), {}}; }
746   static ObjectUnderConstruction getTombstoneKey() {
747     return {Base::getTombstoneKey(), {}};
748   }
749   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
750     return hash_value(Object);
751   }
752   static bool isEqual(const ObjectUnderConstruction &LHS,
753                       const ObjectUnderConstruction &RHS) {
754     return LHS == RHS;
755   }
756 };
757 }
758 
759 namespace {
760   /// A dynamically-allocated heap object.
761   struct DynAlloc {
762     /// The value of this heap-allocated object.
763     APValue Value;
764     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
765     /// or a CallExpr (the latter is for direct calls to operator new inside
766     /// std::allocator<T>::allocate).
767     const Expr *AllocExpr = nullptr;
768 
769     enum Kind {
770       New,
771       ArrayNew,
772       StdAllocator
773     };
774 
775     /// Get the kind of the allocation. This must match between allocation
776     /// and deallocation.
777     Kind getKind() const {
778       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
779         return NE->isArray() ? ArrayNew : New;
780       assert(isa<CallExpr>(AllocExpr));
781       return StdAllocator;
782     }
783   };
784 
785   struct DynAllocOrder {
786     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
787       return L.getIndex() < R.getIndex();
788     }
789   };
790 
791   /// EvalInfo - This is a private struct used by the evaluator to capture
792   /// information about a subexpression as it is folded.  It retains information
793   /// about the AST context, but also maintains information about the folded
794   /// expression.
795   ///
796   /// If an expression could be evaluated, it is still possible it is not a C
797   /// "integer constant expression" or constant expression.  If not, this struct
798   /// captures information about how and why not.
799   ///
800   /// One bit of information passed *into* the request for constant folding
801   /// indicates whether the subexpression is "evaluated" or not according to C
802   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
803   /// evaluate the expression regardless of what the RHS is, but C only allows
804   /// certain things in certain situations.
805   class EvalInfo : public interp::State {
806   public:
807     ASTContext &Ctx;
808 
809     /// EvalStatus - Contains information about the evaluation.
810     Expr::EvalStatus &EvalStatus;
811 
812     /// CurrentCall - The top of the constexpr call stack.
813     CallStackFrame *CurrentCall;
814 
815     /// CallStackDepth - The number of calls in the call stack right now.
816     unsigned CallStackDepth;
817 
818     /// NextCallIndex - The next call index to assign.
819     unsigned NextCallIndex;
820 
821     /// StepsLeft - The remaining number of evaluation steps we're permitted
822     /// to perform. This is essentially a limit for the number of statements
823     /// we will evaluate.
824     unsigned StepsLeft;
825 
826     /// Enable the experimental new constant interpreter. If an expression is
827     /// not supported by the interpreter, an error is triggered.
828     bool EnableNewConstInterp;
829 
830     /// BottomFrame - The frame in which evaluation started. This must be
831     /// initialized after CurrentCall and CallStackDepth.
832     CallStackFrame BottomFrame;
833 
834     /// A stack of values whose lifetimes end at the end of some surrounding
835     /// evaluation frame.
836     llvm::SmallVector<Cleanup, 16> CleanupStack;
837 
838     /// EvaluatingDecl - This is the declaration whose initializer is being
839     /// evaluated, if any.
840     APValue::LValueBase EvaluatingDecl;
841 
842     enum class EvaluatingDeclKind {
843       None,
844       /// We're evaluating the construction of EvaluatingDecl.
845       Ctor,
846       /// We're evaluating the destruction of EvaluatingDecl.
847       Dtor,
848     };
849     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
850 
851     /// EvaluatingDeclValue - This is the value being constructed for the
852     /// declaration whose initializer is being evaluated, if any.
853     APValue *EvaluatingDeclValue;
854 
855     /// Set of objects that are currently being constructed.
856     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
857         ObjectsUnderConstruction;
858 
859     /// Current heap allocations, along with the location where each was
860     /// allocated. We use std::map here because we need stable addresses
861     /// for the stored APValues.
862     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
863 
864     /// The number of heap allocations performed so far in this evaluation.
865     unsigned NumHeapAllocs = 0;
866 
867     struct EvaluatingConstructorRAII {
868       EvalInfo &EI;
869       ObjectUnderConstruction Object;
870       bool DidInsert;
871       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
872                                 bool HasBases)
873           : EI(EI), Object(Object) {
874         DidInsert =
875             EI.ObjectsUnderConstruction
876                 .insert({Object, HasBases ? ConstructionPhase::Bases
877                                           : ConstructionPhase::AfterBases})
878                 .second;
879       }
880       void finishedConstructingBases() {
881         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
882       }
883       void finishedConstructingFields() {
884         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
885       }
886       ~EvaluatingConstructorRAII() {
887         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
888       }
889     };
890 
891     struct EvaluatingDestructorRAII {
892       EvalInfo &EI;
893       ObjectUnderConstruction Object;
894       bool DidInsert;
895       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
896           : EI(EI), Object(Object) {
897         DidInsert = EI.ObjectsUnderConstruction
898                         .insert({Object, ConstructionPhase::Destroying})
899                         .second;
900       }
901       void startedDestroyingBases() {
902         EI.ObjectsUnderConstruction[Object] =
903             ConstructionPhase::DestroyingBases;
904       }
905       ~EvaluatingDestructorRAII() {
906         if (DidInsert)
907           EI.ObjectsUnderConstruction.erase(Object);
908       }
909     };
910 
911     ConstructionPhase
912     isEvaluatingCtorDtor(APValue::LValueBase Base,
913                          ArrayRef<APValue::LValuePathEntry> Path) {
914       return ObjectsUnderConstruction.lookup({Base, Path});
915     }
916 
917     /// If we're currently speculatively evaluating, the outermost call stack
918     /// depth at which we can mutate state, otherwise 0.
919     unsigned SpeculativeEvaluationDepth = 0;
920 
921     /// The current array initialization index, if we're performing array
922     /// initialization.
923     uint64_t ArrayInitIndex = -1;
924 
925     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
926     /// notes attached to it will also be stored, otherwise they will not be.
927     bool HasActiveDiagnostic;
928 
929     /// Have we emitted a diagnostic explaining why we couldn't constant
930     /// fold (not just why it's not strictly a constant expression)?
931     bool HasFoldFailureDiagnostic;
932 
933     /// Whether we're checking that an expression is a potential constant
934     /// expression. If so, do not fail on constructs that could become constant
935     /// later on (such as a use of an undefined global).
936     bool CheckingPotentialConstantExpression = false;
937 
938     /// Whether we're checking for an expression that has undefined behavior.
939     /// If so, we will produce warnings if we encounter an operation that is
940     /// always undefined.
941     ///
942     /// Note that we still need to evaluate the expression normally when this
943     /// is set; this is used when evaluating ICEs in C.
944     bool CheckingForUndefinedBehavior = false;
945 
946     enum EvaluationMode {
947       /// Evaluate as a constant expression. Stop if we find that the expression
948       /// is not a constant expression.
949       EM_ConstantExpression,
950 
951       /// Evaluate as a constant expression. Stop if we find that the expression
952       /// is not a constant expression. Some expressions can be retried in the
953       /// optimizer if we don't constant fold them here, but in an unevaluated
954       /// context we try to fold them immediately since the optimizer never
955       /// gets a chance to look at it.
956       EM_ConstantExpressionUnevaluated,
957 
958       /// Fold the expression to a constant. Stop if we hit a side-effect that
959       /// we can't model.
960       EM_ConstantFold,
961 
962       /// Evaluate in any way we know how. Don't worry about side-effects that
963       /// can't be modeled.
964       EM_IgnoreSideEffects,
965     } EvalMode;
966 
967     /// Are we checking whether the expression is a potential constant
968     /// expression?
969     bool checkingPotentialConstantExpression() const override  {
970       return CheckingPotentialConstantExpression;
971     }
972 
973     /// Are we checking an expression for overflow?
974     // FIXME: We should check for any kind of undefined or suspicious behavior
975     // in such constructs, not just overflow.
976     bool checkingForUndefinedBehavior() const override {
977       return CheckingForUndefinedBehavior;
978     }
979 
980     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
981         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
982           CallStackDepth(0), NextCallIndex(1),
983           StepsLeft(C.getLangOpts().ConstexprStepLimit),
984           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
985           BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
986                       /*This=*/nullptr,
987                       /*CallExpr=*/nullptr, CallRef()),
988           EvaluatingDecl((const ValueDecl *)nullptr),
989           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
990           HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
991 
992     ~EvalInfo() {
993       discardCleanups();
994     }
995 
996     ASTContext &getCtx() const override { return Ctx; }
997 
998     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
999                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1000       EvaluatingDecl = Base;
1001       IsEvaluatingDecl = EDK;
1002       EvaluatingDeclValue = &Value;
1003     }
1004 
1005     bool CheckCallLimit(SourceLocation Loc) {
1006       // Don't perform any constexpr calls (other than the call we're checking)
1007       // when checking a potential constant expression.
1008       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1009         return false;
1010       if (NextCallIndex == 0) {
1011         // NextCallIndex has wrapped around.
1012         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1013         return false;
1014       }
1015       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1016         return true;
1017       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1018         << getLangOpts().ConstexprCallDepth;
1019       return false;
1020     }
1021 
1022     std::pair<CallStackFrame *, unsigned>
1023     getCallFrameAndDepth(unsigned CallIndex) {
1024       assert(CallIndex && "no call index in getCallFrameAndDepth");
1025       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1026       // be null in this loop.
1027       unsigned Depth = CallStackDepth;
1028       CallStackFrame *Frame = CurrentCall;
1029       while (Frame->Index > CallIndex) {
1030         Frame = Frame->Caller;
1031         --Depth;
1032       }
1033       if (Frame->Index == CallIndex)
1034         return {Frame, Depth};
1035       return {nullptr, 0};
1036     }
1037 
1038     bool nextStep(const Stmt *S) {
1039       if (!StepsLeft) {
1040         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1041         return false;
1042       }
1043       --StepsLeft;
1044       return true;
1045     }
1046 
1047     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1048 
1049     std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1050       std::optional<DynAlloc *> Result;
1051       auto It = HeapAllocs.find(DA);
1052       if (It != HeapAllocs.end())
1053         Result = &It->second;
1054       return Result;
1055     }
1056 
1057     /// Get the allocated storage for the given parameter of the given call.
1058     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1059       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1060       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1061                    : nullptr;
1062     }
1063 
1064     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1065     struct StdAllocatorCaller {
1066       unsigned FrameIndex;
1067       QualType ElemType;
1068       explicit operator bool() const { return FrameIndex != 0; };
1069     };
1070 
1071     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1072       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1073            Call = Call->Caller) {
1074         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1075         if (!MD)
1076           continue;
1077         const IdentifierInfo *FnII = MD->getIdentifier();
1078         if (!FnII || !FnII->isStr(FnName))
1079           continue;
1080 
1081         const auto *CTSD =
1082             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1083         if (!CTSD)
1084           continue;
1085 
1086         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1087         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1088         if (CTSD->isInStdNamespace() && ClassII &&
1089             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1090             TAL[0].getKind() == TemplateArgument::Type)
1091           return {Call->Index, TAL[0].getAsType()};
1092       }
1093 
1094       return {};
1095     }
1096 
1097     void performLifetimeExtension() {
1098       // Disable the cleanups for lifetime-extended temporaries.
1099       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1100         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1101       });
1102     }
1103 
1104     /// Throw away any remaining cleanups at the end of evaluation. If any
1105     /// cleanups would have had a side-effect, note that as an unmodeled
1106     /// side-effect and return false. Otherwise, return true.
1107     bool discardCleanups() {
1108       for (Cleanup &C : CleanupStack) {
1109         if (C.hasSideEffect() && !noteSideEffect()) {
1110           CleanupStack.clear();
1111           return false;
1112         }
1113       }
1114       CleanupStack.clear();
1115       return true;
1116     }
1117 
1118   private:
1119     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1120     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1121 
1122     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1123     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1124 
1125     void setFoldFailureDiagnostic(bool Flag) override {
1126       HasFoldFailureDiagnostic = Flag;
1127     }
1128 
1129     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1130 
1131     // If we have a prior diagnostic, it will be noting that the expression
1132     // isn't a constant expression. This diagnostic is more important,
1133     // unless we require this evaluation to produce a constant expression.
1134     //
1135     // FIXME: We might want to show both diagnostics to the user in
1136     // EM_ConstantFold mode.
1137     bool hasPriorDiagnostic() override {
1138       if (!EvalStatus.Diag->empty()) {
1139         switch (EvalMode) {
1140         case EM_ConstantFold:
1141         case EM_IgnoreSideEffects:
1142           if (!HasFoldFailureDiagnostic)
1143             break;
1144           // We've already failed to fold something. Keep that diagnostic.
1145           [[fallthrough]];
1146         case EM_ConstantExpression:
1147         case EM_ConstantExpressionUnevaluated:
1148           setActiveDiagnostic(false);
1149           return true;
1150         }
1151       }
1152       return false;
1153     }
1154 
1155     unsigned getCallStackDepth() override { return CallStackDepth; }
1156 
1157   public:
1158     /// Should we continue evaluation after encountering a side-effect that we
1159     /// couldn't model?
1160     bool keepEvaluatingAfterSideEffect() {
1161       switch (EvalMode) {
1162       case EM_IgnoreSideEffects:
1163         return true;
1164 
1165       case EM_ConstantExpression:
1166       case EM_ConstantExpressionUnevaluated:
1167       case EM_ConstantFold:
1168         // By default, assume any side effect might be valid in some other
1169         // evaluation of this expression from a different context.
1170         return checkingPotentialConstantExpression() ||
1171                checkingForUndefinedBehavior();
1172       }
1173       llvm_unreachable("Missed EvalMode case");
1174     }
1175 
1176     /// Note that we have had a side-effect, and determine whether we should
1177     /// keep evaluating.
1178     bool noteSideEffect() {
1179       EvalStatus.HasSideEffects = true;
1180       return keepEvaluatingAfterSideEffect();
1181     }
1182 
1183     /// Should we continue evaluation after encountering undefined behavior?
1184     bool keepEvaluatingAfterUndefinedBehavior() {
1185       switch (EvalMode) {
1186       case EM_IgnoreSideEffects:
1187       case EM_ConstantFold:
1188         return true;
1189 
1190       case EM_ConstantExpression:
1191       case EM_ConstantExpressionUnevaluated:
1192         return checkingForUndefinedBehavior();
1193       }
1194       llvm_unreachable("Missed EvalMode case");
1195     }
1196 
1197     /// Note that we hit something that was technically undefined behavior, but
1198     /// that we can evaluate past it (such as signed overflow or floating-point
1199     /// division by zero.)
1200     bool noteUndefinedBehavior() override {
1201       EvalStatus.HasUndefinedBehavior = true;
1202       return keepEvaluatingAfterUndefinedBehavior();
1203     }
1204 
1205     /// Should we continue evaluation as much as possible after encountering a
1206     /// construct which can't be reduced to a value?
1207     bool keepEvaluatingAfterFailure() const override {
1208       if (!StepsLeft)
1209         return false;
1210 
1211       switch (EvalMode) {
1212       case EM_ConstantExpression:
1213       case EM_ConstantExpressionUnevaluated:
1214       case EM_ConstantFold:
1215       case EM_IgnoreSideEffects:
1216         return checkingPotentialConstantExpression() ||
1217                checkingForUndefinedBehavior();
1218       }
1219       llvm_unreachable("Missed EvalMode case");
1220     }
1221 
1222     /// Notes that we failed to evaluate an expression that other expressions
1223     /// directly depend on, and determine if we should keep evaluating. This
1224     /// should only be called if we actually intend to keep evaluating.
1225     ///
1226     /// Call noteSideEffect() instead if we may be able to ignore the value that
1227     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1228     ///
1229     /// (Foo(), 1)      // use noteSideEffect
1230     /// (Foo() || true) // use noteSideEffect
1231     /// Foo() + 1       // use noteFailure
1232     [[nodiscard]] bool noteFailure() {
1233       // Failure when evaluating some expression often means there is some
1234       // subexpression whose evaluation was skipped. Therefore, (because we
1235       // don't track whether we skipped an expression when unwinding after an
1236       // evaluation failure) every evaluation failure that bubbles up from a
1237       // subexpression implies that a side-effect has potentially happened. We
1238       // skip setting the HasSideEffects flag to true until we decide to
1239       // continue evaluating after that point, which happens here.
1240       bool KeepGoing = keepEvaluatingAfterFailure();
1241       EvalStatus.HasSideEffects |= KeepGoing;
1242       return KeepGoing;
1243     }
1244 
1245     class ArrayInitLoopIndex {
1246       EvalInfo &Info;
1247       uint64_t OuterIndex;
1248 
1249     public:
1250       ArrayInitLoopIndex(EvalInfo &Info)
1251           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1252         Info.ArrayInitIndex = 0;
1253       }
1254       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1255 
1256       operator uint64_t&() { return Info.ArrayInitIndex; }
1257     };
1258   };
1259 
1260   /// Object used to treat all foldable expressions as constant expressions.
1261   struct FoldConstant {
1262     EvalInfo &Info;
1263     bool Enabled;
1264     bool HadNoPriorDiags;
1265     EvalInfo::EvaluationMode OldMode;
1266 
1267     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1268       : Info(Info),
1269         Enabled(Enabled),
1270         HadNoPriorDiags(Info.EvalStatus.Diag &&
1271                         Info.EvalStatus.Diag->empty() &&
1272                         !Info.EvalStatus.HasSideEffects),
1273         OldMode(Info.EvalMode) {
1274       if (Enabled)
1275         Info.EvalMode = EvalInfo::EM_ConstantFold;
1276     }
1277     void keepDiagnostics() { Enabled = false; }
1278     ~FoldConstant() {
1279       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1280           !Info.EvalStatus.HasSideEffects)
1281         Info.EvalStatus.Diag->clear();
1282       Info.EvalMode = OldMode;
1283     }
1284   };
1285 
1286   /// RAII object used to set the current evaluation mode to ignore
1287   /// side-effects.
1288   struct IgnoreSideEffectsRAII {
1289     EvalInfo &Info;
1290     EvalInfo::EvaluationMode OldMode;
1291     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1292         : Info(Info), OldMode(Info.EvalMode) {
1293       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1294     }
1295 
1296     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1297   };
1298 
1299   /// RAII object used to optionally suppress diagnostics and side-effects from
1300   /// a speculative evaluation.
1301   class SpeculativeEvaluationRAII {
1302     EvalInfo *Info = nullptr;
1303     Expr::EvalStatus OldStatus;
1304     unsigned OldSpeculativeEvaluationDepth = 0;
1305 
1306     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1307       Info = Other.Info;
1308       OldStatus = Other.OldStatus;
1309       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1310       Other.Info = nullptr;
1311     }
1312 
1313     void maybeRestoreState() {
1314       if (!Info)
1315         return;
1316 
1317       Info->EvalStatus = OldStatus;
1318       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1319     }
1320 
1321   public:
1322     SpeculativeEvaluationRAII() = default;
1323 
1324     SpeculativeEvaluationRAII(
1325         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1326         : Info(&Info), OldStatus(Info.EvalStatus),
1327           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1328       Info.EvalStatus.Diag = NewDiag;
1329       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1330     }
1331 
1332     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1333     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1334       moveFromAndCancel(std::move(Other));
1335     }
1336 
1337     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1338       maybeRestoreState();
1339       moveFromAndCancel(std::move(Other));
1340       return *this;
1341     }
1342 
1343     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1344   };
1345 
1346   /// RAII object wrapping a full-expression or block scope, and handling
1347   /// the ending of the lifetime of temporaries created within it.
1348   template<ScopeKind Kind>
1349   class ScopeRAII {
1350     EvalInfo &Info;
1351     unsigned OldStackSize;
1352   public:
1353     ScopeRAII(EvalInfo &Info)
1354         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1355       // Push a new temporary version. This is needed to distinguish between
1356       // temporaries created in different iterations of a loop.
1357       Info.CurrentCall->pushTempVersion();
1358     }
1359     bool destroy(bool RunDestructors = true) {
1360       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1361       OldStackSize = -1U;
1362       return OK;
1363     }
1364     ~ScopeRAII() {
1365       if (OldStackSize != -1U)
1366         destroy(false);
1367       // Body moved to a static method to encourage the compiler to inline away
1368       // instances of this class.
1369       Info.CurrentCall->popTempVersion();
1370     }
1371   private:
1372     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1373                         unsigned OldStackSize) {
1374       assert(OldStackSize <= Info.CleanupStack.size() &&
1375              "running cleanups out of order?");
1376 
1377       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1378       // for a full-expression scope.
1379       bool Success = true;
1380       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1381         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1382           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1383             Success = false;
1384             break;
1385           }
1386         }
1387       }
1388 
1389       // Compact any retained cleanups.
1390       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1391       if (Kind != ScopeKind::Block)
1392         NewEnd =
1393             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1394               return C.isDestroyedAtEndOf(Kind);
1395             });
1396       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1397       return Success;
1398     }
1399   };
1400   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1401   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1402   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1403 }
1404 
1405 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1406                                          CheckSubobjectKind CSK) {
1407   if (Invalid)
1408     return false;
1409   if (isOnePastTheEnd()) {
1410     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1411       << CSK;
1412     setInvalid();
1413     return false;
1414   }
1415   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1416   // must actually be at least one array element; even a VLA cannot have a
1417   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1418   return true;
1419 }
1420 
1421 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1422                                                                 const Expr *E) {
1423   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1424   // Do not set the designator as invalid: we can represent this situation,
1425   // and correct handling of __builtin_object_size requires us to do so.
1426 }
1427 
1428 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1429                                                     const Expr *E,
1430                                                     const APSInt &N) {
1431   // If we're complaining, we must be able to statically determine the size of
1432   // the most derived array.
1433   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1434     Info.CCEDiag(E, diag::note_constexpr_array_index)
1435       << N << /*array*/ 0
1436       << static_cast<unsigned>(getMostDerivedArraySize());
1437   else
1438     Info.CCEDiag(E, diag::note_constexpr_array_index)
1439       << N << /*non-array*/ 1;
1440   setInvalid();
1441 }
1442 
1443 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1444                                const FunctionDecl *Callee, const LValue *This,
1445                                const Expr *CallExpr, CallRef Call)
1446     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1447       CallExpr(CallExpr), Arguments(Call), CallLoc(CallLoc),
1448       Index(Info.NextCallIndex++) {
1449   Info.CurrentCall = this;
1450   ++Info.CallStackDepth;
1451 }
1452 
1453 CallStackFrame::~CallStackFrame() {
1454   assert(Info.CurrentCall == this && "calls retired out of order");
1455   --Info.CallStackDepth;
1456   Info.CurrentCall = Caller;
1457 }
1458 
1459 static bool isRead(AccessKinds AK) {
1460   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1461 }
1462 
1463 static bool isModification(AccessKinds AK) {
1464   switch (AK) {
1465   case AK_Read:
1466   case AK_ReadObjectRepresentation:
1467   case AK_MemberCall:
1468   case AK_DynamicCast:
1469   case AK_TypeId:
1470     return false;
1471   case AK_Assign:
1472   case AK_Increment:
1473   case AK_Decrement:
1474   case AK_Construct:
1475   case AK_Destroy:
1476     return true;
1477   }
1478   llvm_unreachable("unknown access kind");
1479 }
1480 
1481 static bool isAnyAccess(AccessKinds AK) {
1482   return isRead(AK) || isModification(AK);
1483 }
1484 
1485 /// Is this an access per the C++ definition?
1486 static bool isFormalAccess(AccessKinds AK) {
1487   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1488 }
1489 
1490 /// Is this kind of axcess valid on an indeterminate object value?
1491 static bool isValidIndeterminateAccess(AccessKinds AK) {
1492   switch (AK) {
1493   case AK_Read:
1494   case AK_Increment:
1495   case AK_Decrement:
1496     // These need the object's value.
1497     return false;
1498 
1499   case AK_ReadObjectRepresentation:
1500   case AK_Assign:
1501   case AK_Construct:
1502   case AK_Destroy:
1503     // Construction and destruction don't need the value.
1504     return true;
1505 
1506   case AK_MemberCall:
1507   case AK_DynamicCast:
1508   case AK_TypeId:
1509     // These aren't really meaningful on scalars.
1510     return true;
1511   }
1512   llvm_unreachable("unknown access kind");
1513 }
1514 
1515 namespace {
1516   struct ComplexValue {
1517   private:
1518     bool IsInt;
1519 
1520   public:
1521     APSInt IntReal, IntImag;
1522     APFloat FloatReal, FloatImag;
1523 
1524     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1525 
1526     void makeComplexFloat() { IsInt = false; }
1527     bool isComplexFloat() const { return !IsInt; }
1528     APFloat &getComplexFloatReal() { return FloatReal; }
1529     APFloat &getComplexFloatImag() { return FloatImag; }
1530 
1531     void makeComplexInt() { IsInt = true; }
1532     bool isComplexInt() const { return IsInt; }
1533     APSInt &getComplexIntReal() { return IntReal; }
1534     APSInt &getComplexIntImag() { return IntImag; }
1535 
1536     void moveInto(APValue &v) const {
1537       if (isComplexFloat())
1538         v = APValue(FloatReal, FloatImag);
1539       else
1540         v = APValue(IntReal, IntImag);
1541     }
1542     void setFrom(const APValue &v) {
1543       assert(v.isComplexFloat() || v.isComplexInt());
1544       if (v.isComplexFloat()) {
1545         makeComplexFloat();
1546         FloatReal = v.getComplexFloatReal();
1547         FloatImag = v.getComplexFloatImag();
1548       } else {
1549         makeComplexInt();
1550         IntReal = v.getComplexIntReal();
1551         IntImag = v.getComplexIntImag();
1552       }
1553     }
1554   };
1555 
1556   struct LValue {
1557     APValue::LValueBase Base;
1558     CharUnits Offset;
1559     SubobjectDesignator Designator;
1560     bool IsNullPtr : 1;
1561     bool InvalidBase : 1;
1562 
1563     const APValue::LValueBase getLValueBase() const { return Base; }
1564     CharUnits &getLValueOffset() { return Offset; }
1565     const CharUnits &getLValueOffset() const { return Offset; }
1566     SubobjectDesignator &getLValueDesignator() { return Designator; }
1567     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1568     bool isNullPointer() const { return IsNullPtr;}
1569 
1570     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1571     unsigned getLValueVersion() const { return Base.getVersion(); }
1572 
1573     void moveInto(APValue &V) const {
1574       if (Designator.Invalid)
1575         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1576       else {
1577         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1578         V = APValue(Base, Offset, Designator.Entries,
1579                     Designator.IsOnePastTheEnd, IsNullPtr);
1580       }
1581     }
1582     void setFrom(ASTContext &Ctx, const APValue &V) {
1583       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1584       Base = V.getLValueBase();
1585       Offset = V.getLValueOffset();
1586       InvalidBase = false;
1587       Designator = SubobjectDesignator(Ctx, V);
1588       IsNullPtr = V.isNullPointer();
1589     }
1590 
1591     void set(APValue::LValueBase B, bool BInvalid = false) {
1592 #ifndef NDEBUG
1593       // We only allow a few types of invalid bases. Enforce that here.
1594       if (BInvalid) {
1595         const auto *E = B.get<const Expr *>();
1596         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1597                "Unexpected type of invalid base");
1598       }
1599 #endif
1600 
1601       Base = B;
1602       Offset = CharUnits::fromQuantity(0);
1603       InvalidBase = BInvalid;
1604       Designator = SubobjectDesignator(getType(B));
1605       IsNullPtr = false;
1606     }
1607 
1608     void setNull(ASTContext &Ctx, QualType PointerTy) {
1609       Base = (const ValueDecl *)nullptr;
1610       Offset =
1611           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1612       InvalidBase = false;
1613       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1614       IsNullPtr = true;
1615     }
1616 
1617     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1618       set(B, true);
1619     }
1620 
1621     std::string toString(ASTContext &Ctx, QualType T) const {
1622       APValue Printable;
1623       moveInto(Printable);
1624       return Printable.getAsString(Ctx, T);
1625     }
1626 
1627   private:
1628     // Check that this LValue is not based on a null pointer. If it is, produce
1629     // a diagnostic and mark the designator as invalid.
1630     template <typename GenDiagType>
1631     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1632       if (Designator.Invalid)
1633         return false;
1634       if (IsNullPtr) {
1635         GenDiag();
1636         Designator.setInvalid();
1637         return false;
1638       }
1639       return true;
1640     }
1641 
1642   public:
1643     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1644                           CheckSubobjectKind CSK) {
1645       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1646         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1647       });
1648     }
1649 
1650     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1651                                        AccessKinds AK) {
1652       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1653         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1654       });
1655     }
1656 
1657     // Check this LValue refers to an object. If not, set the designator to be
1658     // invalid and emit a diagnostic.
1659     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1660       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1661              Designator.checkSubobject(Info, E, CSK);
1662     }
1663 
1664     void addDecl(EvalInfo &Info, const Expr *E,
1665                  const Decl *D, bool Virtual = false) {
1666       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1667         Designator.addDeclUnchecked(D, Virtual);
1668     }
1669     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1670       if (!Designator.Entries.empty()) {
1671         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1672         Designator.setInvalid();
1673         return;
1674       }
1675       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1676         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1677         Designator.FirstEntryIsAnUnsizedArray = true;
1678         Designator.addUnsizedArrayUnchecked(ElemTy);
1679       }
1680     }
1681     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1682       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1683         Designator.addArrayUnchecked(CAT);
1684     }
1685     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1686       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1687         Designator.addComplexUnchecked(EltTy, Imag);
1688     }
1689     void clearIsNullPointer() {
1690       IsNullPtr = false;
1691     }
1692     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1693                               const APSInt &Index, CharUnits ElementSize) {
1694       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1695       // but we're not required to diagnose it and it's valid in C++.)
1696       if (!Index)
1697         return;
1698 
1699       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1700       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1701       // offsets.
1702       uint64_t Offset64 = Offset.getQuantity();
1703       uint64_t ElemSize64 = ElementSize.getQuantity();
1704       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1705       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1706 
1707       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1708         Designator.adjustIndex(Info, E, Index);
1709       clearIsNullPointer();
1710     }
1711     void adjustOffset(CharUnits N) {
1712       Offset += N;
1713       if (N.getQuantity())
1714         clearIsNullPointer();
1715     }
1716   };
1717 
1718   struct MemberPtr {
1719     MemberPtr() {}
1720     explicit MemberPtr(const ValueDecl *Decl)
1721         : DeclAndIsDerivedMember(Decl, false) {}
1722 
1723     /// The member or (direct or indirect) field referred to by this member
1724     /// pointer, or 0 if this is a null member pointer.
1725     const ValueDecl *getDecl() const {
1726       return DeclAndIsDerivedMember.getPointer();
1727     }
1728     /// Is this actually a member of some type derived from the relevant class?
1729     bool isDerivedMember() const {
1730       return DeclAndIsDerivedMember.getInt();
1731     }
1732     /// Get the class which the declaration actually lives in.
1733     const CXXRecordDecl *getContainingRecord() const {
1734       return cast<CXXRecordDecl>(
1735           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1736     }
1737 
1738     void moveInto(APValue &V) const {
1739       V = APValue(getDecl(), isDerivedMember(), Path);
1740     }
1741     void setFrom(const APValue &V) {
1742       assert(V.isMemberPointer());
1743       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1744       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1745       Path.clear();
1746       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1747       Path.insert(Path.end(), P.begin(), P.end());
1748     }
1749 
1750     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1751     /// whether the member is a member of some class derived from the class type
1752     /// of the member pointer.
1753     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1754     /// Path - The path of base/derived classes from the member declaration's
1755     /// class (exclusive) to the class type of the member pointer (inclusive).
1756     SmallVector<const CXXRecordDecl*, 4> Path;
1757 
1758     /// Perform a cast towards the class of the Decl (either up or down the
1759     /// hierarchy).
1760     bool castBack(const CXXRecordDecl *Class) {
1761       assert(!Path.empty());
1762       const CXXRecordDecl *Expected;
1763       if (Path.size() >= 2)
1764         Expected = Path[Path.size() - 2];
1765       else
1766         Expected = getContainingRecord();
1767       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1768         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1769         // if B does not contain the original member and is not a base or
1770         // derived class of the class containing the original member, the result
1771         // of the cast is undefined.
1772         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1773         // (D::*). We consider that to be a language defect.
1774         return false;
1775       }
1776       Path.pop_back();
1777       return true;
1778     }
1779     /// Perform a base-to-derived member pointer cast.
1780     bool castToDerived(const CXXRecordDecl *Derived) {
1781       if (!getDecl())
1782         return true;
1783       if (!isDerivedMember()) {
1784         Path.push_back(Derived);
1785         return true;
1786       }
1787       if (!castBack(Derived))
1788         return false;
1789       if (Path.empty())
1790         DeclAndIsDerivedMember.setInt(false);
1791       return true;
1792     }
1793     /// Perform a derived-to-base member pointer cast.
1794     bool castToBase(const CXXRecordDecl *Base) {
1795       if (!getDecl())
1796         return true;
1797       if (Path.empty())
1798         DeclAndIsDerivedMember.setInt(true);
1799       if (isDerivedMember()) {
1800         Path.push_back(Base);
1801         return true;
1802       }
1803       return castBack(Base);
1804     }
1805   };
1806 
1807   /// Compare two member pointers, which are assumed to be of the same type.
1808   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1809     if (!LHS.getDecl() || !RHS.getDecl())
1810       return !LHS.getDecl() && !RHS.getDecl();
1811     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1812       return false;
1813     return LHS.Path == RHS.Path;
1814   }
1815 }
1816 
1817 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1818 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1819                             const LValue &This, const Expr *E,
1820                             bool AllowNonLiteralTypes = false);
1821 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1822                            bool InvalidBaseOK = false);
1823 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1824                             bool InvalidBaseOK = false);
1825 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1826                                   EvalInfo &Info);
1827 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1828 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1829 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1830                                     EvalInfo &Info);
1831 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1832 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1833 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1834                            EvalInfo &Info);
1835 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1836 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1837                                   EvalInfo &Info);
1838 
1839 /// Evaluate an integer or fixed point expression into an APResult.
1840 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1841                                         EvalInfo &Info);
1842 
1843 /// Evaluate only a fixed point expression into an APResult.
1844 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1845                                EvalInfo &Info);
1846 
1847 //===----------------------------------------------------------------------===//
1848 // Misc utilities
1849 //===----------------------------------------------------------------------===//
1850 
1851 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1852 /// preserving its value (by extending by up to one bit as needed).
1853 static void negateAsSigned(APSInt &Int) {
1854   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1855     Int = Int.extend(Int.getBitWidth() + 1);
1856     Int.setIsSigned(true);
1857   }
1858   Int = -Int;
1859 }
1860 
1861 template<typename KeyT>
1862 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1863                                          ScopeKind Scope, LValue &LV) {
1864   unsigned Version = getTempVersion();
1865   APValue::LValueBase Base(Key, Index, Version);
1866   LV.set(Base);
1867   return createLocal(Base, Key, T, Scope);
1868 }
1869 
1870 /// Allocate storage for a parameter of a function call made in this frame.
1871 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1872                                      LValue &LV) {
1873   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1874   APValue::LValueBase Base(PVD, Index, Args.Version);
1875   LV.set(Base);
1876   // We always destroy parameters at the end of the call, even if we'd allow
1877   // them to live to the end of the full-expression at runtime, in order to
1878   // give portable results and match other compilers.
1879   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1880 }
1881 
1882 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1883                                      QualType T, ScopeKind Scope) {
1884   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1885   unsigned Version = Base.getVersion();
1886   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1887   assert(Result.isAbsent() && "local created multiple times");
1888 
1889   // If we're creating a local immediately in the operand of a speculative
1890   // evaluation, don't register a cleanup to be run outside the speculative
1891   // evaluation context, since we won't actually be able to initialize this
1892   // object.
1893   if (Index <= Info.SpeculativeEvaluationDepth) {
1894     if (T.isDestructedType())
1895       Info.noteSideEffect();
1896   } else {
1897     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1898   }
1899   return Result;
1900 }
1901 
1902 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1903   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1904     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1905     return nullptr;
1906   }
1907 
1908   DynamicAllocLValue DA(NumHeapAllocs++);
1909   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1910   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1911                                    std::forward_as_tuple(DA), std::tuple<>());
1912   assert(Result.second && "reused a heap alloc index?");
1913   Result.first->second.AllocExpr = E;
1914   return &Result.first->second.Value;
1915 }
1916 
1917 /// Produce a string describing the given constexpr call.
1918 void CallStackFrame::describe(raw_ostream &Out) const {
1919   unsigned ArgIndex = 0;
1920   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1921                       !isa<CXXConstructorDecl>(Callee) &&
1922                       cast<CXXMethodDecl>(Callee)->isInstance();
1923 
1924   if (!IsMemberCall)
1925     Out << *Callee << '(';
1926 
1927   if (This && IsMemberCall) {
1928     if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1929       const Expr *Object = MCE->getImplicitObjectArgument();
1930       Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1931                           /*Indentation=*/0);
1932       if (Object->getType()->isPointerType())
1933           Out << "->";
1934       else
1935           Out << ".";
1936     } else if (const auto *OCE =
1937                    dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1938       OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1939                                   Info.Ctx.getPrintingPolicy(),
1940                                   /*Indentation=*/0);
1941       Out << ".";
1942     } else {
1943       APValue Val;
1944       This->moveInto(Val);
1945       Val.printPretty(
1946           Out, Info.Ctx,
1947           Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1948       Out << ".";
1949     }
1950     Out << *Callee << '(';
1951     IsMemberCall = false;
1952   }
1953 
1954   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1955        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1956     if (ArgIndex > (unsigned)IsMemberCall)
1957       Out << ", ";
1958 
1959     const ParmVarDecl *Param = *I;
1960     APValue *V = Info.getParamSlot(Arguments, Param);
1961     if (V)
1962       V->printPretty(Out, Info.Ctx, Param->getType());
1963     else
1964       Out << "<...>";
1965 
1966     if (ArgIndex == 0 && IsMemberCall)
1967       Out << "->" << *Callee << '(';
1968   }
1969 
1970   Out << ')';
1971 }
1972 
1973 /// Evaluate an expression to see if it had side-effects, and discard its
1974 /// result.
1975 /// \return \c true if the caller should keep evaluating.
1976 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1977   assert(!E->isValueDependent());
1978   APValue Scratch;
1979   if (!Evaluate(Scratch, Info, E))
1980     // We don't need the value, but we might have skipped a side effect here.
1981     return Info.noteSideEffect();
1982   return true;
1983 }
1984 
1985 /// Should this call expression be treated as a no-op?
1986 static bool IsNoOpCall(const CallExpr *E) {
1987   unsigned Builtin = E->getBuiltinCallee();
1988   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1989           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1990           Builtin == Builtin::BI__builtin_function_start);
1991 }
1992 
1993 static bool IsGlobalLValue(APValue::LValueBase B) {
1994   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1995   // constant expression of pointer type that evaluates to...
1996 
1997   // ... a null pointer value, or a prvalue core constant expression of type
1998   // std::nullptr_t.
1999   if (!B)
2000     return true;
2001 
2002   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2003     // ... the address of an object with static storage duration,
2004     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2005       return VD->hasGlobalStorage();
2006     if (isa<TemplateParamObjectDecl>(D))
2007       return true;
2008     // ... the address of a function,
2009     // ... the address of a GUID [MS extension],
2010     // ... the address of an unnamed global constant
2011     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2012   }
2013 
2014   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2015     return true;
2016 
2017   const Expr *E = B.get<const Expr*>();
2018   switch (E->getStmtClass()) {
2019   default:
2020     return false;
2021   case Expr::CompoundLiteralExprClass: {
2022     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2023     return CLE->isFileScope() && CLE->isLValue();
2024   }
2025   case Expr::MaterializeTemporaryExprClass:
2026     // A materialized temporary might have been lifetime-extended to static
2027     // storage duration.
2028     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2029   // A string literal has static storage duration.
2030   case Expr::StringLiteralClass:
2031   case Expr::PredefinedExprClass:
2032   case Expr::ObjCStringLiteralClass:
2033   case Expr::ObjCEncodeExprClass:
2034     return true;
2035   case Expr::ObjCBoxedExprClass:
2036     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2037   case Expr::CallExprClass:
2038     return IsNoOpCall(cast<CallExpr>(E));
2039   // For GCC compatibility, &&label has static storage duration.
2040   case Expr::AddrLabelExprClass:
2041     return true;
2042   // A Block literal expression may be used as the initialization value for
2043   // Block variables at global or local static scope.
2044   case Expr::BlockExprClass:
2045     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2046   // The APValue generated from a __builtin_source_location will be emitted as a
2047   // literal.
2048   case Expr::SourceLocExprClass:
2049     return true;
2050   case Expr::ImplicitValueInitExprClass:
2051     // FIXME:
2052     // We can never form an lvalue with an implicit value initialization as its
2053     // base through expression evaluation, so these only appear in one case: the
2054     // implicit variable declaration we invent when checking whether a constexpr
2055     // constructor can produce a constant expression. We must assume that such
2056     // an expression might be a global lvalue.
2057     return true;
2058   }
2059 }
2060 
2061 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2062   return LVal.Base.dyn_cast<const ValueDecl*>();
2063 }
2064 
2065 static bool IsLiteralLValue(const LValue &Value) {
2066   if (Value.getLValueCallIndex())
2067     return false;
2068   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2069   return E && !isa<MaterializeTemporaryExpr>(E);
2070 }
2071 
2072 static bool IsWeakLValue(const LValue &Value) {
2073   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2074   return Decl && Decl->isWeak();
2075 }
2076 
2077 static bool isZeroSized(const LValue &Value) {
2078   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2079   if (Decl && isa<VarDecl>(Decl)) {
2080     QualType Ty = Decl->getType();
2081     if (Ty->isArrayType())
2082       return Ty->isIncompleteType() ||
2083              Decl->getASTContext().getTypeSize(Ty) == 0;
2084   }
2085   return false;
2086 }
2087 
2088 static bool HasSameBase(const LValue &A, const LValue &B) {
2089   if (!A.getLValueBase())
2090     return !B.getLValueBase();
2091   if (!B.getLValueBase())
2092     return false;
2093 
2094   if (A.getLValueBase().getOpaqueValue() !=
2095       B.getLValueBase().getOpaqueValue())
2096     return false;
2097 
2098   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2099          A.getLValueVersion() == B.getLValueVersion();
2100 }
2101 
2102 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2103   assert(Base && "no location for a null lvalue");
2104   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2105 
2106   // For a parameter, find the corresponding call stack frame (if it still
2107   // exists), and point at the parameter of the function definition we actually
2108   // invoked.
2109   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2110     unsigned Idx = PVD->getFunctionScopeIndex();
2111     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2112       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2113           F->Arguments.Version == Base.getVersion() && F->Callee &&
2114           Idx < F->Callee->getNumParams()) {
2115         VD = F->Callee->getParamDecl(Idx);
2116         break;
2117       }
2118     }
2119   }
2120 
2121   if (VD)
2122     Info.Note(VD->getLocation(), diag::note_declared_at);
2123   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2124     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2125   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2126     // FIXME: Produce a note for dangling pointers too.
2127     if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2128       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2129                 diag::note_constexpr_dynamic_alloc_here);
2130   }
2131 
2132   // We have no information to show for a typeid(T) object.
2133 }
2134 
2135 enum class CheckEvaluationResultKind {
2136   ConstantExpression,
2137   FullyInitialized,
2138 };
2139 
2140 /// Materialized temporaries that we've already checked to determine if they're
2141 /// initializsed by a constant expression.
2142 using CheckedTemporaries =
2143     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2144 
2145 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2146                                   EvalInfo &Info, SourceLocation DiagLoc,
2147                                   QualType Type, const APValue &Value,
2148                                   ConstantExprKind Kind,
2149                                   const FieldDecl *SubobjectDecl,
2150                                   CheckedTemporaries &CheckedTemps);
2151 
2152 /// Check that this reference or pointer core constant expression is a valid
2153 /// value for an address or reference constant expression. Return true if we
2154 /// can fold this expression, whether or not it's a constant expression.
2155 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2156                                           QualType Type, const LValue &LVal,
2157                                           ConstantExprKind Kind,
2158                                           CheckedTemporaries &CheckedTemps) {
2159   bool IsReferenceType = Type->isReferenceType();
2160 
2161   APValue::LValueBase Base = LVal.getLValueBase();
2162   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2163 
2164   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2165   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2166 
2167   // Additional restrictions apply in a template argument. We only enforce the
2168   // C++20 restrictions here; additional syntactic and semantic restrictions
2169   // are applied elsewhere.
2170   if (isTemplateArgument(Kind)) {
2171     int InvalidBaseKind = -1;
2172     StringRef Ident;
2173     if (Base.is<TypeInfoLValue>())
2174       InvalidBaseKind = 0;
2175     else if (isa_and_nonnull<StringLiteral>(BaseE))
2176       InvalidBaseKind = 1;
2177     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2178              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2179       InvalidBaseKind = 2;
2180     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2181       InvalidBaseKind = 3;
2182       Ident = PE->getIdentKindName();
2183     }
2184 
2185     if (InvalidBaseKind != -1) {
2186       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2187           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2188           << Ident;
2189       return false;
2190     }
2191   }
2192 
2193   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2194       FD && FD->isImmediateFunction()) {
2195     Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2196         << !Type->isAnyPointerType();
2197     Info.Note(FD->getLocation(), diag::note_declared_at);
2198     return false;
2199   }
2200 
2201   // Check that the object is a global. Note that the fake 'this' object we
2202   // manufacture when checking potential constant expressions is conservatively
2203   // assumed to be global here.
2204   if (!IsGlobalLValue(Base)) {
2205     if (Info.getLangOpts().CPlusPlus11) {
2206       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2207           << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2208           << BaseVD;
2209       auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2210       if (VarD && VarD->isConstexpr()) {
2211         // Non-static local constexpr variables have unintuitive semantics:
2212         //   constexpr int a = 1;
2213         //   constexpr const int *p = &a;
2214         // ... is invalid because the address of 'a' is not constant. Suggest
2215         // adding a 'static' in this case.
2216         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2217             << VarD
2218             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2219       } else {
2220         NoteLValueLocation(Info, Base);
2221       }
2222     } else {
2223       Info.FFDiag(Loc);
2224     }
2225     // Don't allow references to temporaries to escape.
2226     return false;
2227   }
2228   assert((Info.checkingPotentialConstantExpression() ||
2229           LVal.getLValueCallIndex() == 0) &&
2230          "have call index for global lvalue");
2231 
2232   if (Base.is<DynamicAllocLValue>()) {
2233     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2234         << IsReferenceType << !Designator.Entries.empty();
2235     NoteLValueLocation(Info, Base);
2236     return false;
2237   }
2238 
2239   if (BaseVD) {
2240     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2241       // Check if this is a thread-local variable.
2242       if (Var->getTLSKind())
2243         // FIXME: Diagnostic!
2244         return false;
2245 
2246       // A dllimport variable never acts like a constant, unless we're
2247       // evaluating a value for use only in name mangling.
2248       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2249         // FIXME: Diagnostic!
2250         return false;
2251 
2252       // In CUDA/HIP device compilation, only device side variables have
2253       // constant addresses.
2254       if (Info.getCtx().getLangOpts().CUDA &&
2255           Info.getCtx().getLangOpts().CUDAIsDevice &&
2256           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2257         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2258              !Var->hasAttr<CUDAConstantAttr>() &&
2259              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2260              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2261             Var->hasAttr<HIPManagedAttr>())
2262           return false;
2263       }
2264     }
2265     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2266       // __declspec(dllimport) must be handled very carefully:
2267       // We must never initialize an expression with the thunk in C++.
2268       // Doing otherwise would allow the same id-expression to yield
2269       // different addresses for the same function in different translation
2270       // units.  However, this means that we must dynamically initialize the
2271       // expression with the contents of the import address table at runtime.
2272       //
2273       // The C language has no notion of ODR; furthermore, it has no notion of
2274       // dynamic initialization.  This means that we are permitted to
2275       // perform initialization with the address of the thunk.
2276       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2277           FD->hasAttr<DLLImportAttr>())
2278         // FIXME: Diagnostic!
2279         return false;
2280     }
2281   } else if (const auto *MTE =
2282                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2283     if (CheckedTemps.insert(MTE).second) {
2284       QualType TempType = getType(Base);
2285       if (TempType.isDestructedType()) {
2286         Info.FFDiag(MTE->getExprLoc(),
2287                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2288             << TempType;
2289         return false;
2290       }
2291 
2292       APValue *V = MTE->getOrCreateValue(false);
2293       assert(V && "evasluation result refers to uninitialised temporary");
2294       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2295                                  Info, MTE->getExprLoc(), TempType, *V, Kind,
2296                                  /*SubobjectDecl=*/nullptr, CheckedTemps))
2297         return false;
2298     }
2299   }
2300 
2301   // Allow address constant expressions to be past-the-end pointers. This is
2302   // an extension: the standard requires them to point to an object.
2303   if (!IsReferenceType)
2304     return true;
2305 
2306   // A reference constant expression must refer to an object.
2307   if (!Base) {
2308     // FIXME: diagnostic
2309     Info.CCEDiag(Loc);
2310     return true;
2311   }
2312 
2313   // Does this refer one past the end of some object?
2314   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2315     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2316       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2317     NoteLValueLocation(Info, Base);
2318   }
2319 
2320   return true;
2321 }
2322 
2323 /// Member pointers are constant expressions unless they point to a
2324 /// non-virtual dllimport member function.
2325 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2326                                                  SourceLocation Loc,
2327                                                  QualType Type,
2328                                                  const APValue &Value,
2329                                                  ConstantExprKind Kind) {
2330   const ValueDecl *Member = Value.getMemberPointerDecl();
2331   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2332   if (!FD)
2333     return true;
2334   if (FD->isImmediateFunction()) {
2335     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2336     Info.Note(FD->getLocation(), diag::note_declared_at);
2337     return false;
2338   }
2339   return isForManglingOnly(Kind) || FD->isVirtual() ||
2340          !FD->hasAttr<DLLImportAttr>();
2341 }
2342 
2343 /// Check that this core constant expression is of literal type, and if not,
2344 /// produce an appropriate diagnostic.
2345 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2346                              const LValue *This = nullptr) {
2347   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2348     return true;
2349 
2350   // C++1y: A constant initializer for an object o [...] may also invoke
2351   // constexpr constructors for o and its subobjects even if those objects
2352   // are of non-literal class types.
2353   //
2354   // C++11 missed this detail for aggregates, so classes like this:
2355   //   struct foo_t { union { int i; volatile int j; } u; };
2356   // are not (obviously) initializable like so:
2357   //   __attribute__((__require_constant_initialization__))
2358   //   static const foo_t x = {{0}};
2359   // because "i" is a subobject with non-literal initialization (due to the
2360   // volatile member of the union). See:
2361   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2362   // Therefore, we use the C++1y behavior.
2363   if (This && Info.EvaluatingDecl == This->getLValueBase())
2364     return true;
2365 
2366   // Prvalue constant expressions must be of literal types.
2367   if (Info.getLangOpts().CPlusPlus11)
2368     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2369       << E->getType();
2370   else
2371     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2372   return false;
2373 }
2374 
2375 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2376                                   EvalInfo &Info, SourceLocation DiagLoc,
2377                                   QualType Type, const APValue &Value,
2378                                   ConstantExprKind Kind,
2379                                   const FieldDecl *SubobjectDecl,
2380                                   CheckedTemporaries &CheckedTemps) {
2381   if (!Value.hasValue()) {
2382     if (SubobjectDecl) {
2383       Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2384           << /*(name)*/ 1 << SubobjectDecl;
2385       Info.Note(SubobjectDecl->getLocation(),
2386                 diag::note_constexpr_subobject_declared_here);
2387     } else {
2388       Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2389           << /*of type*/ 0 << Type;
2390     }
2391     return false;
2392   }
2393 
2394   // We allow _Atomic(T) to be initialized from anything that T can be
2395   // initialized from.
2396   if (const AtomicType *AT = Type->getAs<AtomicType>())
2397     Type = AT->getValueType();
2398 
2399   // Core issue 1454: For a literal constant expression of array or class type,
2400   // each subobject of its value shall have been initialized by a constant
2401   // expression.
2402   if (Value.isArray()) {
2403     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2404     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2405       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2406                                  Value.getArrayInitializedElt(I), Kind,
2407                                  SubobjectDecl, CheckedTemps))
2408         return false;
2409     }
2410     if (!Value.hasArrayFiller())
2411       return true;
2412     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2413                                  Value.getArrayFiller(), Kind, SubobjectDecl,
2414                                  CheckedTemps);
2415   }
2416   if (Value.isUnion() && Value.getUnionField()) {
2417     return CheckEvaluationResult(
2418         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2419         Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2420   }
2421   if (Value.isStruct()) {
2422     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2423     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2424       unsigned BaseIndex = 0;
2425       for (const CXXBaseSpecifier &BS : CD->bases()) {
2426         const APValue &BaseValue = Value.getStructBase(BaseIndex);
2427         if (!BaseValue.hasValue()) {
2428           SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2429           Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2430               << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2431           return false;
2432         }
2433         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2434                                    Kind, /*SubobjectDecl=*/nullptr,
2435                                    CheckedTemps))
2436           return false;
2437         ++BaseIndex;
2438       }
2439     }
2440     for (const auto *I : RD->fields()) {
2441       if (I->isUnnamedBitfield())
2442         continue;
2443 
2444       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2445                                  Value.getStructField(I->getFieldIndex()), Kind,
2446                                  I, CheckedTemps))
2447         return false;
2448     }
2449   }
2450 
2451   if (Value.isLValue() &&
2452       CERK == CheckEvaluationResultKind::ConstantExpression) {
2453     LValue LVal;
2454     LVal.setFrom(Info.Ctx, Value);
2455     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2456                                          CheckedTemps);
2457   }
2458 
2459   if (Value.isMemberPointer() &&
2460       CERK == CheckEvaluationResultKind::ConstantExpression)
2461     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2462 
2463   // Everything else is fine.
2464   return true;
2465 }
2466 
2467 /// Check that this core constant expression value is a valid value for a
2468 /// constant expression. If not, report an appropriate diagnostic. Does not
2469 /// check that the expression is of literal type.
2470 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2471                                     QualType Type, const APValue &Value,
2472                                     ConstantExprKind Kind) {
2473   // Nothing to check for a constant expression of type 'cv void'.
2474   if (Type->isVoidType())
2475     return true;
2476 
2477   CheckedTemporaries CheckedTemps;
2478   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2479                                Info, DiagLoc, Type, Value, Kind,
2480                                /*SubobjectDecl=*/nullptr, CheckedTemps);
2481 }
2482 
2483 /// Check that this evaluated value is fully-initialized and can be loaded by
2484 /// an lvalue-to-rvalue conversion.
2485 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2486                                   QualType Type, const APValue &Value) {
2487   CheckedTemporaries CheckedTemps;
2488   return CheckEvaluationResult(
2489       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2490       ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2491 }
2492 
2493 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2494 /// "the allocated storage is deallocated within the evaluation".
2495 static bool CheckMemoryLeaks(EvalInfo &Info) {
2496   if (!Info.HeapAllocs.empty()) {
2497     // We can still fold to a constant despite a compile-time memory leak,
2498     // so long as the heap allocation isn't referenced in the result (we check
2499     // that in CheckConstantExpression).
2500     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2501                  diag::note_constexpr_memory_leak)
2502         << unsigned(Info.HeapAllocs.size() - 1);
2503   }
2504   return true;
2505 }
2506 
2507 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2508   // A null base expression indicates a null pointer.  These are always
2509   // evaluatable, and they are false unless the offset is zero.
2510   if (!Value.getLValueBase()) {
2511     // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2512     Result = !Value.getLValueOffset().isZero();
2513     return true;
2514   }
2515 
2516   // We have a non-null base.  These are generally known to be true, but if it's
2517   // a weak declaration it can be null at runtime.
2518   Result = true;
2519   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2520   return !Decl || !Decl->isWeak();
2521 }
2522 
2523 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2524   // TODO: This function should produce notes if it fails.
2525   switch (Val.getKind()) {
2526   case APValue::None:
2527   case APValue::Indeterminate:
2528     return false;
2529   case APValue::Int:
2530     Result = Val.getInt().getBoolValue();
2531     return true;
2532   case APValue::FixedPoint:
2533     Result = Val.getFixedPoint().getBoolValue();
2534     return true;
2535   case APValue::Float:
2536     Result = !Val.getFloat().isZero();
2537     return true;
2538   case APValue::ComplexInt:
2539     Result = Val.getComplexIntReal().getBoolValue() ||
2540              Val.getComplexIntImag().getBoolValue();
2541     return true;
2542   case APValue::ComplexFloat:
2543     Result = !Val.getComplexFloatReal().isZero() ||
2544              !Val.getComplexFloatImag().isZero();
2545     return true;
2546   case APValue::LValue:
2547     return EvalPointerValueAsBool(Val, Result);
2548   case APValue::MemberPointer:
2549     if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2550       return false;
2551     }
2552     Result = Val.getMemberPointerDecl();
2553     return true;
2554   case APValue::Vector:
2555   case APValue::Array:
2556   case APValue::Struct:
2557   case APValue::Union:
2558   case APValue::AddrLabelDiff:
2559     return false;
2560   }
2561 
2562   llvm_unreachable("unknown APValue kind");
2563 }
2564 
2565 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2566                                        EvalInfo &Info) {
2567   assert(!E->isValueDependent());
2568   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2569   APValue Val;
2570   if (!Evaluate(Val, Info, E))
2571     return false;
2572   return HandleConversionToBool(Val, Result);
2573 }
2574 
2575 template<typename T>
2576 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2577                            const T &SrcValue, QualType DestType) {
2578   Info.CCEDiag(E, diag::note_constexpr_overflow)
2579     << SrcValue << DestType;
2580   return Info.noteUndefinedBehavior();
2581 }
2582 
2583 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2584                                  QualType SrcType, const APFloat &Value,
2585                                  QualType DestType, APSInt &Result) {
2586   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2587   // Determine whether we are converting to unsigned or signed.
2588   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2589 
2590   Result = APSInt(DestWidth, !DestSigned);
2591   bool ignored;
2592   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2593       & APFloat::opInvalidOp)
2594     return HandleOverflow(Info, E, Value, DestType);
2595   return true;
2596 }
2597 
2598 /// Get rounding mode to use in evaluation of the specified expression.
2599 ///
2600 /// If rounding mode is unknown at compile time, still try to evaluate the
2601 /// expression. If the result is exact, it does not depend on rounding mode.
2602 /// So return "tonearest" mode instead of "dynamic".
2603 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2604   llvm::RoundingMode RM =
2605       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2606   if (RM == llvm::RoundingMode::Dynamic)
2607     RM = llvm::RoundingMode::NearestTiesToEven;
2608   return RM;
2609 }
2610 
2611 /// Check if the given evaluation result is allowed for constant evaluation.
2612 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2613                                      APFloat::opStatus St) {
2614   // In a constant context, assume that any dynamic rounding mode or FP
2615   // exception state matches the default floating-point environment.
2616   if (Info.InConstantContext)
2617     return true;
2618 
2619   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2620   if ((St & APFloat::opInexact) &&
2621       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2622     // Inexact result means that it depends on rounding mode. If the requested
2623     // mode is dynamic, the evaluation cannot be made in compile time.
2624     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2625     return false;
2626   }
2627 
2628   if ((St != APFloat::opOK) &&
2629       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2630        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2631        FPO.getAllowFEnvAccess())) {
2632     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2633     return false;
2634   }
2635 
2636   if ((St & APFloat::opStatus::opInvalidOp) &&
2637       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2638     // There is no usefully definable result.
2639     Info.FFDiag(E);
2640     return false;
2641   }
2642 
2643   // FIXME: if:
2644   // - evaluation triggered other FP exception, and
2645   // - exception mode is not "ignore", and
2646   // - the expression being evaluated is not a part of global variable
2647   //   initializer,
2648   // the evaluation probably need to be rejected.
2649   return true;
2650 }
2651 
2652 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2653                                    QualType SrcType, QualType DestType,
2654                                    APFloat &Result) {
2655   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2656   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2657   APFloat::opStatus St;
2658   APFloat Value = Result;
2659   bool ignored;
2660   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2661   return checkFloatingPointResult(Info, E, St);
2662 }
2663 
2664 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2665                                  QualType DestType, QualType SrcType,
2666                                  const APSInt &Value) {
2667   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2668   // Figure out if this is a truncate, extend or noop cast.
2669   // If the input is signed, do a sign extend, noop, or truncate.
2670   APSInt Result = Value.extOrTrunc(DestWidth);
2671   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2672   if (DestType->isBooleanType())
2673     Result = Value.getBoolValue();
2674   return Result;
2675 }
2676 
2677 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2678                                  const FPOptions FPO,
2679                                  QualType SrcType, const APSInt &Value,
2680                                  QualType DestType, APFloat &Result) {
2681   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2682   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2683   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2684   return checkFloatingPointResult(Info, E, St);
2685 }
2686 
2687 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2688                                   APValue &Value, const FieldDecl *FD) {
2689   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2690 
2691   if (!Value.isInt()) {
2692     // Trying to store a pointer-cast-to-integer into a bitfield.
2693     // FIXME: In this case, we should provide the diagnostic for casting
2694     // a pointer to an integer.
2695     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2696     Info.FFDiag(E);
2697     return false;
2698   }
2699 
2700   APSInt &Int = Value.getInt();
2701   unsigned OldBitWidth = Int.getBitWidth();
2702   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2703   if (NewBitWidth < OldBitWidth)
2704     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2705   return true;
2706 }
2707 
2708 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2709                                   llvm::APInt &Res) {
2710   APValue SVal;
2711   if (!Evaluate(SVal, Info, E))
2712     return false;
2713   if (SVal.isInt()) {
2714     Res = SVal.getInt();
2715     return true;
2716   }
2717   if (SVal.isFloat()) {
2718     Res = SVal.getFloat().bitcastToAPInt();
2719     return true;
2720   }
2721   if (SVal.isVector()) {
2722     QualType VecTy = E->getType();
2723     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2724     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2725     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2726     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2727     Res = llvm::APInt::getZero(VecSize);
2728     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2729       APValue &Elt = SVal.getVectorElt(i);
2730       llvm::APInt EltAsInt;
2731       if (Elt.isInt()) {
2732         EltAsInt = Elt.getInt();
2733       } else if (Elt.isFloat()) {
2734         EltAsInt = Elt.getFloat().bitcastToAPInt();
2735       } else {
2736         // Don't try to handle vectors of anything other than int or float
2737         // (not sure if it's possible to hit this case).
2738         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2739         return false;
2740       }
2741       unsigned BaseEltSize = EltAsInt.getBitWidth();
2742       if (BigEndian)
2743         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2744       else
2745         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2746     }
2747     return true;
2748   }
2749   // Give up if the input isn't an int, float, or vector.  For example, we
2750   // reject "(v4i16)(intptr_t)&a".
2751   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2752   return false;
2753 }
2754 
2755 /// Perform the given integer operation, which is known to need at most BitWidth
2756 /// bits, and check for overflow in the original type (if that type was not an
2757 /// unsigned type).
2758 template<typename Operation>
2759 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2760                                  const APSInt &LHS, const APSInt &RHS,
2761                                  unsigned BitWidth, Operation Op,
2762                                  APSInt &Result) {
2763   if (LHS.isUnsigned()) {
2764     Result = Op(LHS, RHS);
2765     return true;
2766   }
2767 
2768   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2769   Result = Value.trunc(LHS.getBitWidth());
2770   if (Result.extend(BitWidth) != Value) {
2771     if (Info.checkingForUndefinedBehavior())
2772       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2773                                        diag::warn_integer_constant_overflow)
2774           << toString(Result, 10) << E->getType();
2775     return HandleOverflow(Info, E, Value, E->getType());
2776   }
2777   return true;
2778 }
2779 
2780 /// Perform the given binary integer operation.
2781 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2782                               BinaryOperatorKind Opcode, APSInt RHS,
2783                               APSInt &Result) {
2784   bool HandleOverflowResult = true;
2785   switch (Opcode) {
2786   default:
2787     Info.FFDiag(E);
2788     return false;
2789   case BO_Mul:
2790     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2791                                 std::multiplies<APSInt>(), Result);
2792   case BO_Add:
2793     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2794                                 std::plus<APSInt>(), Result);
2795   case BO_Sub:
2796     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2797                                 std::minus<APSInt>(), Result);
2798   case BO_And: Result = LHS & RHS; return true;
2799   case BO_Xor: Result = LHS ^ RHS; return true;
2800   case BO_Or:  Result = LHS | RHS; return true;
2801   case BO_Div:
2802   case BO_Rem:
2803     if (RHS == 0) {
2804       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2805       return false;
2806     }
2807     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2808     // this operation and gives the two's complement result.
2809     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2810         LHS.isMinSignedValue())
2811       HandleOverflowResult = HandleOverflow(
2812           Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2813     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2814     return HandleOverflowResult;
2815   case BO_Shl: {
2816     if (Info.getLangOpts().OpenCL)
2817       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2818       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2819                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2820                     RHS.isUnsigned());
2821     else if (RHS.isSigned() && RHS.isNegative()) {
2822       // During constant-folding, a negative shift is an opposite shift. Such
2823       // a shift is not a constant expression.
2824       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2825       RHS = -RHS;
2826       goto shift_right;
2827     }
2828   shift_left:
2829     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2830     // the shifted type.
2831     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2832     if (SA != RHS) {
2833       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2834         << RHS << E->getType() << LHS.getBitWidth();
2835     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2836       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2837       // operand, and must not overflow the corresponding unsigned type.
2838       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2839       // E1 x 2^E2 module 2^N.
2840       if (LHS.isNegative())
2841         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2842       else if (LHS.countl_zero() < SA)
2843         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2844     }
2845     Result = LHS << SA;
2846     return true;
2847   }
2848   case BO_Shr: {
2849     if (Info.getLangOpts().OpenCL)
2850       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2851       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2852                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2853                     RHS.isUnsigned());
2854     else if (RHS.isSigned() && RHS.isNegative()) {
2855       // During constant-folding, a negative shift is an opposite shift. Such a
2856       // shift is not a constant expression.
2857       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2858       RHS = -RHS;
2859       goto shift_left;
2860     }
2861   shift_right:
2862     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2863     // shifted type.
2864     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2865     if (SA != RHS)
2866       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2867         << RHS << E->getType() << LHS.getBitWidth();
2868     Result = LHS >> SA;
2869     return true;
2870   }
2871 
2872   case BO_LT: Result = LHS < RHS; return true;
2873   case BO_GT: Result = LHS > RHS; return true;
2874   case BO_LE: Result = LHS <= RHS; return true;
2875   case BO_GE: Result = LHS >= RHS; return true;
2876   case BO_EQ: Result = LHS == RHS; return true;
2877   case BO_NE: Result = LHS != RHS; return true;
2878   case BO_Cmp:
2879     llvm_unreachable("BO_Cmp should be handled elsewhere");
2880   }
2881 }
2882 
2883 /// Perform the given binary floating-point operation, in-place, on LHS.
2884 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2885                                   APFloat &LHS, BinaryOperatorKind Opcode,
2886                                   const APFloat &RHS) {
2887   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2888   APFloat::opStatus St;
2889   switch (Opcode) {
2890   default:
2891     Info.FFDiag(E);
2892     return false;
2893   case BO_Mul:
2894     St = LHS.multiply(RHS, RM);
2895     break;
2896   case BO_Add:
2897     St = LHS.add(RHS, RM);
2898     break;
2899   case BO_Sub:
2900     St = LHS.subtract(RHS, RM);
2901     break;
2902   case BO_Div:
2903     // [expr.mul]p4:
2904     //   If the second operand of / or % is zero the behavior is undefined.
2905     if (RHS.isZero())
2906       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2907     St = LHS.divide(RHS, RM);
2908     break;
2909   }
2910 
2911   // [expr.pre]p4:
2912   //   If during the evaluation of an expression, the result is not
2913   //   mathematically defined [...], the behavior is undefined.
2914   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2915   if (LHS.isNaN()) {
2916     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2917     return Info.noteUndefinedBehavior();
2918   }
2919 
2920   return checkFloatingPointResult(Info, E, St);
2921 }
2922 
2923 static bool handleLogicalOpForVector(const APInt &LHSValue,
2924                                      BinaryOperatorKind Opcode,
2925                                      const APInt &RHSValue, APInt &Result) {
2926   bool LHS = (LHSValue != 0);
2927   bool RHS = (RHSValue != 0);
2928 
2929   if (Opcode == BO_LAnd)
2930     Result = LHS && RHS;
2931   else
2932     Result = LHS || RHS;
2933   return true;
2934 }
2935 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2936                                      BinaryOperatorKind Opcode,
2937                                      const APFloat &RHSValue, APInt &Result) {
2938   bool LHS = !LHSValue.isZero();
2939   bool RHS = !RHSValue.isZero();
2940 
2941   if (Opcode == BO_LAnd)
2942     Result = LHS && RHS;
2943   else
2944     Result = LHS || RHS;
2945   return true;
2946 }
2947 
2948 static bool handleLogicalOpForVector(const APValue &LHSValue,
2949                                      BinaryOperatorKind Opcode,
2950                                      const APValue &RHSValue, APInt &Result) {
2951   // The result is always an int type, however operands match the first.
2952   if (LHSValue.getKind() == APValue::Int)
2953     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2954                                     RHSValue.getInt(), Result);
2955   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2956   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2957                                   RHSValue.getFloat(), Result);
2958 }
2959 
2960 template <typename APTy>
2961 static bool
2962 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2963                                const APTy &RHSValue, APInt &Result) {
2964   switch (Opcode) {
2965   default:
2966     llvm_unreachable("unsupported binary operator");
2967   case BO_EQ:
2968     Result = (LHSValue == RHSValue);
2969     break;
2970   case BO_NE:
2971     Result = (LHSValue != RHSValue);
2972     break;
2973   case BO_LT:
2974     Result = (LHSValue < RHSValue);
2975     break;
2976   case BO_GT:
2977     Result = (LHSValue > RHSValue);
2978     break;
2979   case BO_LE:
2980     Result = (LHSValue <= RHSValue);
2981     break;
2982   case BO_GE:
2983     Result = (LHSValue >= RHSValue);
2984     break;
2985   }
2986 
2987   // The boolean operations on these vector types use an instruction that
2988   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2989   // to -1 to make sure that we produce the correct value.
2990   Result.negate();
2991 
2992   return true;
2993 }
2994 
2995 static bool handleCompareOpForVector(const APValue &LHSValue,
2996                                      BinaryOperatorKind Opcode,
2997                                      const APValue &RHSValue, APInt &Result) {
2998   // The result is always an int type, however operands match the first.
2999   if (LHSValue.getKind() == APValue::Int)
3000     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3001                                           RHSValue.getInt(), Result);
3002   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3003   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3004                                         RHSValue.getFloat(), Result);
3005 }
3006 
3007 // Perform binary operations for vector types, in place on the LHS.
3008 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3009                                     BinaryOperatorKind Opcode,
3010                                     APValue &LHSValue,
3011                                     const APValue &RHSValue) {
3012   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3013          "Operation not supported on vector types");
3014 
3015   const auto *VT = E->getType()->castAs<VectorType>();
3016   unsigned NumElements = VT->getNumElements();
3017   QualType EltTy = VT->getElementType();
3018 
3019   // In the cases (typically C as I've observed) where we aren't evaluating
3020   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3021   // just give up.
3022   if (!LHSValue.isVector()) {
3023     assert(LHSValue.isLValue() &&
3024            "A vector result that isn't a vector OR uncalculated LValue");
3025     Info.FFDiag(E);
3026     return false;
3027   }
3028 
3029   assert(LHSValue.getVectorLength() == NumElements &&
3030          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3031 
3032   SmallVector<APValue, 4> ResultElements;
3033 
3034   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3035     APValue LHSElt = LHSValue.getVectorElt(EltNum);
3036     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3037 
3038     if (EltTy->isIntegerType()) {
3039       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3040                        EltTy->isUnsignedIntegerType()};
3041       bool Success = true;
3042 
3043       if (BinaryOperator::isLogicalOp(Opcode))
3044         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3045       else if (BinaryOperator::isComparisonOp(Opcode))
3046         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3047       else
3048         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3049                                     RHSElt.getInt(), EltResult);
3050 
3051       if (!Success) {
3052         Info.FFDiag(E);
3053         return false;
3054       }
3055       ResultElements.emplace_back(EltResult);
3056 
3057     } else if (EltTy->isFloatingType()) {
3058       assert(LHSElt.getKind() == APValue::Float &&
3059              RHSElt.getKind() == APValue::Float &&
3060              "Mismatched LHS/RHS/Result Type");
3061       APFloat LHSFloat = LHSElt.getFloat();
3062 
3063       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3064                                  RHSElt.getFloat())) {
3065         Info.FFDiag(E);
3066         return false;
3067       }
3068 
3069       ResultElements.emplace_back(LHSFloat);
3070     }
3071   }
3072 
3073   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3074   return true;
3075 }
3076 
3077 /// Cast an lvalue referring to a base subobject to a derived class, by
3078 /// truncating the lvalue's path to the given length.
3079 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3080                                const RecordDecl *TruncatedType,
3081                                unsigned TruncatedElements) {
3082   SubobjectDesignator &D = Result.Designator;
3083 
3084   // Check we actually point to a derived class object.
3085   if (TruncatedElements == D.Entries.size())
3086     return true;
3087   assert(TruncatedElements >= D.MostDerivedPathLength &&
3088          "not casting to a derived class");
3089   if (!Result.checkSubobject(Info, E, CSK_Derived))
3090     return false;
3091 
3092   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3093   const RecordDecl *RD = TruncatedType;
3094   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3095     if (RD->isInvalidDecl()) return false;
3096     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3097     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3098     if (isVirtualBaseClass(D.Entries[I]))
3099       Result.Offset -= Layout.getVBaseClassOffset(Base);
3100     else
3101       Result.Offset -= Layout.getBaseClassOffset(Base);
3102     RD = Base;
3103   }
3104   D.Entries.resize(TruncatedElements);
3105   return true;
3106 }
3107 
3108 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3109                                    const CXXRecordDecl *Derived,
3110                                    const CXXRecordDecl *Base,
3111                                    const ASTRecordLayout *RL = nullptr) {
3112   if (!RL) {
3113     if (Derived->isInvalidDecl()) return false;
3114     RL = &Info.Ctx.getASTRecordLayout(Derived);
3115   }
3116 
3117   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3118   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3119   return true;
3120 }
3121 
3122 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3123                              const CXXRecordDecl *DerivedDecl,
3124                              const CXXBaseSpecifier *Base) {
3125   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3126 
3127   if (!Base->isVirtual())
3128     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3129 
3130   SubobjectDesignator &D = Obj.Designator;
3131   if (D.Invalid)
3132     return false;
3133 
3134   // Extract most-derived object and corresponding type.
3135   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3136   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3137     return false;
3138 
3139   // Find the virtual base class.
3140   if (DerivedDecl->isInvalidDecl()) return false;
3141   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3142   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3143   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3144   return true;
3145 }
3146 
3147 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3148                                  QualType Type, LValue &Result) {
3149   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3150                                      PathE = E->path_end();
3151        PathI != PathE; ++PathI) {
3152     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3153                           *PathI))
3154       return false;
3155     Type = (*PathI)->getType();
3156   }
3157   return true;
3158 }
3159 
3160 /// Cast an lvalue referring to a derived class to a known base subobject.
3161 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3162                             const CXXRecordDecl *DerivedRD,
3163                             const CXXRecordDecl *BaseRD) {
3164   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3165                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3166   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3167     llvm_unreachable("Class must be derived from the passed in base class!");
3168 
3169   for (CXXBasePathElement &Elem : Paths.front())
3170     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3171       return false;
3172   return true;
3173 }
3174 
3175 /// Update LVal to refer to the given field, which must be a member of the type
3176 /// currently described by LVal.
3177 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3178                                const FieldDecl *FD,
3179                                const ASTRecordLayout *RL = nullptr) {
3180   if (!RL) {
3181     if (FD->getParent()->isInvalidDecl()) return false;
3182     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3183   }
3184 
3185   unsigned I = FD->getFieldIndex();
3186   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3187   LVal.addDecl(Info, E, FD);
3188   return true;
3189 }
3190 
3191 /// Update LVal to refer to the given indirect field.
3192 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3193                                        LValue &LVal,
3194                                        const IndirectFieldDecl *IFD) {
3195   for (const auto *C : IFD->chain())
3196     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3197       return false;
3198   return true;
3199 }
3200 
3201 /// Get the size of the given type in char units.
3202 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3203                          QualType Type, CharUnits &Size) {
3204   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3205   // extension.
3206   if (Type->isVoidType() || Type->isFunctionType()) {
3207     Size = CharUnits::One();
3208     return true;
3209   }
3210 
3211   if (Type->isDependentType()) {
3212     Info.FFDiag(Loc);
3213     return false;
3214   }
3215 
3216   if (!Type->isConstantSizeType()) {
3217     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3218     // FIXME: Better diagnostic.
3219     Info.FFDiag(Loc);
3220     return false;
3221   }
3222 
3223   Size = Info.Ctx.getTypeSizeInChars(Type);
3224   return true;
3225 }
3226 
3227 /// Update a pointer value to model pointer arithmetic.
3228 /// \param Info - Information about the ongoing evaluation.
3229 /// \param E - The expression being evaluated, for diagnostic purposes.
3230 /// \param LVal - The pointer value to be updated.
3231 /// \param EltTy - The pointee type represented by LVal.
3232 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3233 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3234                                         LValue &LVal, QualType EltTy,
3235                                         APSInt Adjustment) {
3236   CharUnits SizeOfPointee;
3237   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3238     return false;
3239 
3240   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3241   return true;
3242 }
3243 
3244 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3245                                         LValue &LVal, QualType EltTy,
3246                                         int64_t Adjustment) {
3247   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3248                                      APSInt::get(Adjustment));
3249 }
3250 
3251 /// Update an lvalue to refer to a component of a complex number.
3252 /// \param Info - Information about the ongoing evaluation.
3253 /// \param LVal - The lvalue to be updated.
3254 /// \param EltTy - The complex number's component type.
3255 /// \param Imag - False for the real component, true for the imaginary.
3256 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3257                                        LValue &LVal, QualType EltTy,
3258                                        bool Imag) {
3259   if (Imag) {
3260     CharUnits SizeOfComponent;
3261     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3262       return false;
3263     LVal.Offset += SizeOfComponent;
3264   }
3265   LVal.addComplex(Info, E, EltTy, Imag);
3266   return true;
3267 }
3268 
3269 /// Try to evaluate the initializer for a variable declaration.
3270 ///
3271 /// \param Info   Information about the ongoing evaluation.
3272 /// \param E      An expression to be used when printing diagnostics.
3273 /// \param VD     The variable whose initializer should be obtained.
3274 /// \param Version The version of the variable within the frame.
3275 /// \param Frame  The frame in which the variable was created. Must be null
3276 ///               if this variable is not local to the evaluation.
3277 /// \param Result Filled in with a pointer to the value of the variable.
3278 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3279                                 const VarDecl *VD, CallStackFrame *Frame,
3280                                 unsigned Version, APValue *&Result) {
3281   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3282 
3283   // If this is a local variable, dig out its value.
3284   if (Frame) {
3285     Result = Frame->getTemporary(VD, Version);
3286     if (Result)
3287       return true;
3288 
3289     if (!isa<ParmVarDecl>(VD)) {
3290       // Assume variables referenced within a lambda's call operator that were
3291       // not declared within the call operator are captures and during checking
3292       // of a potential constant expression, assume they are unknown constant
3293       // expressions.
3294       assert(isLambdaCallOperator(Frame->Callee) &&
3295              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3296              "missing value for local variable");
3297       if (Info.checkingPotentialConstantExpression())
3298         return false;
3299       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3300       // still reachable at all?
3301       Info.FFDiag(E->getBeginLoc(),
3302                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3303           << "captures not currently allowed";
3304       return false;
3305     }
3306   }
3307 
3308   // If we're currently evaluating the initializer of this declaration, use that
3309   // in-flight value.
3310   if (Info.EvaluatingDecl == Base) {
3311     Result = Info.EvaluatingDeclValue;
3312     return true;
3313   }
3314 
3315   if (isa<ParmVarDecl>(VD)) {
3316     // Assume parameters of a potential constant expression are usable in
3317     // constant expressions.
3318     if (!Info.checkingPotentialConstantExpression() ||
3319         !Info.CurrentCall->Callee ||
3320         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3321       if (Info.getLangOpts().CPlusPlus11) {
3322         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3323             << VD;
3324         NoteLValueLocation(Info, Base);
3325       } else {
3326         Info.FFDiag(E);
3327       }
3328     }
3329     return false;
3330   }
3331 
3332   // Dig out the initializer, and use the declaration which it's attached to.
3333   // FIXME: We should eventually check whether the variable has a reachable
3334   // initializing declaration.
3335   const Expr *Init = VD->getAnyInitializer(VD);
3336   if (!Init) {
3337     // Don't diagnose during potential constant expression checking; an
3338     // initializer might be added later.
3339     if (!Info.checkingPotentialConstantExpression()) {
3340       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3341         << VD;
3342       NoteLValueLocation(Info, Base);
3343     }
3344     return false;
3345   }
3346 
3347   if (Init->isValueDependent()) {
3348     // The DeclRefExpr is not value-dependent, but the variable it refers to
3349     // has a value-dependent initializer. This should only happen in
3350     // constant-folding cases, where the variable is not actually of a suitable
3351     // type for use in a constant expression (otherwise the DeclRefExpr would
3352     // have been value-dependent too), so diagnose that.
3353     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3354     if (!Info.checkingPotentialConstantExpression()) {
3355       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3356                          ? diag::note_constexpr_ltor_non_constexpr
3357                          : diag::note_constexpr_ltor_non_integral, 1)
3358           << VD << VD->getType();
3359       NoteLValueLocation(Info, Base);
3360     }
3361     return false;
3362   }
3363 
3364   // Check that we can fold the initializer. In C++, we will have already done
3365   // this in the cases where it matters for conformance.
3366   if (!VD->evaluateValue()) {
3367     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3368     NoteLValueLocation(Info, Base);
3369     return false;
3370   }
3371 
3372   // Check that the variable is actually usable in constant expressions. For a
3373   // const integral variable or a reference, we might have a non-constant
3374   // initializer that we can nonetheless evaluate the initializer for. Such
3375   // variables are not usable in constant expressions. In C++98, the
3376   // initializer also syntactically needs to be an ICE.
3377   //
3378   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3379   // expressions here; doing so would regress diagnostics for things like
3380   // reading from a volatile constexpr variable.
3381   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3382        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3383       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3384        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3385     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3386     NoteLValueLocation(Info, Base);
3387   }
3388 
3389   // Never use the initializer of a weak variable, not even for constant
3390   // folding. We can't be sure that this is the definition that will be used.
3391   if (VD->isWeak()) {
3392     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3393     NoteLValueLocation(Info, Base);
3394     return false;
3395   }
3396 
3397   Result = VD->getEvaluatedValue();
3398   return true;
3399 }
3400 
3401 /// Get the base index of the given base class within an APValue representing
3402 /// the given derived class.
3403 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3404                              const CXXRecordDecl *Base) {
3405   Base = Base->getCanonicalDecl();
3406   unsigned Index = 0;
3407   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3408          E = Derived->bases_end(); I != E; ++I, ++Index) {
3409     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3410       return Index;
3411   }
3412 
3413   llvm_unreachable("base class missing from derived class's bases list");
3414 }
3415 
3416 /// Extract the value of a character from a string literal.
3417 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3418                                             uint64_t Index) {
3419   assert(!isa<SourceLocExpr>(Lit) &&
3420          "SourceLocExpr should have already been converted to a StringLiteral");
3421 
3422   // FIXME: Support MakeStringConstant
3423   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3424     std::string Str;
3425     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3426     assert(Index <= Str.size() && "Index too large");
3427     return APSInt::getUnsigned(Str.c_str()[Index]);
3428   }
3429 
3430   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3431     Lit = PE->getFunctionName();
3432   const StringLiteral *S = cast<StringLiteral>(Lit);
3433   const ConstantArrayType *CAT =
3434       Info.Ctx.getAsConstantArrayType(S->getType());
3435   assert(CAT && "string literal isn't an array");
3436   QualType CharType = CAT->getElementType();
3437   assert(CharType->isIntegerType() && "unexpected character type");
3438 
3439   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3440                CharType->isUnsignedIntegerType());
3441   if (Index < S->getLength())
3442     Value = S->getCodeUnit(Index);
3443   return Value;
3444 }
3445 
3446 // Expand a string literal into an array of characters.
3447 //
3448 // FIXME: This is inefficient; we should probably introduce something similar
3449 // to the LLVM ConstantDataArray to make this cheaper.
3450 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3451                                 APValue &Result,
3452                                 QualType AllocType = QualType()) {
3453   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3454       AllocType.isNull() ? S->getType() : AllocType);
3455   assert(CAT && "string literal isn't an array");
3456   QualType CharType = CAT->getElementType();
3457   assert(CharType->isIntegerType() && "unexpected character type");
3458 
3459   unsigned Elts = CAT->getSize().getZExtValue();
3460   Result = APValue(APValue::UninitArray(),
3461                    std::min(S->getLength(), Elts), Elts);
3462   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3463                CharType->isUnsignedIntegerType());
3464   if (Result.hasArrayFiller())
3465     Result.getArrayFiller() = APValue(Value);
3466   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3467     Value = S->getCodeUnit(I);
3468     Result.getArrayInitializedElt(I) = APValue(Value);
3469   }
3470 }
3471 
3472 // Expand an array so that it has more than Index filled elements.
3473 static void expandArray(APValue &Array, unsigned Index) {
3474   unsigned Size = Array.getArraySize();
3475   assert(Index < Size);
3476 
3477   // Always at least double the number of elements for which we store a value.
3478   unsigned OldElts = Array.getArrayInitializedElts();
3479   unsigned NewElts = std::max(Index+1, OldElts * 2);
3480   NewElts = std::min(Size, std::max(NewElts, 8u));
3481 
3482   // Copy the data across.
3483   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3484   for (unsigned I = 0; I != OldElts; ++I)
3485     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3486   for (unsigned I = OldElts; I != NewElts; ++I)
3487     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3488   if (NewValue.hasArrayFiller())
3489     NewValue.getArrayFiller() = Array.getArrayFiller();
3490   Array.swap(NewValue);
3491 }
3492 
3493 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3494 /// conversion. If it's of class type, we may assume that the copy operation
3495 /// is trivial. Note that this is never true for a union type with fields
3496 /// (because the copy always "reads" the active member) and always true for
3497 /// a non-class type.
3498 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3499 static bool isReadByLvalueToRvalueConversion(QualType T) {
3500   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3501   return !RD || isReadByLvalueToRvalueConversion(RD);
3502 }
3503 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3504   // FIXME: A trivial copy of a union copies the object representation, even if
3505   // the union is empty.
3506   if (RD->isUnion())
3507     return !RD->field_empty();
3508   if (RD->isEmpty())
3509     return false;
3510 
3511   for (auto *Field : RD->fields())
3512     if (!Field->isUnnamedBitfield() &&
3513         isReadByLvalueToRvalueConversion(Field->getType()))
3514       return true;
3515 
3516   for (auto &BaseSpec : RD->bases())
3517     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3518       return true;
3519 
3520   return false;
3521 }
3522 
3523 /// Diagnose an attempt to read from any unreadable field within the specified
3524 /// type, which might be a class type.
3525 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3526                                   QualType T) {
3527   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3528   if (!RD)
3529     return false;
3530 
3531   if (!RD->hasMutableFields())
3532     return false;
3533 
3534   for (auto *Field : RD->fields()) {
3535     // If we're actually going to read this field in some way, then it can't
3536     // be mutable. If we're in a union, then assigning to a mutable field
3537     // (even an empty one) can change the active member, so that's not OK.
3538     // FIXME: Add core issue number for the union case.
3539     if (Field->isMutable() &&
3540         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3541       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3542       Info.Note(Field->getLocation(), diag::note_declared_at);
3543       return true;
3544     }
3545 
3546     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3547       return true;
3548   }
3549 
3550   for (auto &BaseSpec : RD->bases())
3551     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3552       return true;
3553 
3554   // All mutable fields were empty, and thus not actually read.
3555   return false;
3556 }
3557 
3558 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3559                                         APValue::LValueBase Base,
3560                                         bool MutableSubobject = false) {
3561   // A temporary or transient heap allocation we created.
3562   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3563     return true;
3564 
3565   switch (Info.IsEvaluatingDecl) {
3566   case EvalInfo::EvaluatingDeclKind::None:
3567     return false;
3568 
3569   case EvalInfo::EvaluatingDeclKind::Ctor:
3570     // The variable whose initializer we're evaluating.
3571     if (Info.EvaluatingDecl == Base)
3572       return true;
3573 
3574     // A temporary lifetime-extended by the variable whose initializer we're
3575     // evaluating.
3576     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3577       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3578         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3579     return false;
3580 
3581   case EvalInfo::EvaluatingDeclKind::Dtor:
3582     // C++2a [expr.const]p6:
3583     //   [during constant destruction] the lifetime of a and its non-mutable
3584     //   subobjects (but not its mutable subobjects) [are] considered to start
3585     //   within e.
3586     if (MutableSubobject || Base != Info.EvaluatingDecl)
3587       return false;
3588     // FIXME: We can meaningfully extend this to cover non-const objects, but
3589     // we will need special handling: we should be able to access only
3590     // subobjects of such objects that are themselves declared const.
3591     QualType T = getType(Base);
3592     return T.isConstQualified() || T->isReferenceType();
3593   }
3594 
3595   llvm_unreachable("unknown evaluating decl kind");
3596 }
3597 
3598 namespace {
3599 /// A handle to a complete object (an object that is not a subobject of
3600 /// another object).
3601 struct CompleteObject {
3602   /// The identity of the object.
3603   APValue::LValueBase Base;
3604   /// The value of the complete object.
3605   APValue *Value;
3606   /// The type of the complete object.
3607   QualType Type;
3608 
3609   CompleteObject() : Value(nullptr) {}
3610   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3611       : Base(Base), Value(Value), Type(Type) {}
3612 
3613   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3614     // If this isn't a "real" access (eg, if it's just accessing the type
3615     // info), allow it. We assume the type doesn't change dynamically for
3616     // subobjects of constexpr objects (even though we'd hit UB here if it
3617     // did). FIXME: Is this right?
3618     if (!isAnyAccess(AK))
3619       return true;
3620 
3621     // In C++14 onwards, it is permitted to read a mutable member whose
3622     // lifetime began within the evaluation.
3623     // FIXME: Should we also allow this in C++11?
3624     if (!Info.getLangOpts().CPlusPlus14)
3625       return false;
3626     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3627   }
3628 
3629   explicit operator bool() const { return !Type.isNull(); }
3630 };
3631 } // end anonymous namespace
3632 
3633 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3634                                  bool IsMutable = false) {
3635   // C++ [basic.type.qualifier]p1:
3636   // - A const object is an object of type const T or a non-mutable subobject
3637   //   of a const object.
3638   if (ObjType.isConstQualified() && !IsMutable)
3639     SubobjType.addConst();
3640   // - A volatile object is an object of type const T or a subobject of a
3641   //   volatile object.
3642   if (ObjType.isVolatileQualified())
3643     SubobjType.addVolatile();
3644   return SubobjType;
3645 }
3646 
3647 /// Find the designated sub-object of an rvalue.
3648 template<typename SubobjectHandler>
3649 typename SubobjectHandler::result_type
3650 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3651               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3652   if (Sub.Invalid)
3653     // A diagnostic will have already been produced.
3654     return handler.failed();
3655   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3656     if (Info.getLangOpts().CPlusPlus11)
3657       Info.FFDiag(E, Sub.isOnePastTheEnd()
3658                          ? diag::note_constexpr_access_past_end
3659                          : diag::note_constexpr_access_unsized_array)
3660           << handler.AccessKind;
3661     else
3662       Info.FFDiag(E);
3663     return handler.failed();
3664   }
3665 
3666   APValue *O = Obj.Value;
3667   QualType ObjType = Obj.Type;
3668   const FieldDecl *LastField = nullptr;
3669   const FieldDecl *VolatileField = nullptr;
3670 
3671   // Walk the designator's path to find the subobject.
3672   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3673     // Reading an indeterminate value is undefined, but assigning over one is OK.
3674     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3675         (O->isIndeterminate() &&
3676          !isValidIndeterminateAccess(handler.AccessKind))) {
3677       if (!Info.checkingPotentialConstantExpression())
3678         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3679             << handler.AccessKind << O->isIndeterminate();
3680       return handler.failed();
3681     }
3682 
3683     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3684     //    const and volatile semantics are not applied on an object under
3685     //    {con,de}struction.
3686     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3687         ObjType->isRecordType() &&
3688         Info.isEvaluatingCtorDtor(
3689             Obj.Base,
3690             llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3691             ConstructionPhase::None) {
3692       ObjType = Info.Ctx.getCanonicalType(ObjType);
3693       ObjType.removeLocalConst();
3694       ObjType.removeLocalVolatile();
3695     }
3696 
3697     // If this is our last pass, check that the final object type is OK.
3698     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3699       // Accesses to volatile objects are prohibited.
3700       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3701         if (Info.getLangOpts().CPlusPlus) {
3702           int DiagKind;
3703           SourceLocation Loc;
3704           const NamedDecl *Decl = nullptr;
3705           if (VolatileField) {
3706             DiagKind = 2;
3707             Loc = VolatileField->getLocation();
3708             Decl = VolatileField;
3709           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3710             DiagKind = 1;
3711             Loc = VD->getLocation();
3712             Decl = VD;
3713           } else {
3714             DiagKind = 0;
3715             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3716               Loc = E->getExprLoc();
3717           }
3718           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3719               << handler.AccessKind << DiagKind << Decl;
3720           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3721         } else {
3722           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3723         }
3724         return handler.failed();
3725       }
3726 
3727       // If we are reading an object of class type, there may still be more
3728       // things we need to check: if there are any mutable subobjects, we
3729       // cannot perform this read. (This only happens when performing a trivial
3730       // copy or assignment.)
3731       if (ObjType->isRecordType() &&
3732           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3733           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3734         return handler.failed();
3735     }
3736 
3737     if (I == N) {
3738       if (!handler.found(*O, ObjType))
3739         return false;
3740 
3741       // If we modified a bit-field, truncate it to the right width.
3742       if (isModification(handler.AccessKind) &&
3743           LastField && LastField->isBitField() &&
3744           !truncateBitfieldValue(Info, E, *O, LastField))
3745         return false;
3746 
3747       return true;
3748     }
3749 
3750     LastField = nullptr;
3751     if (ObjType->isArrayType()) {
3752       // Next subobject is an array element.
3753       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3754       assert(CAT && "vla in literal type?");
3755       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3756       if (CAT->getSize().ule(Index)) {
3757         // Note, it should not be possible to form a pointer with a valid
3758         // designator which points more than one past the end of the array.
3759         if (Info.getLangOpts().CPlusPlus11)
3760           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3761             << handler.AccessKind;
3762         else
3763           Info.FFDiag(E);
3764         return handler.failed();
3765       }
3766 
3767       ObjType = CAT->getElementType();
3768 
3769       if (O->getArrayInitializedElts() > Index)
3770         O = &O->getArrayInitializedElt(Index);
3771       else if (!isRead(handler.AccessKind)) {
3772         expandArray(*O, Index);
3773         O = &O->getArrayInitializedElt(Index);
3774       } else
3775         O = &O->getArrayFiller();
3776     } else if (ObjType->isAnyComplexType()) {
3777       // Next subobject is a complex number.
3778       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779       if (Index > 1) {
3780         if (Info.getLangOpts().CPlusPlus11)
3781           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3782             << handler.AccessKind;
3783         else
3784           Info.FFDiag(E);
3785         return handler.failed();
3786       }
3787 
3788       ObjType = getSubobjectType(
3789           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3790 
3791       assert(I == N - 1 && "extracting subobject of scalar?");
3792       if (O->isComplexInt()) {
3793         return handler.found(Index ? O->getComplexIntImag()
3794                                    : O->getComplexIntReal(), ObjType);
3795       } else {
3796         assert(O->isComplexFloat());
3797         return handler.found(Index ? O->getComplexFloatImag()
3798                                    : O->getComplexFloatReal(), ObjType);
3799       }
3800     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3801       if (Field->isMutable() &&
3802           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3803         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3804           << handler.AccessKind << Field;
3805         Info.Note(Field->getLocation(), diag::note_declared_at);
3806         return handler.failed();
3807       }
3808 
3809       // Next subobject is a class, struct or union field.
3810       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3811       if (RD->isUnion()) {
3812         const FieldDecl *UnionField = O->getUnionField();
3813         if (!UnionField ||
3814             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3815           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3816             // Placement new onto an inactive union member makes it active.
3817             O->setUnion(Field, APValue());
3818           } else {
3819             // FIXME: If O->getUnionValue() is absent, report that there's no
3820             // active union member rather than reporting the prior active union
3821             // member. We'll need to fix nullptr_t to not use APValue() as its
3822             // representation first.
3823             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3824                 << handler.AccessKind << Field << !UnionField << UnionField;
3825             return handler.failed();
3826           }
3827         }
3828         O = &O->getUnionValue();
3829       } else
3830         O = &O->getStructField(Field->getFieldIndex());
3831 
3832       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3833       LastField = Field;
3834       if (Field->getType().isVolatileQualified())
3835         VolatileField = Field;
3836     } else {
3837       // Next subobject is a base class.
3838       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3839       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3840       O = &O->getStructBase(getBaseIndex(Derived, Base));
3841 
3842       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3843     }
3844   }
3845 }
3846 
3847 namespace {
3848 struct ExtractSubobjectHandler {
3849   EvalInfo &Info;
3850   const Expr *E;
3851   APValue &Result;
3852   const AccessKinds AccessKind;
3853 
3854   typedef bool result_type;
3855   bool failed() { return false; }
3856   bool found(APValue &Subobj, QualType SubobjType) {
3857     Result = Subobj;
3858     if (AccessKind == AK_ReadObjectRepresentation)
3859       return true;
3860     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3861   }
3862   bool found(APSInt &Value, QualType SubobjType) {
3863     Result = APValue(Value);
3864     return true;
3865   }
3866   bool found(APFloat &Value, QualType SubobjType) {
3867     Result = APValue(Value);
3868     return true;
3869   }
3870 };
3871 } // end anonymous namespace
3872 
3873 /// Extract the designated sub-object of an rvalue.
3874 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3875                              const CompleteObject &Obj,
3876                              const SubobjectDesignator &Sub, APValue &Result,
3877                              AccessKinds AK = AK_Read) {
3878   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3879   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3880   return findSubobject(Info, E, Obj, Sub, Handler);
3881 }
3882 
3883 namespace {
3884 struct ModifySubobjectHandler {
3885   EvalInfo &Info;
3886   APValue &NewVal;
3887   const Expr *E;
3888 
3889   typedef bool result_type;
3890   static const AccessKinds AccessKind = AK_Assign;
3891 
3892   bool checkConst(QualType QT) {
3893     // Assigning to a const object has undefined behavior.
3894     if (QT.isConstQualified()) {
3895       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3896       return false;
3897     }
3898     return true;
3899   }
3900 
3901   bool failed() { return false; }
3902   bool found(APValue &Subobj, QualType SubobjType) {
3903     if (!checkConst(SubobjType))
3904       return false;
3905     // We've been given ownership of NewVal, so just swap it in.
3906     Subobj.swap(NewVal);
3907     return true;
3908   }
3909   bool found(APSInt &Value, QualType SubobjType) {
3910     if (!checkConst(SubobjType))
3911       return false;
3912     if (!NewVal.isInt()) {
3913       // Maybe trying to write a cast pointer value into a complex?
3914       Info.FFDiag(E);
3915       return false;
3916     }
3917     Value = NewVal.getInt();
3918     return true;
3919   }
3920   bool found(APFloat &Value, QualType SubobjType) {
3921     if (!checkConst(SubobjType))
3922       return false;
3923     Value = NewVal.getFloat();
3924     return true;
3925   }
3926 };
3927 } // end anonymous namespace
3928 
3929 const AccessKinds ModifySubobjectHandler::AccessKind;
3930 
3931 /// Update the designated sub-object of an rvalue to the given value.
3932 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3933                             const CompleteObject &Obj,
3934                             const SubobjectDesignator &Sub,
3935                             APValue &NewVal) {
3936   ModifySubobjectHandler Handler = { Info, NewVal, E };
3937   return findSubobject(Info, E, Obj, Sub, Handler);
3938 }
3939 
3940 /// Find the position where two subobject designators diverge, or equivalently
3941 /// the length of the common initial subsequence.
3942 static unsigned FindDesignatorMismatch(QualType ObjType,
3943                                        const SubobjectDesignator &A,
3944                                        const SubobjectDesignator &B,
3945                                        bool &WasArrayIndex) {
3946   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3947   for (/**/; I != N; ++I) {
3948     if (!ObjType.isNull() &&
3949         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3950       // Next subobject is an array element.
3951       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3952         WasArrayIndex = true;
3953         return I;
3954       }
3955       if (ObjType->isAnyComplexType())
3956         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3957       else
3958         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3959     } else {
3960       if (A.Entries[I].getAsBaseOrMember() !=
3961           B.Entries[I].getAsBaseOrMember()) {
3962         WasArrayIndex = false;
3963         return I;
3964       }
3965       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3966         // Next subobject is a field.
3967         ObjType = FD->getType();
3968       else
3969         // Next subobject is a base class.
3970         ObjType = QualType();
3971     }
3972   }
3973   WasArrayIndex = false;
3974   return I;
3975 }
3976 
3977 /// Determine whether the given subobject designators refer to elements of the
3978 /// same array object.
3979 static bool AreElementsOfSameArray(QualType ObjType,
3980                                    const SubobjectDesignator &A,
3981                                    const SubobjectDesignator &B) {
3982   if (A.Entries.size() != B.Entries.size())
3983     return false;
3984 
3985   bool IsArray = A.MostDerivedIsArrayElement;
3986   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3987     // A is a subobject of the array element.
3988     return false;
3989 
3990   // If A (and B) designates an array element, the last entry will be the array
3991   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3992   // of length 1' case, and the entire path must match.
3993   bool WasArrayIndex;
3994   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3995   return CommonLength >= A.Entries.size() - IsArray;
3996 }
3997 
3998 /// Find the complete object to which an LValue refers.
3999 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4000                                          AccessKinds AK, const LValue &LVal,
4001                                          QualType LValType) {
4002   if (LVal.InvalidBase) {
4003     Info.FFDiag(E);
4004     return CompleteObject();
4005   }
4006 
4007   if (!LVal.Base) {
4008     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4009     return CompleteObject();
4010   }
4011 
4012   CallStackFrame *Frame = nullptr;
4013   unsigned Depth = 0;
4014   if (LVal.getLValueCallIndex()) {
4015     std::tie(Frame, Depth) =
4016         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4017     if (!Frame) {
4018       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4019         << AK << LVal.Base.is<const ValueDecl*>();
4020       NoteLValueLocation(Info, LVal.Base);
4021       return CompleteObject();
4022     }
4023   }
4024 
4025   bool IsAccess = isAnyAccess(AK);
4026 
4027   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4028   // is not a constant expression (even if the object is non-volatile). We also
4029   // apply this rule to C++98, in order to conform to the expected 'volatile'
4030   // semantics.
4031   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4032     if (Info.getLangOpts().CPlusPlus)
4033       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4034         << AK << LValType;
4035     else
4036       Info.FFDiag(E);
4037     return CompleteObject();
4038   }
4039 
4040   // Compute value storage location and type of base object.
4041   APValue *BaseVal = nullptr;
4042   QualType BaseType = getType(LVal.Base);
4043 
4044   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4045       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4046     // This is the object whose initializer we're evaluating, so its lifetime
4047     // started in the current evaluation.
4048     BaseVal = Info.EvaluatingDeclValue;
4049   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4050     // Allow reading from a GUID declaration.
4051     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4052       if (isModification(AK)) {
4053         // All the remaining cases do not permit modification of the object.
4054         Info.FFDiag(E, diag::note_constexpr_modify_global);
4055         return CompleteObject();
4056       }
4057       APValue &V = GD->getAsAPValue();
4058       if (V.isAbsent()) {
4059         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4060             << GD->getType();
4061         return CompleteObject();
4062       }
4063       return CompleteObject(LVal.Base, &V, GD->getType());
4064     }
4065 
4066     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4067     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4068       if (isModification(AK)) {
4069         Info.FFDiag(E, diag::note_constexpr_modify_global);
4070         return CompleteObject();
4071       }
4072       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4073                             GCD->getType());
4074     }
4075 
4076     // Allow reading from template parameter objects.
4077     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4078       if (isModification(AK)) {
4079         Info.FFDiag(E, diag::note_constexpr_modify_global);
4080         return CompleteObject();
4081       }
4082       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4083                             TPO->getType());
4084     }
4085 
4086     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4087     // In C++11, constexpr, non-volatile variables initialized with constant
4088     // expressions are constant expressions too. Inside constexpr functions,
4089     // parameters are constant expressions even if they're non-const.
4090     // In C++1y, objects local to a constant expression (those with a Frame) are
4091     // both readable and writable inside constant expressions.
4092     // In C, such things can also be folded, although they are not ICEs.
4093     const VarDecl *VD = dyn_cast<VarDecl>(D);
4094     if (VD) {
4095       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4096         VD = VDef;
4097     }
4098     if (!VD || VD->isInvalidDecl()) {
4099       Info.FFDiag(E);
4100       return CompleteObject();
4101     }
4102 
4103     bool IsConstant = BaseType.isConstant(Info.Ctx);
4104 
4105     // Unless we're looking at a local variable or argument in a constexpr call,
4106     // the variable we're reading must be const.
4107     if (!Frame) {
4108       if (IsAccess && isa<ParmVarDecl>(VD)) {
4109         // Access of a parameter that's not associated with a frame isn't going
4110         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4111         // suitable diagnostic.
4112       } else if (Info.getLangOpts().CPlusPlus14 &&
4113                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4114         // OK, we can read and modify an object if we're in the process of
4115         // evaluating its initializer, because its lifetime began in this
4116         // evaluation.
4117       } else if (isModification(AK)) {
4118         // All the remaining cases do not permit modification of the object.
4119         Info.FFDiag(E, diag::note_constexpr_modify_global);
4120         return CompleteObject();
4121       } else if (VD->isConstexpr()) {
4122         // OK, we can read this variable.
4123       } else if (BaseType->isIntegralOrEnumerationType()) {
4124         if (!IsConstant) {
4125           if (!IsAccess)
4126             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4127           if (Info.getLangOpts().CPlusPlus) {
4128             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4129             Info.Note(VD->getLocation(), diag::note_declared_at);
4130           } else {
4131             Info.FFDiag(E);
4132           }
4133           return CompleteObject();
4134         }
4135       } else if (!IsAccess) {
4136         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4137       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4138                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4139         // This variable might end up being constexpr. Don't diagnose it yet.
4140       } else if (IsConstant) {
4141         // Keep evaluating to see what we can do. In particular, we support
4142         // folding of const floating-point types, in order to make static const
4143         // data members of such types (supported as an extension) more useful.
4144         if (Info.getLangOpts().CPlusPlus) {
4145           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4146                               ? diag::note_constexpr_ltor_non_constexpr
4147                               : diag::note_constexpr_ltor_non_integral, 1)
4148               << VD << BaseType;
4149           Info.Note(VD->getLocation(), diag::note_declared_at);
4150         } else {
4151           Info.CCEDiag(E);
4152         }
4153       } else {
4154         // Never allow reading a non-const value.
4155         if (Info.getLangOpts().CPlusPlus) {
4156           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4157                              ? diag::note_constexpr_ltor_non_constexpr
4158                              : diag::note_constexpr_ltor_non_integral, 1)
4159               << VD << BaseType;
4160           Info.Note(VD->getLocation(), diag::note_declared_at);
4161         } else {
4162           Info.FFDiag(E);
4163         }
4164         return CompleteObject();
4165       }
4166     }
4167 
4168     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4169       return CompleteObject();
4170   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4171     std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4172     if (!Alloc) {
4173       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4174       return CompleteObject();
4175     }
4176     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4177                           LVal.Base.getDynamicAllocType());
4178   } else {
4179     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4180 
4181     if (!Frame) {
4182       if (const MaterializeTemporaryExpr *MTE =
4183               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4184         assert(MTE->getStorageDuration() == SD_Static &&
4185                "should have a frame for a non-global materialized temporary");
4186 
4187         // C++20 [expr.const]p4: [DR2126]
4188         //   An object or reference is usable in constant expressions if it is
4189         //   - a temporary object of non-volatile const-qualified literal type
4190         //     whose lifetime is extended to that of a variable that is usable
4191         //     in constant expressions
4192         //
4193         // C++20 [expr.const]p5:
4194         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4195         //   - a non-volatile glvalue that refers to an object that is usable
4196         //     in constant expressions, or
4197         //   - a non-volatile glvalue of literal type that refers to a
4198         //     non-volatile object whose lifetime began within the evaluation
4199         //     of E;
4200         //
4201         // C++11 misses the 'began within the evaluation of e' check and
4202         // instead allows all temporaries, including things like:
4203         //   int &&r = 1;
4204         //   int x = ++r;
4205         //   constexpr int k = r;
4206         // Therefore we use the C++14-onwards rules in C++11 too.
4207         //
4208         // Note that temporaries whose lifetimes began while evaluating a
4209         // variable's constructor are not usable while evaluating the
4210         // corresponding destructor, not even if they're of const-qualified
4211         // types.
4212         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4213             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4214           if (!IsAccess)
4215             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4216           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4217           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4218           return CompleteObject();
4219         }
4220 
4221         BaseVal = MTE->getOrCreateValue(false);
4222         assert(BaseVal && "got reference to unevaluated temporary");
4223       } else {
4224         if (!IsAccess)
4225           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4226         APValue Val;
4227         LVal.moveInto(Val);
4228         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4229             << AK
4230             << Val.getAsString(Info.Ctx,
4231                                Info.Ctx.getLValueReferenceType(LValType));
4232         NoteLValueLocation(Info, LVal.Base);
4233         return CompleteObject();
4234       }
4235     } else {
4236       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4237       assert(BaseVal && "missing value for temporary");
4238     }
4239   }
4240 
4241   // In C++14, we can't safely access any mutable state when we might be
4242   // evaluating after an unmodeled side effect. Parameters are modeled as state
4243   // in the caller, but aren't visible once the call returns, so they can be
4244   // modified in a speculatively-evaluated call.
4245   //
4246   // FIXME: Not all local state is mutable. Allow local constant subobjects
4247   // to be read here (but take care with 'mutable' fields).
4248   unsigned VisibleDepth = Depth;
4249   if (llvm::isa_and_nonnull<ParmVarDecl>(
4250           LVal.Base.dyn_cast<const ValueDecl *>()))
4251     ++VisibleDepth;
4252   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4253        Info.EvalStatus.HasSideEffects) ||
4254       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4255     return CompleteObject();
4256 
4257   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4258 }
4259 
4260 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4261 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4262 /// glvalue referred to by an entity of reference type.
4263 ///
4264 /// \param Info - Information about the ongoing evaluation.
4265 /// \param Conv - The expression for which we are performing the conversion.
4266 ///               Used for diagnostics.
4267 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4268 ///               case of a non-class type).
4269 /// \param LVal - The glvalue on which we are attempting to perform this action.
4270 /// \param RVal - The produced value will be placed here.
4271 /// \param WantObjectRepresentation - If true, we're looking for the object
4272 ///               representation rather than the value, and in particular,
4273 ///               there is no requirement that the result be fully initialized.
4274 static bool
4275 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4276                                const LValue &LVal, APValue &RVal,
4277                                bool WantObjectRepresentation = false) {
4278   if (LVal.Designator.Invalid)
4279     return false;
4280 
4281   // Check for special cases where there is no existing APValue to look at.
4282   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4283 
4284   AccessKinds AK =
4285       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4286 
4287   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4288     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4289       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4290       // initializer until now for such expressions. Such an expression can't be
4291       // an ICE in C, so this only matters for fold.
4292       if (Type.isVolatileQualified()) {
4293         Info.FFDiag(Conv);
4294         return false;
4295       }
4296 
4297       APValue Lit;
4298       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4299         return false;
4300 
4301       // According to GCC info page:
4302       //
4303       // 6.28 Compound Literals
4304       //
4305       // As an optimization, G++ sometimes gives array compound literals longer
4306       // lifetimes: when the array either appears outside a function or has a
4307       // const-qualified type. If foo and its initializer had elements of type
4308       // char *const rather than char *, or if foo were a global variable, the
4309       // array would have static storage duration. But it is probably safest
4310       // just to avoid the use of array compound literals in C++ code.
4311       //
4312       // Obey that rule by checking constness for converted array types.
4313 
4314       QualType CLETy = CLE->getType();
4315       if (CLETy->isArrayType() && !Type->isArrayType()) {
4316         if (!CLETy.isConstant(Info.Ctx)) {
4317           Info.FFDiag(Conv);
4318           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4319           return false;
4320         }
4321       }
4322 
4323       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4324       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4325     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4326       // Special-case character extraction so we don't have to construct an
4327       // APValue for the whole string.
4328       assert(LVal.Designator.Entries.size() <= 1 &&
4329              "Can only read characters from string literals");
4330       if (LVal.Designator.Entries.empty()) {
4331         // Fail for now for LValue to RValue conversion of an array.
4332         // (This shouldn't show up in C/C++, but it could be triggered by a
4333         // weird EvaluateAsRValue call from a tool.)
4334         Info.FFDiag(Conv);
4335         return false;
4336       }
4337       if (LVal.Designator.isOnePastTheEnd()) {
4338         if (Info.getLangOpts().CPlusPlus11)
4339           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4340         else
4341           Info.FFDiag(Conv);
4342         return false;
4343       }
4344       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4345       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4346       return true;
4347     }
4348   }
4349 
4350   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4351   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4352 }
4353 
4354 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4355 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4356                              QualType LValType, APValue &Val) {
4357   if (LVal.Designator.Invalid)
4358     return false;
4359 
4360   if (!Info.getLangOpts().CPlusPlus14) {
4361     Info.FFDiag(E);
4362     return false;
4363   }
4364 
4365   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4366   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4367 }
4368 
4369 namespace {
4370 struct CompoundAssignSubobjectHandler {
4371   EvalInfo &Info;
4372   const CompoundAssignOperator *E;
4373   QualType PromotedLHSType;
4374   BinaryOperatorKind Opcode;
4375   const APValue &RHS;
4376 
4377   static const AccessKinds AccessKind = AK_Assign;
4378 
4379   typedef bool result_type;
4380 
4381   bool checkConst(QualType QT) {
4382     // Assigning to a const object has undefined behavior.
4383     if (QT.isConstQualified()) {
4384       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4385       return false;
4386     }
4387     return true;
4388   }
4389 
4390   bool failed() { return false; }
4391   bool found(APValue &Subobj, QualType SubobjType) {
4392     switch (Subobj.getKind()) {
4393     case APValue::Int:
4394       return found(Subobj.getInt(), SubobjType);
4395     case APValue::Float:
4396       return found(Subobj.getFloat(), SubobjType);
4397     case APValue::ComplexInt:
4398     case APValue::ComplexFloat:
4399       // FIXME: Implement complex compound assignment.
4400       Info.FFDiag(E);
4401       return false;
4402     case APValue::LValue:
4403       return foundPointer(Subobj, SubobjType);
4404     case APValue::Vector:
4405       return foundVector(Subobj, SubobjType);
4406     default:
4407       // FIXME: can this happen?
4408       Info.FFDiag(E);
4409       return false;
4410     }
4411   }
4412 
4413   bool foundVector(APValue &Value, QualType SubobjType) {
4414     if (!checkConst(SubobjType))
4415       return false;
4416 
4417     if (!SubobjType->isVectorType()) {
4418       Info.FFDiag(E);
4419       return false;
4420     }
4421     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4422   }
4423 
4424   bool found(APSInt &Value, QualType SubobjType) {
4425     if (!checkConst(SubobjType))
4426       return false;
4427 
4428     if (!SubobjType->isIntegerType()) {
4429       // We don't support compound assignment on integer-cast-to-pointer
4430       // values.
4431       Info.FFDiag(E);
4432       return false;
4433     }
4434 
4435     if (RHS.isInt()) {
4436       APSInt LHS =
4437           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4438       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4439         return false;
4440       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4441       return true;
4442     } else if (RHS.isFloat()) {
4443       const FPOptions FPO = E->getFPFeaturesInEffect(
4444                                     Info.Ctx.getLangOpts());
4445       APFloat FValue(0.0);
4446       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4447                                   PromotedLHSType, FValue) &&
4448              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4449              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4450                                   Value);
4451     }
4452 
4453     Info.FFDiag(E);
4454     return false;
4455   }
4456   bool found(APFloat &Value, QualType SubobjType) {
4457     return checkConst(SubobjType) &&
4458            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4459                                   Value) &&
4460            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4461            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4462   }
4463   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4464     if (!checkConst(SubobjType))
4465       return false;
4466 
4467     QualType PointeeType;
4468     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4469       PointeeType = PT->getPointeeType();
4470 
4471     if (PointeeType.isNull() || !RHS.isInt() ||
4472         (Opcode != BO_Add && Opcode != BO_Sub)) {
4473       Info.FFDiag(E);
4474       return false;
4475     }
4476 
4477     APSInt Offset = RHS.getInt();
4478     if (Opcode == BO_Sub)
4479       negateAsSigned(Offset);
4480 
4481     LValue LVal;
4482     LVal.setFrom(Info.Ctx, Subobj);
4483     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4484       return false;
4485     LVal.moveInto(Subobj);
4486     return true;
4487   }
4488 };
4489 } // end anonymous namespace
4490 
4491 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4492 
4493 /// Perform a compound assignment of LVal <op>= RVal.
4494 static bool handleCompoundAssignment(EvalInfo &Info,
4495                                      const CompoundAssignOperator *E,
4496                                      const LValue &LVal, QualType LValType,
4497                                      QualType PromotedLValType,
4498                                      BinaryOperatorKind Opcode,
4499                                      const APValue &RVal) {
4500   if (LVal.Designator.Invalid)
4501     return false;
4502 
4503   if (!Info.getLangOpts().CPlusPlus14) {
4504     Info.FFDiag(E);
4505     return false;
4506   }
4507 
4508   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4509   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4510                                              RVal };
4511   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4512 }
4513 
4514 namespace {
4515 struct IncDecSubobjectHandler {
4516   EvalInfo &Info;
4517   const UnaryOperator *E;
4518   AccessKinds AccessKind;
4519   APValue *Old;
4520 
4521   typedef bool result_type;
4522 
4523   bool checkConst(QualType QT) {
4524     // Assigning to a const object has undefined behavior.
4525     if (QT.isConstQualified()) {
4526       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4527       return false;
4528     }
4529     return true;
4530   }
4531 
4532   bool failed() { return false; }
4533   bool found(APValue &Subobj, QualType SubobjType) {
4534     // Stash the old value. Also clear Old, so we don't clobber it later
4535     // if we're post-incrementing a complex.
4536     if (Old) {
4537       *Old = Subobj;
4538       Old = nullptr;
4539     }
4540 
4541     switch (Subobj.getKind()) {
4542     case APValue::Int:
4543       return found(Subobj.getInt(), SubobjType);
4544     case APValue::Float:
4545       return found(Subobj.getFloat(), SubobjType);
4546     case APValue::ComplexInt:
4547       return found(Subobj.getComplexIntReal(),
4548                    SubobjType->castAs<ComplexType>()->getElementType()
4549                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4550     case APValue::ComplexFloat:
4551       return found(Subobj.getComplexFloatReal(),
4552                    SubobjType->castAs<ComplexType>()->getElementType()
4553                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4554     case APValue::LValue:
4555       return foundPointer(Subobj, SubobjType);
4556     default:
4557       // FIXME: can this happen?
4558       Info.FFDiag(E);
4559       return false;
4560     }
4561   }
4562   bool found(APSInt &Value, QualType SubobjType) {
4563     if (!checkConst(SubobjType))
4564       return false;
4565 
4566     if (!SubobjType->isIntegerType()) {
4567       // We don't support increment / decrement on integer-cast-to-pointer
4568       // values.
4569       Info.FFDiag(E);
4570       return false;
4571     }
4572 
4573     if (Old) *Old = APValue(Value);
4574 
4575     // bool arithmetic promotes to int, and the conversion back to bool
4576     // doesn't reduce mod 2^n, so special-case it.
4577     if (SubobjType->isBooleanType()) {
4578       if (AccessKind == AK_Increment)
4579         Value = 1;
4580       else
4581         Value = !Value;
4582       return true;
4583     }
4584 
4585     bool WasNegative = Value.isNegative();
4586     if (AccessKind == AK_Increment) {
4587       ++Value;
4588 
4589       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4590         APSInt ActualValue(Value, /*IsUnsigned*/true);
4591         return HandleOverflow(Info, E, ActualValue, SubobjType);
4592       }
4593     } else {
4594       --Value;
4595 
4596       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4597         unsigned BitWidth = Value.getBitWidth();
4598         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4599         ActualValue.setBit(BitWidth);
4600         return HandleOverflow(Info, E, ActualValue, SubobjType);
4601       }
4602     }
4603     return true;
4604   }
4605   bool found(APFloat &Value, QualType SubobjType) {
4606     if (!checkConst(SubobjType))
4607       return false;
4608 
4609     if (Old) *Old = APValue(Value);
4610 
4611     APFloat One(Value.getSemantics(), 1);
4612     if (AccessKind == AK_Increment)
4613       Value.add(One, APFloat::rmNearestTiesToEven);
4614     else
4615       Value.subtract(One, APFloat::rmNearestTiesToEven);
4616     return true;
4617   }
4618   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4619     if (!checkConst(SubobjType))
4620       return false;
4621 
4622     QualType PointeeType;
4623     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4624       PointeeType = PT->getPointeeType();
4625     else {
4626       Info.FFDiag(E);
4627       return false;
4628     }
4629 
4630     LValue LVal;
4631     LVal.setFrom(Info.Ctx, Subobj);
4632     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4633                                      AccessKind == AK_Increment ? 1 : -1))
4634       return false;
4635     LVal.moveInto(Subobj);
4636     return true;
4637   }
4638 };
4639 } // end anonymous namespace
4640 
4641 /// Perform an increment or decrement on LVal.
4642 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4643                          QualType LValType, bool IsIncrement, APValue *Old) {
4644   if (LVal.Designator.Invalid)
4645     return false;
4646 
4647   if (!Info.getLangOpts().CPlusPlus14) {
4648     Info.FFDiag(E);
4649     return false;
4650   }
4651 
4652   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4653   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4654   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4655   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4656 }
4657 
4658 /// Build an lvalue for the object argument of a member function call.
4659 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4660                                    LValue &This) {
4661   if (Object->getType()->isPointerType() && Object->isPRValue())
4662     return EvaluatePointer(Object, This, Info);
4663 
4664   if (Object->isGLValue())
4665     return EvaluateLValue(Object, This, Info);
4666 
4667   if (Object->getType()->isLiteralType(Info.Ctx))
4668     return EvaluateTemporary(Object, This, Info);
4669 
4670   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4671   return false;
4672 }
4673 
4674 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4675 /// lvalue referring to the result.
4676 ///
4677 /// \param Info - Information about the ongoing evaluation.
4678 /// \param LV - An lvalue referring to the base of the member pointer.
4679 /// \param RHS - The member pointer expression.
4680 /// \param IncludeMember - Specifies whether the member itself is included in
4681 ///        the resulting LValue subobject designator. This is not possible when
4682 ///        creating a bound member function.
4683 /// \return The field or method declaration to which the member pointer refers,
4684 ///         or 0 if evaluation fails.
4685 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4686                                                   QualType LVType,
4687                                                   LValue &LV,
4688                                                   const Expr *RHS,
4689                                                   bool IncludeMember = true) {
4690   MemberPtr MemPtr;
4691   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4692     return nullptr;
4693 
4694   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4695   // member value, the behavior is undefined.
4696   if (!MemPtr.getDecl()) {
4697     // FIXME: Specific diagnostic.
4698     Info.FFDiag(RHS);
4699     return nullptr;
4700   }
4701 
4702   if (MemPtr.isDerivedMember()) {
4703     // This is a member of some derived class. Truncate LV appropriately.
4704     // The end of the derived-to-base path for the base object must match the
4705     // derived-to-base path for the member pointer.
4706     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4707         LV.Designator.Entries.size()) {
4708       Info.FFDiag(RHS);
4709       return nullptr;
4710     }
4711     unsigned PathLengthToMember =
4712         LV.Designator.Entries.size() - MemPtr.Path.size();
4713     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4714       const CXXRecordDecl *LVDecl = getAsBaseClass(
4715           LV.Designator.Entries[PathLengthToMember + I]);
4716       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4717       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4718         Info.FFDiag(RHS);
4719         return nullptr;
4720       }
4721     }
4722 
4723     // Truncate the lvalue to the appropriate derived class.
4724     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4725                             PathLengthToMember))
4726       return nullptr;
4727   } else if (!MemPtr.Path.empty()) {
4728     // Extend the LValue path with the member pointer's path.
4729     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4730                                   MemPtr.Path.size() + IncludeMember);
4731 
4732     // Walk down to the appropriate base class.
4733     if (const PointerType *PT = LVType->getAs<PointerType>())
4734       LVType = PT->getPointeeType();
4735     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4736     assert(RD && "member pointer access on non-class-type expression");
4737     // The first class in the path is that of the lvalue.
4738     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4739       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4740       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4741         return nullptr;
4742       RD = Base;
4743     }
4744     // Finally cast to the class containing the member.
4745     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4746                                 MemPtr.getContainingRecord()))
4747       return nullptr;
4748   }
4749 
4750   // Add the member. Note that we cannot build bound member functions here.
4751   if (IncludeMember) {
4752     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4753       if (!HandleLValueMember(Info, RHS, LV, FD))
4754         return nullptr;
4755     } else if (const IndirectFieldDecl *IFD =
4756                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4757       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4758         return nullptr;
4759     } else {
4760       llvm_unreachable("can't construct reference to bound member function");
4761     }
4762   }
4763 
4764   return MemPtr.getDecl();
4765 }
4766 
4767 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4768                                                   const BinaryOperator *BO,
4769                                                   LValue &LV,
4770                                                   bool IncludeMember = true) {
4771   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4772 
4773   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4774     if (Info.noteFailure()) {
4775       MemberPtr MemPtr;
4776       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4777     }
4778     return nullptr;
4779   }
4780 
4781   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4782                                    BO->getRHS(), IncludeMember);
4783 }
4784 
4785 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4786 /// the provided lvalue, which currently refers to the base object.
4787 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4788                                     LValue &Result) {
4789   SubobjectDesignator &D = Result.Designator;
4790   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4791     return false;
4792 
4793   QualType TargetQT = E->getType();
4794   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4795     TargetQT = PT->getPointeeType();
4796 
4797   // Check this cast lands within the final derived-to-base subobject path.
4798   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4799     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4800       << D.MostDerivedType << TargetQT;
4801     return false;
4802   }
4803 
4804   // Check the type of the final cast. We don't need to check the path,
4805   // since a cast can only be formed if the path is unique.
4806   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4807   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4808   const CXXRecordDecl *FinalType;
4809   if (NewEntriesSize == D.MostDerivedPathLength)
4810     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4811   else
4812     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4813   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4814     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4815       << D.MostDerivedType << TargetQT;
4816     return false;
4817   }
4818 
4819   // Truncate the lvalue to the appropriate derived class.
4820   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4821 }
4822 
4823 /// Get the value to use for a default-initialized object of type T.
4824 /// Return false if it encounters something invalid.
4825 static bool getDefaultInitValue(QualType T, APValue &Result) {
4826   bool Success = true;
4827   if (auto *RD = T->getAsCXXRecordDecl()) {
4828     if (RD->isInvalidDecl()) {
4829       Result = APValue();
4830       return false;
4831     }
4832     if (RD->isUnion()) {
4833       Result = APValue((const FieldDecl *)nullptr);
4834       return true;
4835     }
4836     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4837                      std::distance(RD->field_begin(), RD->field_end()));
4838 
4839     unsigned Index = 0;
4840     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4841                                                   End = RD->bases_end();
4842          I != End; ++I, ++Index)
4843       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4844 
4845     for (const auto *I : RD->fields()) {
4846       if (I->isUnnamedBitfield())
4847         continue;
4848       Success &= getDefaultInitValue(I->getType(),
4849                                      Result.getStructField(I->getFieldIndex()));
4850     }
4851     return Success;
4852   }
4853 
4854   if (auto *AT =
4855           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4856     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4857     if (Result.hasArrayFiller())
4858       Success &=
4859           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4860 
4861     return Success;
4862   }
4863 
4864   Result = APValue::IndeterminateValue();
4865   return true;
4866 }
4867 
4868 namespace {
4869 enum EvalStmtResult {
4870   /// Evaluation failed.
4871   ESR_Failed,
4872   /// Hit a 'return' statement.
4873   ESR_Returned,
4874   /// Evaluation succeeded.
4875   ESR_Succeeded,
4876   /// Hit a 'continue' statement.
4877   ESR_Continue,
4878   /// Hit a 'break' statement.
4879   ESR_Break,
4880   /// Still scanning for 'case' or 'default' statement.
4881   ESR_CaseNotFound
4882 };
4883 }
4884 
4885 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4886   if (VD->isInvalidDecl())
4887     return false;
4888   // We don't need to evaluate the initializer for a static local.
4889   if (!VD->hasLocalStorage())
4890     return true;
4891 
4892   LValue Result;
4893   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4894                                                    ScopeKind::Block, Result);
4895 
4896   const Expr *InitE = VD->getInit();
4897   if (!InitE) {
4898     if (VD->getType()->isDependentType())
4899       return Info.noteSideEffect();
4900     return getDefaultInitValue(VD->getType(), Val);
4901   }
4902   if (InitE->isValueDependent())
4903     return false;
4904 
4905   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4906     // Wipe out any partially-computed value, to allow tracking that this
4907     // evaluation failed.
4908     Val = APValue();
4909     return false;
4910   }
4911 
4912   return true;
4913 }
4914 
4915 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4916   bool OK = true;
4917 
4918   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4919     OK &= EvaluateVarDecl(Info, VD);
4920 
4921   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4922     for (auto *BD : DD->bindings())
4923       if (auto *VD = BD->getHoldingVar())
4924         OK &= EvaluateDecl(Info, VD);
4925 
4926   return OK;
4927 }
4928 
4929 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4930   assert(E->isValueDependent());
4931   if (Info.noteSideEffect())
4932     return true;
4933   assert(E->containsErrors() && "valid value-dependent expression should never "
4934                                 "reach invalid code path.");
4935   return false;
4936 }
4937 
4938 /// Evaluate a condition (either a variable declaration or an expression).
4939 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4940                          const Expr *Cond, bool &Result) {
4941   if (Cond->isValueDependent())
4942     return false;
4943   FullExpressionRAII Scope(Info);
4944   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4945     return false;
4946   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4947     return false;
4948   return Scope.destroy();
4949 }
4950 
4951 namespace {
4952 /// A location where the result (returned value) of evaluating a
4953 /// statement should be stored.
4954 struct StmtResult {
4955   /// The APValue that should be filled in with the returned value.
4956   APValue &Value;
4957   /// The location containing the result, if any (used to support RVO).
4958   const LValue *Slot;
4959 };
4960 
4961 struct TempVersionRAII {
4962   CallStackFrame &Frame;
4963 
4964   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4965     Frame.pushTempVersion();
4966   }
4967 
4968   ~TempVersionRAII() {
4969     Frame.popTempVersion();
4970   }
4971 };
4972 
4973 }
4974 
4975 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4976                                    const Stmt *S,
4977                                    const SwitchCase *SC = nullptr);
4978 
4979 /// Evaluate the body of a loop, and translate the result as appropriate.
4980 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4981                                        const Stmt *Body,
4982                                        const SwitchCase *Case = nullptr) {
4983   BlockScopeRAII Scope(Info);
4984 
4985   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4986   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4987     ESR = ESR_Failed;
4988 
4989   switch (ESR) {
4990   case ESR_Break:
4991     return ESR_Succeeded;
4992   case ESR_Succeeded:
4993   case ESR_Continue:
4994     return ESR_Continue;
4995   case ESR_Failed:
4996   case ESR_Returned:
4997   case ESR_CaseNotFound:
4998     return ESR;
4999   }
5000   llvm_unreachable("Invalid EvalStmtResult!");
5001 }
5002 
5003 /// Evaluate a switch statement.
5004 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5005                                      const SwitchStmt *SS) {
5006   BlockScopeRAII Scope(Info);
5007 
5008   // Evaluate the switch condition.
5009   APSInt Value;
5010   {
5011     if (const Stmt *Init = SS->getInit()) {
5012       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5013       if (ESR != ESR_Succeeded) {
5014         if (ESR != ESR_Failed && !Scope.destroy())
5015           ESR = ESR_Failed;
5016         return ESR;
5017       }
5018     }
5019 
5020     FullExpressionRAII CondScope(Info);
5021     if (SS->getConditionVariable() &&
5022         !EvaluateDecl(Info, SS->getConditionVariable()))
5023       return ESR_Failed;
5024     if (SS->getCond()->isValueDependent()) {
5025       // We don't know what the value is, and which branch should jump to.
5026       EvaluateDependentExpr(SS->getCond(), Info);
5027       return ESR_Failed;
5028     }
5029     if (!EvaluateInteger(SS->getCond(), Value, Info))
5030       return ESR_Failed;
5031 
5032     if (!CondScope.destroy())
5033       return ESR_Failed;
5034   }
5035 
5036   // Find the switch case corresponding to the value of the condition.
5037   // FIXME: Cache this lookup.
5038   const SwitchCase *Found = nullptr;
5039   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5040        SC = SC->getNextSwitchCase()) {
5041     if (isa<DefaultStmt>(SC)) {
5042       Found = SC;
5043       continue;
5044     }
5045 
5046     const CaseStmt *CS = cast<CaseStmt>(SC);
5047     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5048     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5049                               : LHS;
5050     if (LHS <= Value && Value <= RHS) {
5051       Found = SC;
5052       break;
5053     }
5054   }
5055 
5056   if (!Found)
5057     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5058 
5059   // Search the switch body for the switch case and evaluate it from there.
5060   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5061   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5062     return ESR_Failed;
5063 
5064   switch (ESR) {
5065   case ESR_Break:
5066     return ESR_Succeeded;
5067   case ESR_Succeeded:
5068   case ESR_Continue:
5069   case ESR_Failed:
5070   case ESR_Returned:
5071     return ESR;
5072   case ESR_CaseNotFound:
5073     // This can only happen if the switch case is nested within a statement
5074     // expression. We have no intention of supporting that.
5075     Info.FFDiag(Found->getBeginLoc(),
5076                 diag::note_constexpr_stmt_expr_unsupported);
5077     return ESR_Failed;
5078   }
5079   llvm_unreachable("Invalid EvalStmtResult!");
5080 }
5081 
5082 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5083   // An expression E is a core constant expression unless the evaluation of E
5084   // would evaluate one of the following: [C++23] - a control flow that passes
5085   // through a declaration of a variable with static or thread storage duration
5086   // unless that variable is usable in constant expressions.
5087   if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5088       !VD->isUsableInConstantExpressions(Info.Ctx)) {
5089     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5090         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5091     return false;
5092   }
5093   return true;
5094 }
5095 
5096 // Evaluate a statement.
5097 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5098                                    const Stmt *S, const SwitchCase *Case) {
5099   if (!Info.nextStep(S))
5100     return ESR_Failed;
5101 
5102   // If we're hunting down a 'case' or 'default' label, recurse through
5103   // substatements until we hit the label.
5104   if (Case) {
5105     switch (S->getStmtClass()) {
5106     case Stmt::CompoundStmtClass:
5107       // FIXME: Precompute which substatement of a compound statement we
5108       // would jump to, and go straight there rather than performing a
5109       // linear scan each time.
5110     case Stmt::LabelStmtClass:
5111     case Stmt::AttributedStmtClass:
5112     case Stmt::DoStmtClass:
5113       break;
5114 
5115     case Stmt::CaseStmtClass:
5116     case Stmt::DefaultStmtClass:
5117       if (Case == S)
5118         Case = nullptr;
5119       break;
5120 
5121     case Stmt::IfStmtClass: {
5122       // FIXME: Precompute which side of an 'if' we would jump to, and go
5123       // straight there rather than scanning both sides.
5124       const IfStmt *IS = cast<IfStmt>(S);
5125 
5126       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5127       // preceded by our switch label.
5128       BlockScopeRAII Scope(Info);
5129 
5130       // Step into the init statement in case it brings an (uninitialized)
5131       // variable into scope.
5132       if (const Stmt *Init = IS->getInit()) {
5133         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5134         if (ESR != ESR_CaseNotFound) {
5135           assert(ESR != ESR_Succeeded);
5136           return ESR;
5137         }
5138       }
5139 
5140       // Condition variable must be initialized if it exists.
5141       // FIXME: We can skip evaluating the body if there's a condition
5142       // variable, as there can't be any case labels within it.
5143       // (The same is true for 'for' statements.)
5144 
5145       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5146       if (ESR == ESR_Failed)
5147         return ESR;
5148       if (ESR != ESR_CaseNotFound)
5149         return Scope.destroy() ? ESR : ESR_Failed;
5150       if (!IS->getElse())
5151         return ESR_CaseNotFound;
5152 
5153       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5154       if (ESR == ESR_Failed)
5155         return ESR;
5156       if (ESR != ESR_CaseNotFound)
5157         return Scope.destroy() ? ESR : ESR_Failed;
5158       return ESR_CaseNotFound;
5159     }
5160 
5161     case Stmt::WhileStmtClass: {
5162       EvalStmtResult ESR =
5163           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5164       if (ESR != ESR_Continue)
5165         return ESR;
5166       break;
5167     }
5168 
5169     case Stmt::ForStmtClass: {
5170       const ForStmt *FS = cast<ForStmt>(S);
5171       BlockScopeRAII Scope(Info);
5172 
5173       // Step into the init statement in case it brings an (uninitialized)
5174       // variable into scope.
5175       if (const Stmt *Init = FS->getInit()) {
5176         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5177         if (ESR != ESR_CaseNotFound) {
5178           assert(ESR != ESR_Succeeded);
5179           return ESR;
5180         }
5181       }
5182 
5183       EvalStmtResult ESR =
5184           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5185       if (ESR != ESR_Continue)
5186         return ESR;
5187       if (const auto *Inc = FS->getInc()) {
5188         if (Inc->isValueDependent()) {
5189           if (!EvaluateDependentExpr(Inc, Info))
5190             return ESR_Failed;
5191         } else {
5192           FullExpressionRAII IncScope(Info);
5193           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5194             return ESR_Failed;
5195         }
5196       }
5197       break;
5198     }
5199 
5200     case Stmt::DeclStmtClass: {
5201       // Start the lifetime of any uninitialized variables we encounter. They
5202       // might be used by the selected branch of the switch.
5203       const DeclStmt *DS = cast<DeclStmt>(S);
5204       for (const auto *D : DS->decls()) {
5205         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5206           if (!CheckLocalVariableDeclaration(Info, VD))
5207             return ESR_Failed;
5208           if (VD->hasLocalStorage() && !VD->getInit())
5209             if (!EvaluateVarDecl(Info, VD))
5210               return ESR_Failed;
5211           // FIXME: If the variable has initialization that can't be jumped
5212           // over, bail out of any immediately-surrounding compound-statement
5213           // too. There can't be any case labels here.
5214         }
5215       }
5216       return ESR_CaseNotFound;
5217     }
5218 
5219     default:
5220       return ESR_CaseNotFound;
5221     }
5222   }
5223 
5224   switch (S->getStmtClass()) {
5225   default:
5226     if (const Expr *E = dyn_cast<Expr>(S)) {
5227       if (E->isValueDependent()) {
5228         if (!EvaluateDependentExpr(E, Info))
5229           return ESR_Failed;
5230       } else {
5231         // Don't bother evaluating beyond an expression-statement which couldn't
5232         // be evaluated.
5233         // FIXME: Do we need the FullExpressionRAII object here?
5234         // VisitExprWithCleanups should create one when necessary.
5235         FullExpressionRAII Scope(Info);
5236         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5237           return ESR_Failed;
5238       }
5239       return ESR_Succeeded;
5240     }
5241 
5242     Info.FFDiag(S->getBeginLoc());
5243     return ESR_Failed;
5244 
5245   case Stmt::NullStmtClass:
5246     return ESR_Succeeded;
5247 
5248   case Stmt::DeclStmtClass: {
5249     const DeclStmt *DS = cast<DeclStmt>(S);
5250     for (const auto *D : DS->decls()) {
5251       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5252       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5253         return ESR_Failed;
5254       // Each declaration initialization is its own full-expression.
5255       FullExpressionRAII Scope(Info);
5256       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5257         return ESR_Failed;
5258       if (!Scope.destroy())
5259         return ESR_Failed;
5260     }
5261     return ESR_Succeeded;
5262   }
5263 
5264   case Stmt::ReturnStmtClass: {
5265     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5266     FullExpressionRAII Scope(Info);
5267     if (RetExpr && RetExpr->isValueDependent()) {
5268       EvaluateDependentExpr(RetExpr, Info);
5269       // We know we returned, but we don't know what the value is.
5270       return ESR_Failed;
5271     }
5272     if (RetExpr &&
5273         !(Result.Slot
5274               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5275               : Evaluate(Result.Value, Info, RetExpr)))
5276       return ESR_Failed;
5277     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5278   }
5279 
5280   case Stmt::CompoundStmtClass: {
5281     BlockScopeRAII Scope(Info);
5282 
5283     const CompoundStmt *CS = cast<CompoundStmt>(S);
5284     for (const auto *BI : CS->body()) {
5285       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5286       if (ESR == ESR_Succeeded)
5287         Case = nullptr;
5288       else if (ESR != ESR_CaseNotFound) {
5289         if (ESR != ESR_Failed && !Scope.destroy())
5290           return ESR_Failed;
5291         return ESR;
5292       }
5293     }
5294     if (Case)
5295       return ESR_CaseNotFound;
5296     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5297   }
5298 
5299   case Stmt::IfStmtClass: {
5300     const IfStmt *IS = cast<IfStmt>(S);
5301 
5302     // Evaluate the condition, as either a var decl or as an expression.
5303     BlockScopeRAII Scope(Info);
5304     if (const Stmt *Init = IS->getInit()) {
5305       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5306       if (ESR != ESR_Succeeded) {
5307         if (ESR != ESR_Failed && !Scope.destroy())
5308           return ESR_Failed;
5309         return ESR;
5310       }
5311     }
5312     bool Cond;
5313     if (IS->isConsteval()) {
5314       Cond = IS->isNonNegatedConsteval();
5315       // If we are not in a constant context, if consteval should not evaluate
5316       // to true.
5317       if (!Info.InConstantContext)
5318         Cond = !Cond;
5319     } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5320                              Cond))
5321       return ESR_Failed;
5322 
5323     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5324       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5325       if (ESR != ESR_Succeeded) {
5326         if (ESR != ESR_Failed && !Scope.destroy())
5327           return ESR_Failed;
5328         return ESR;
5329       }
5330     }
5331     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5332   }
5333 
5334   case Stmt::WhileStmtClass: {
5335     const WhileStmt *WS = cast<WhileStmt>(S);
5336     while (true) {
5337       BlockScopeRAII Scope(Info);
5338       bool Continue;
5339       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5340                         Continue))
5341         return ESR_Failed;
5342       if (!Continue)
5343         break;
5344 
5345       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5346       if (ESR != ESR_Continue) {
5347         if (ESR != ESR_Failed && !Scope.destroy())
5348           return ESR_Failed;
5349         return ESR;
5350       }
5351       if (!Scope.destroy())
5352         return ESR_Failed;
5353     }
5354     return ESR_Succeeded;
5355   }
5356 
5357   case Stmt::DoStmtClass: {
5358     const DoStmt *DS = cast<DoStmt>(S);
5359     bool Continue;
5360     do {
5361       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5362       if (ESR != ESR_Continue)
5363         return ESR;
5364       Case = nullptr;
5365 
5366       if (DS->getCond()->isValueDependent()) {
5367         EvaluateDependentExpr(DS->getCond(), Info);
5368         // Bailout as we don't know whether to keep going or terminate the loop.
5369         return ESR_Failed;
5370       }
5371       FullExpressionRAII CondScope(Info);
5372       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5373           !CondScope.destroy())
5374         return ESR_Failed;
5375     } while (Continue);
5376     return ESR_Succeeded;
5377   }
5378 
5379   case Stmt::ForStmtClass: {
5380     const ForStmt *FS = cast<ForStmt>(S);
5381     BlockScopeRAII ForScope(Info);
5382     if (FS->getInit()) {
5383       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5384       if (ESR != ESR_Succeeded) {
5385         if (ESR != ESR_Failed && !ForScope.destroy())
5386           return ESR_Failed;
5387         return ESR;
5388       }
5389     }
5390     while (true) {
5391       BlockScopeRAII IterScope(Info);
5392       bool Continue = true;
5393       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5394                                          FS->getCond(), Continue))
5395         return ESR_Failed;
5396       if (!Continue)
5397         break;
5398 
5399       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5400       if (ESR != ESR_Continue) {
5401         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5402           return ESR_Failed;
5403         return ESR;
5404       }
5405 
5406       if (const auto *Inc = FS->getInc()) {
5407         if (Inc->isValueDependent()) {
5408           if (!EvaluateDependentExpr(Inc, Info))
5409             return ESR_Failed;
5410         } else {
5411           FullExpressionRAII IncScope(Info);
5412           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5413             return ESR_Failed;
5414         }
5415       }
5416 
5417       if (!IterScope.destroy())
5418         return ESR_Failed;
5419     }
5420     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5421   }
5422 
5423   case Stmt::CXXForRangeStmtClass: {
5424     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5425     BlockScopeRAII Scope(Info);
5426 
5427     // Evaluate the init-statement if present.
5428     if (FS->getInit()) {
5429       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5430       if (ESR != ESR_Succeeded) {
5431         if (ESR != ESR_Failed && !Scope.destroy())
5432           return ESR_Failed;
5433         return ESR;
5434       }
5435     }
5436 
5437     // Initialize the __range variable.
5438     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5439     if (ESR != ESR_Succeeded) {
5440       if (ESR != ESR_Failed && !Scope.destroy())
5441         return ESR_Failed;
5442       return ESR;
5443     }
5444 
5445     // In error-recovery cases it's possible to get here even if we failed to
5446     // synthesize the __begin and __end variables.
5447     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5448       return ESR_Failed;
5449 
5450     // Create the __begin and __end iterators.
5451     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5452     if (ESR != ESR_Succeeded) {
5453       if (ESR != ESR_Failed && !Scope.destroy())
5454         return ESR_Failed;
5455       return ESR;
5456     }
5457     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5458     if (ESR != ESR_Succeeded) {
5459       if (ESR != ESR_Failed && !Scope.destroy())
5460         return ESR_Failed;
5461       return ESR;
5462     }
5463 
5464     while (true) {
5465       // Condition: __begin != __end.
5466       {
5467         if (FS->getCond()->isValueDependent()) {
5468           EvaluateDependentExpr(FS->getCond(), Info);
5469           // We don't know whether to keep going or terminate the loop.
5470           return ESR_Failed;
5471         }
5472         bool Continue = true;
5473         FullExpressionRAII CondExpr(Info);
5474         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5475           return ESR_Failed;
5476         if (!Continue)
5477           break;
5478       }
5479 
5480       // User's variable declaration, initialized by *__begin.
5481       BlockScopeRAII InnerScope(Info);
5482       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5483       if (ESR != ESR_Succeeded) {
5484         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5485           return ESR_Failed;
5486         return ESR;
5487       }
5488 
5489       // Loop body.
5490       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5491       if (ESR != ESR_Continue) {
5492         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5493           return ESR_Failed;
5494         return ESR;
5495       }
5496       if (FS->getInc()->isValueDependent()) {
5497         if (!EvaluateDependentExpr(FS->getInc(), Info))
5498           return ESR_Failed;
5499       } else {
5500         // Increment: ++__begin
5501         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5502           return ESR_Failed;
5503       }
5504 
5505       if (!InnerScope.destroy())
5506         return ESR_Failed;
5507     }
5508 
5509     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5510   }
5511 
5512   case Stmt::SwitchStmtClass:
5513     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5514 
5515   case Stmt::ContinueStmtClass:
5516     return ESR_Continue;
5517 
5518   case Stmt::BreakStmtClass:
5519     return ESR_Break;
5520 
5521   case Stmt::LabelStmtClass:
5522     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5523 
5524   case Stmt::AttributedStmtClass:
5525     // As a general principle, C++11 attributes can be ignored without
5526     // any semantic impact.
5527     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5528                         Case);
5529 
5530   case Stmt::CaseStmtClass:
5531   case Stmt::DefaultStmtClass:
5532     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5533   case Stmt::CXXTryStmtClass:
5534     // Evaluate try blocks by evaluating all sub statements.
5535     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5536   }
5537 }
5538 
5539 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5540 /// default constructor. If so, we'll fold it whether or not it's marked as
5541 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5542 /// so we need special handling.
5543 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5544                                            const CXXConstructorDecl *CD,
5545                                            bool IsValueInitialization) {
5546   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5547     return false;
5548 
5549   // Value-initialization does not call a trivial default constructor, so such a
5550   // call is a core constant expression whether or not the constructor is
5551   // constexpr.
5552   if (!CD->isConstexpr() && !IsValueInitialization) {
5553     if (Info.getLangOpts().CPlusPlus11) {
5554       // FIXME: If DiagDecl is an implicitly-declared special member function,
5555       // we should be much more explicit about why it's not constexpr.
5556       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5557         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5558       Info.Note(CD->getLocation(), diag::note_declared_at);
5559     } else {
5560       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5561     }
5562   }
5563   return true;
5564 }
5565 
5566 /// CheckConstexprFunction - Check that a function can be called in a constant
5567 /// expression.
5568 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5569                                    const FunctionDecl *Declaration,
5570                                    const FunctionDecl *Definition,
5571                                    const Stmt *Body) {
5572   // Potential constant expressions can contain calls to declared, but not yet
5573   // defined, constexpr functions.
5574   if (Info.checkingPotentialConstantExpression() && !Definition &&
5575       Declaration->isConstexpr())
5576     return false;
5577 
5578   // Bail out if the function declaration itself is invalid.  We will
5579   // have produced a relevant diagnostic while parsing it, so just
5580   // note the problematic sub-expression.
5581   if (Declaration->isInvalidDecl()) {
5582     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5583     return false;
5584   }
5585 
5586   // DR1872: An instantiated virtual constexpr function can't be called in a
5587   // constant expression (prior to C++20). We can still constant-fold such a
5588   // call.
5589   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5590       cast<CXXMethodDecl>(Declaration)->isVirtual())
5591     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5592 
5593   if (Definition && Definition->isInvalidDecl()) {
5594     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5595     return false;
5596   }
5597 
5598   // Can we evaluate this function call?
5599   if (Definition && Definition->isConstexpr() && Body)
5600     return true;
5601 
5602   if (Info.getLangOpts().CPlusPlus11) {
5603     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5604 
5605     // If this function is not constexpr because it is an inherited
5606     // non-constexpr constructor, diagnose that directly.
5607     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5608     if (CD && CD->isInheritingConstructor()) {
5609       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5610       if (!Inherited->isConstexpr())
5611         DiagDecl = CD = Inherited;
5612     }
5613 
5614     // FIXME: If DiagDecl is an implicitly-declared special member function
5615     // or an inheriting constructor, we should be much more explicit about why
5616     // it's not constexpr.
5617     if (CD && CD->isInheritingConstructor())
5618       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5619         << CD->getInheritedConstructor().getConstructor()->getParent();
5620     else
5621       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5622         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5623     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5624   } else {
5625     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5626   }
5627   return false;
5628 }
5629 
5630 namespace {
5631 struct CheckDynamicTypeHandler {
5632   AccessKinds AccessKind;
5633   typedef bool result_type;
5634   bool failed() { return false; }
5635   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5636   bool found(APSInt &Value, QualType SubobjType) { return true; }
5637   bool found(APFloat &Value, QualType SubobjType) { return true; }
5638 };
5639 } // end anonymous namespace
5640 
5641 /// Check that we can access the notional vptr of an object / determine its
5642 /// dynamic type.
5643 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5644                              AccessKinds AK, bool Polymorphic) {
5645   if (This.Designator.Invalid)
5646     return false;
5647 
5648   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5649 
5650   if (!Obj)
5651     return false;
5652 
5653   if (!Obj.Value) {
5654     // The object is not usable in constant expressions, so we can't inspect
5655     // its value to see if it's in-lifetime or what the active union members
5656     // are. We can still check for a one-past-the-end lvalue.
5657     if (This.Designator.isOnePastTheEnd() ||
5658         This.Designator.isMostDerivedAnUnsizedArray()) {
5659       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5660                          ? diag::note_constexpr_access_past_end
5661                          : diag::note_constexpr_access_unsized_array)
5662           << AK;
5663       return false;
5664     } else if (Polymorphic) {
5665       // Conservatively refuse to perform a polymorphic operation if we would
5666       // not be able to read a notional 'vptr' value.
5667       APValue Val;
5668       This.moveInto(Val);
5669       QualType StarThisType =
5670           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5671       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5672           << AK << Val.getAsString(Info.Ctx, StarThisType);
5673       return false;
5674     }
5675     return true;
5676   }
5677 
5678   CheckDynamicTypeHandler Handler{AK};
5679   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5680 }
5681 
5682 /// Check that the pointee of the 'this' pointer in a member function call is
5683 /// either within its lifetime or in its period of construction or destruction.
5684 static bool
5685 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5686                                      const LValue &This,
5687                                      const CXXMethodDecl *NamedMember) {
5688   return checkDynamicType(
5689       Info, E, This,
5690       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5691 }
5692 
5693 struct DynamicType {
5694   /// The dynamic class type of the object.
5695   const CXXRecordDecl *Type;
5696   /// The corresponding path length in the lvalue.
5697   unsigned PathLength;
5698 };
5699 
5700 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5701                                              unsigned PathLength) {
5702   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5703       Designator.Entries.size() && "invalid path length");
5704   return (PathLength == Designator.MostDerivedPathLength)
5705              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5706              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5707 }
5708 
5709 /// Determine the dynamic type of an object.
5710 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5711                                                      const Expr *E,
5712                                                      LValue &This,
5713                                                      AccessKinds AK) {
5714   // If we don't have an lvalue denoting an object of class type, there is no
5715   // meaningful dynamic type. (We consider objects of non-class type to have no
5716   // dynamic type.)
5717   if (!checkDynamicType(Info, E, This, AK, true))
5718     return std::nullopt;
5719 
5720   // Refuse to compute a dynamic type in the presence of virtual bases. This
5721   // shouldn't happen other than in constant-folding situations, since literal
5722   // types can't have virtual bases.
5723   //
5724   // Note that consumers of DynamicType assume that the type has no virtual
5725   // bases, and will need modifications if this restriction is relaxed.
5726   const CXXRecordDecl *Class =
5727       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5728   if (!Class || Class->getNumVBases()) {
5729     Info.FFDiag(E);
5730     return std::nullopt;
5731   }
5732 
5733   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5734   // binary search here instead. But the overwhelmingly common case is that
5735   // we're not in the middle of a constructor, so it probably doesn't matter
5736   // in practice.
5737   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5738   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5739        PathLength <= Path.size(); ++PathLength) {
5740     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5741                                       Path.slice(0, PathLength))) {
5742     case ConstructionPhase::Bases:
5743     case ConstructionPhase::DestroyingBases:
5744       // We're constructing or destroying a base class. This is not the dynamic
5745       // type.
5746       break;
5747 
5748     case ConstructionPhase::None:
5749     case ConstructionPhase::AfterBases:
5750     case ConstructionPhase::AfterFields:
5751     case ConstructionPhase::Destroying:
5752       // We've finished constructing the base classes and not yet started
5753       // destroying them again, so this is the dynamic type.
5754       return DynamicType{getBaseClassType(This.Designator, PathLength),
5755                          PathLength};
5756     }
5757   }
5758 
5759   // CWG issue 1517: we're constructing a base class of the object described by
5760   // 'This', so that object has not yet begun its period of construction and
5761   // any polymorphic operation on it results in undefined behavior.
5762   Info.FFDiag(E);
5763   return std::nullopt;
5764 }
5765 
5766 /// Perform virtual dispatch.
5767 static const CXXMethodDecl *HandleVirtualDispatch(
5768     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5769     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5770   std::optional<DynamicType> DynType = ComputeDynamicType(
5771       Info, E, This,
5772       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5773   if (!DynType)
5774     return nullptr;
5775 
5776   // Find the final overrider. It must be declared in one of the classes on the
5777   // path from the dynamic type to the static type.
5778   // FIXME: If we ever allow literal types to have virtual base classes, that
5779   // won't be true.
5780   const CXXMethodDecl *Callee = Found;
5781   unsigned PathLength = DynType->PathLength;
5782   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5783     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5784     const CXXMethodDecl *Overrider =
5785         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5786     if (Overrider) {
5787       Callee = Overrider;
5788       break;
5789     }
5790   }
5791 
5792   // C++2a [class.abstract]p6:
5793   //   the effect of making a virtual call to a pure virtual function [...] is
5794   //   undefined
5795   if (Callee->isPure()) {
5796     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5797     Info.Note(Callee->getLocation(), diag::note_declared_at);
5798     return nullptr;
5799   }
5800 
5801   // If necessary, walk the rest of the path to determine the sequence of
5802   // covariant adjustment steps to apply.
5803   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5804                                        Found->getReturnType())) {
5805     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5806     for (unsigned CovariantPathLength = PathLength + 1;
5807          CovariantPathLength != This.Designator.Entries.size();
5808          ++CovariantPathLength) {
5809       const CXXRecordDecl *NextClass =
5810           getBaseClassType(This.Designator, CovariantPathLength);
5811       const CXXMethodDecl *Next =
5812           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5813       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5814                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5815         CovariantAdjustmentPath.push_back(Next->getReturnType());
5816     }
5817     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5818                                          CovariantAdjustmentPath.back()))
5819       CovariantAdjustmentPath.push_back(Found->getReturnType());
5820   }
5821 
5822   // Perform 'this' adjustment.
5823   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5824     return nullptr;
5825 
5826   return Callee;
5827 }
5828 
5829 /// Perform the adjustment from a value returned by a virtual function to
5830 /// a value of the statically expected type, which may be a pointer or
5831 /// reference to a base class of the returned type.
5832 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5833                                             APValue &Result,
5834                                             ArrayRef<QualType> Path) {
5835   assert(Result.isLValue() &&
5836          "unexpected kind of APValue for covariant return");
5837   if (Result.isNullPointer())
5838     return true;
5839 
5840   LValue LVal;
5841   LVal.setFrom(Info.Ctx, Result);
5842 
5843   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5844   for (unsigned I = 1; I != Path.size(); ++I) {
5845     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5846     assert(OldClass && NewClass && "unexpected kind of covariant return");
5847     if (OldClass != NewClass &&
5848         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5849       return false;
5850     OldClass = NewClass;
5851   }
5852 
5853   LVal.moveInto(Result);
5854   return true;
5855 }
5856 
5857 /// Determine whether \p Base, which is known to be a direct base class of
5858 /// \p Derived, is a public base class.
5859 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5860                               const CXXRecordDecl *Base) {
5861   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5862     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5863     if (BaseClass && declaresSameEntity(BaseClass, Base))
5864       return BaseSpec.getAccessSpecifier() == AS_public;
5865   }
5866   llvm_unreachable("Base is not a direct base of Derived");
5867 }
5868 
5869 /// Apply the given dynamic cast operation on the provided lvalue.
5870 ///
5871 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5872 /// to find a suitable target subobject.
5873 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5874                               LValue &Ptr) {
5875   // We can't do anything with a non-symbolic pointer value.
5876   SubobjectDesignator &D = Ptr.Designator;
5877   if (D.Invalid)
5878     return false;
5879 
5880   // C++ [expr.dynamic.cast]p6:
5881   //   If v is a null pointer value, the result is a null pointer value.
5882   if (Ptr.isNullPointer() && !E->isGLValue())
5883     return true;
5884 
5885   // For all the other cases, we need the pointer to point to an object within
5886   // its lifetime / period of construction / destruction, and we need to know
5887   // its dynamic type.
5888   std::optional<DynamicType> DynType =
5889       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5890   if (!DynType)
5891     return false;
5892 
5893   // C++ [expr.dynamic.cast]p7:
5894   //   If T is "pointer to cv void", then the result is a pointer to the most
5895   //   derived object
5896   if (E->getType()->isVoidPointerType())
5897     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5898 
5899   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5900   assert(C && "dynamic_cast target is not void pointer nor class");
5901   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5902 
5903   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5904     // C++ [expr.dynamic.cast]p9:
5905     if (!E->isGLValue()) {
5906       //   The value of a failed cast to pointer type is the null pointer value
5907       //   of the required result type.
5908       Ptr.setNull(Info.Ctx, E->getType());
5909       return true;
5910     }
5911 
5912     //   A failed cast to reference type throws [...] std::bad_cast.
5913     unsigned DiagKind;
5914     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5915                    DynType->Type->isDerivedFrom(C)))
5916       DiagKind = 0;
5917     else if (!Paths || Paths->begin() == Paths->end())
5918       DiagKind = 1;
5919     else if (Paths->isAmbiguous(CQT))
5920       DiagKind = 2;
5921     else {
5922       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5923       DiagKind = 3;
5924     }
5925     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5926         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5927         << Info.Ctx.getRecordType(DynType->Type)
5928         << E->getType().getUnqualifiedType();
5929     return false;
5930   };
5931 
5932   // Runtime check, phase 1:
5933   //   Walk from the base subobject towards the derived object looking for the
5934   //   target type.
5935   for (int PathLength = Ptr.Designator.Entries.size();
5936        PathLength >= (int)DynType->PathLength; --PathLength) {
5937     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5938     if (declaresSameEntity(Class, C))
5939       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5940     // We can only walk across public inheritance edges.
5941     if (PathLength > (int)DynType->PathLength &&
5942         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5943                            Class))
5944       return RuntimeCheckFailed(nullptr);
5945   }
5946 
5947   // Runtime check, phase 2:
5948   //   Search the dynamic type for an unambiguous public base of type C.
5949   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5950                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5951   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5952       Paths.front().Access == AS_public) {
5953     // Downcast to the dynamic type...
5954     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5955       return false;
5956     // ... then upcast to the chosen base class subobject.
5957     for (CXXBasePathElement &Elem : Paths.front())
5958       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5959         return false;
5960     return true;
5961   }
5962 
5963   // Otherwise, the runtime check fails.
5964   return RuntimeCheckFailed(&Paths);
5965 }
5966 
5967 namespace {
5968 struct StartLifetimeOfUnionMemberHandler {
5969   EvalInfo &Info;
5970   const Expr *LHSExpr;
5971   const FieldDecl *Field;
5972   bool DuringInit;
5973   bool Failed = false;
5974   static const AccessKinds AccessKind = AK_Assign;
5975 
5976   typedef bool result_type;
5977   bool failed() { return Failed; }
5978   bool found(APValue &Subobj, QualType SubobjType) {
5979     // We are supposed to perform no initialization but begin the lifetime of
5980     // the object. We interpret that as meaning to do what default
5981     // initialization of the object would do if all constructors involved were
5982     // trivial:
5983     //  * All base, non-variant member, and array element subobjects' lifetimes
5984     //    begin
5985     //  * No variant members' lifetimes begin
5986     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5987     assert(SubobjType->isUnionType());
5988     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5989       // This union member is already active. If it's also in-lifetime, there's
5990       // nothing to do.
5991       if (Subobj.getUnionValue().hasValue())
5992         return true;
5993     } else if (DuringInit) {
5994       // We're currently in the process of initializing a different union
5995       // member.  If we carried on, that initialization would attempt to
5996       // store to an inactive union member, resulting in undefined behavior.
5997       Info.FFDiag(LHSExpr,
5998                   diag::note_constexpr_union_member_change_during_init);
5999       return false;
6000     }
6001     APValue Result;
6002     Failed = !getDefaultInitValue(Field->getType(), Result);
6003     Subobj.setUnion(Field, Result);
6004     return true;
6005   }
6006   bool found(APSInt &Value, QualType SubobjType) {
6007     llvm_unreachable("wrong value kind for union object");
6008   }
6009   bool found(APFloat &Value, QualType SubobjType) {
6010     llvm_unreachable("wrong value kind for union object");
6011   }
6012 };
6013 } // end anonymous namespace
6014 
6015 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6016 
6017 /// Handle a builtin simple-assignment or a call to a trivial assignment
6018 /// operator whose left-hand side might involve a union member access. If it
6019 /// does, implicitly start the lifetime of any accessed union elements per
6020 /// C++20 [class.union]5.
6021 static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6022                                                const Expr *LHSExpr,
6023                                                const LValue &LHS) {
6024   if (LHS.InvalidBase || LHS.Designator.Invalid)
6025     return false;
6026 
6027   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6028   // C++ [class.union]p5:
6029   //   define the set S(E) of subexpressions of E as follows:
6030   unsigned PathLength = LHS.Designator.Entries.size();
6031   for (const Expr *E = LHSExpr; E != nullptr;) {
6032     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
6033     if (auto *ME = dyn_cast<MemberExpr>(E)) {
6034       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6035       // Note that we can't implicitly start the lifetime of a reference,
6036       // so we don't need to proceed any further if we reach one.
6037       if (!FD || FD->getType()->isReferenceType())
6038         break;
6039 
6040       //    ... and also contains A.B if B names a union member ...
6041       if (FD->getParent()->isUnion()) {
6042         //    ... of a non-class, non-array type, or of a class type with a
6043         //    trivial default constructor that is not deleted, or an array of
6044         //    such types.
6045         auto *RD =
6046             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6047         if (!RD || RD->hasTrivialDefaultConstructor())
6048           UnionPathLengths.push_back({PathLength - 1, FD});
6049       }
6050 
6051       E = ME->getBase();
6052       --PathLength;
6053       assert(declaresSameEntity(FD,
6054                                 LHS.Designator.Entries[PathLength]
6055                                     .getAsBaseOrMember().getPointer()));
6056 
6057       //   -- If E is of the form A[B] and is interpreted as a built-in array
6058       //      subscripting operator, S(E) is [S(the array operand, if any)].
6059     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6060       // Step over an ArrayToPointerDecay implicit cast.
6061       auto *Base = ASE->getBase()->IgnoreImplicit();
6062       if (!Base->getType()->isArrayType())
6063         break;
6064 
6065       E = Base;
6066       --PathLength;
6067 
6068     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6069       // Step over a derived-to-base conversion.
6070       E = ICE->getSubExpr();
6071       if (ICE->getCastKind() == CK_NoOp)
6072         continue;
6073       if (ICE->getCastKind() != CK_DerivedToBase &&
6074           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6075         break;
6076       // Walk path backwards as we walk up from the base to the derived class.
6077       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6078         if (Elt->isVirtual()) {
6079           // A class with virtual base classes never has a trivial default
6080           // constructor, so S(E) is empty in this case.
6081           E = nullptr;
6082           break;
6083         }
6084 
6085         --PathLength;
6086         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6087                                   LHS.Designator.Entries[PathLength]
6088                                       .getAsBaseOrMember().getPointer()));
6089       }
6090 
6091     //   -- Otherwise, S(E) is empty.
6092     } else {
6093       break;
6094     }
6095   }
6096 
6097   // Common case: no unions' lifetimes are started.
6098   if (UnionPathLengths.empty())
6099     return true;
6100 
6101   //   if modification of X [would access an inactive union member], an object
6102   //   of the type of X is implicitly created
6103   CompleteObject Obj =
6104       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6105   if (!Obj)
6106     return false;
6107   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6108            llvm::reverse(UnionPathLengths)) {
6109     // Form a designator for the union object.
6110     SubobjectDesignator D = LHS.Designator;
6111     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6112 
6113     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6114                       ConstructionPhase::AfterBases;
6115     StartLifetimeOfUnionMemberHandler StartLifetime{
6116         Info, LHSExpr, LengthAndField.second, DuringInit};
6117     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6118       return false;
6119   }
6120 
6121   return true;
6122 }
6123 
6124 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6125                             CallRef Call, EvalInfo &Info,
6126                             bool NonNull = false) {
6127   LValue LV;
6128   // Create the parameter slot and register its destruction. For a vararg
6129   // argument, create a temporary.
6130   // FIXME: For calling conventions that destroy parameters in the callee,
6131   // should we consider performing destruction when the function returns
6132   // instead?
6133   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6134                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6135                                                        ScopeKind::Call, LV);
6136   if (!EvaluateInPlace(V, Info, LV, Arg))
6137     return false;
6138 
6139   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6140   // undefined behavior, so is non-constant.
6141   if (NonNull && V.isLValue() && V.isNullPointer()) {
6142     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6143     return false;
6144   }
6145 
6146   return true;
6147 }
6148 
6149 /// Evaluate the arguments to a function call.
6150 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6151                          EvalInfo &Info, const FunctionDecl *Callee,
6152                          bool RightToLeft = false) {
6153   bool Success = true;
6154   llvm::SmallBitVector ForbiddenNullArgs;
6155   if (Callee->hasAttr<NonNullAttr>()) {
6156     ForbiddenNullArgs.resize(Args.size());
6157     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6158       if (!Attr->args_size()) {
6159         ForbiddenNullArgs.set();
6160         break;
6161       } else
6162         for (auto Idx : Attr->args()) {
6163           unsigned ASTIdx = Idx.getASTIndex();
6164           if (ASTIdx >= Args.size())
6165             continue;
6166           ForbiddenNullArgs[ASTIdx] = true;
6167         }
6168     }
6169   }
6170   for (unsigned I = 0; I < Args.size(); I++) {
6171     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6172     const ParmVarDecl *PVD =
6173         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6174     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6175     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6176       // If we're checking for a potential constant expression, evaluate all
6177       // initializers even if some of them fail.
6178       if (!Info.noteFailure())
6179         return false;
6180       Success = false;
6181     }
6182   }
6183   return Success;
6184 }
6185 
6186 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6187 /// constructor or assignment operator.
6188 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6189                               const Expr *E, APValue &Result,
6190                               bool CopyObjectRepresentation) {
6191   // Find the reference argument.
6192   CallStackFrame *Frame = Info.CurrentCall;
6193   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6194   if (!RefValue) {
6195     Info.FFDiag(E);
6196     return false;
6197   }
6198 
6199   // Copy out the contents of the RHS object.
6200   LValue RefLValue;
6201   RefLValue.setFrom(Info.Ctx, *RefValue);
6202   return handleLValueToRValueConversion(
6203       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6204       CopyObjectRepresentation);
6205 }
6206 
6207 /// Evaluate a function call.
6208 static bool HandleFunctionCall(SourceLocation CallLoc,
6209                                const FunctionDecl *Callee, const LValue *This,
6210                                const Expr *E, ArrayRef<const Expr *> Args,
6211                                CallRef Call, const Stmt *Body, EvalInfo &Info,
6212                                APValue &Result, const LValue *ResultSlot) {
6213   if (!Info.CheckCallLimit(CallLoc))
6214     return false;
6215 
6216   CallStackFrame Frame(Info, CallLoc, Callee, This, E, Call);
6217 
6218   // For a trivial copy or move assignment, perform an APValue copy. This is
6219   // essential for unions, where the operations performed by the assignment
6220   // operator cannot be represented as statements.
6221   //
6222   // Skip this for non-union classes with no fields; in that case, the defaulted
6223   // copy/move does not actually read the object.
6224   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6225   if (MD && MD->isDefaulted() &&
6226       (MD->getParent()->isUnion() ||
6227        (MD->isTrivial() &&
6228         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6229     assert(This &&
6230            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6231     APValue RHSValue;
6232     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6233                            MD->getParent()->isUnion()))
6234       return false;
6235     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6236                           RHSValue))
6237       return false;
6238     This->moveInto(Result);
6239     return true;
6240   } else if (MD && isLambdaCallOperator(MD)) {
6241     // We're in a lambda; determine the lambda capture field maps unless we're
6242     // just constexpr checking a lambda's call operator. constexpr checking is
6243     // done before the captures have been added to the closure object (unless
6244     // we're inferring constexpr-ness), so we don't have access to them in this
6245     // case. But since we don't need the captures to constexpr check, we can
6246     // just ignore them.
6247     if (!Info.checkingPotentialConstantExpression())
6248       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6249                                         Frame.LambdaThisCaptureField);
6250   }
6251 
6252   StmtResult Ret = {Result, ResultSlot};
6253   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6254   if (ESR == ESR_Succeeded) {
6255     if (Callee->getReturnType()->isVoidType())
6256       return true;
6257     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6258   }
6259   return ESR == ESR_Returned;
6260 }
6261 
6262 /// Evaluate a constructor call.
6263 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6264                                   CallRef Call,
6265                                   const CXXConstructorDecl *Definition,
6266                                   EvalInfo &Info, APValue &Result) {
6267   SourceLocation CallLoc = E->getExprLoc();
6268   if (!Info.CheckCallLimit(CallLoc))
6269     return false;
6270 
6271   const CXXRecordDecl *RD = Definition->getParent();
6272   if (RD->getNumVBases()) {
6273     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6274     return false;
6275   }
6276 
6277   EvalInfo::EvaluatingConstructorRAII EvalObj(
6278       Info,
6279       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6280       RD->getNumBases());
6281   CallStackFrame Frame(Info, CallLoc, Definition, &This, E, Call);
6282 
6283   // FIXME: Creating an APValue just to hold a nonexistent return value is
6284   // wasteful.
6285   APValue RetVal;
6286   StmtResult Ret = {RetVal, nullptr};
6287 
6288   // If it's a delegating constructor, delegate.
6289   if (Definition->isDelegatingConstructor()) {
6290     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6291     if ((*I)->getInit()->isValueDependent()) {
6292       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6293         return false;
6294     } else {
6295       FullExpressionRAII InitScope(Info);
6296       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6297           !InitScope.destroy())
6298         return false;
6299     }
6300     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6301   }
6302 
6303   // For a trivial copy or move constructor, perform an APValue copy. This is
6304   // essential for unions (or classes with anonymous union members), where the
6305   // operations performed by the constructor cannot be represented by
6306   // ctor-initializers.
6307   //
6308   // Skip this for empty non-union classes; we should not perform an
6309   // lvalue-to-rvalue conversion on them because their copy constructor does not
6310   // actually read them.
6311   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6312       (Definition->getParent()->isUnion() ||
6313        (Definition->isTrivial() &&
6314         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6315     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6316                              Definition->getParent()->isUnion());
6317   }
6318 
6319   // Reserve space for the struct members.
6320   if (!Result.hasValue()) {
6321     if (!RD->isUnion())
6322       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6323                        std::distance(RD->field_begin(), RD->field_end()));
6324     else
6325       // A union starts with no active member.
6326       Result = APValue((const FieldDecl*)nullptr);
6327   }
6328 
6329   if (RD->isInvalidDecl()) return false;
6330   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6331 
6332   // A scope for temporaries lifetime-extended by reference members.
6333   BlockScopeRAII LifetimeExtendedScope(Info);
6334 
6335   bool Success = true;
6336   unsigned BasesSeen = 0;
6337 #ifndef NDEBUG
6338   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6339 #endif
6340   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6341   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6342     // We might be initializing the same field again if this is an indirect
6343     // field initialization.
6344     if (FieldIt == RD->field_end() ||
6345         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6346       assert(Indirect && "fields out of order?");
6347       return;
6348     }
6349 
6350     // Default-initialize any fields with no explicit initializer.
6351     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6352       assert(FieldIt != RD->field_end() && "missing field?");
6353       if (!FieldIt->isUnnamedBitfield())
6354         Success &= getDefaultInitValue(
6355             FieldIt->getType(),
6356             Result.getStructField(FieldIt->getFieldIndex()));
6357     }
6358     ++FieldIt;
6359   };
6360   for (const auto *I : Definition->inits()) {
6361     LValue Subobject = This;
6362     LValue SubobjectParent = This;
6363     APValue *Value = &Result;
6364 
6365     // Determine the subobject to initialize.
6366     FieldDecl *FD = nullptr;
6367     if (I->isBaseInitializer()) {
6368       QualType BaseType(I->getBaseClass(), 0);
6369 #ifndef NDEBUG
6370       // Non-virtual base classes are initialized in the order in the class
6371       // definition. We have already checked for virtual base classes.
6372       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6373       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6374              "base class initializers not in expected order");
6375       ++BaseIt;
6376 #endif
6377       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6378                                   BaseType->getAsCXXRecordDecl(), &Layout))
6379         return false;
6380       Value = &Result.getStructBase(BasesSeen++);
6381     } else if ((FD = I->getMember())) {
6382       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6383         return false;
6384       if (RD->isUnion()) {
6385         Result = APValue(FD);
6386         Value = &Result.getUnionValue();
6387       } else {
6388         SkipToField(FD, false);
6389         Value = &Result.getStructField(FD->getFieldIndex());
6390       }
6391     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6392       // Walk the indirect field decl's chain to find the object to initialize,
6393       // and make sure we've initialized every step along it.
6394       auto IndirectFieldChain = IFD->chain();
6395       for (auto *C : IndirectFieldChain) {
6396         FD = cast<FieldDecl>(C);
6397         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6398         // Switch the union field if it differs. This happens if we had
6399         // preceding zero-initialization, and we're now initializing a union
6400         // subobject other than the first.
6401         // FIXME: In this case, the values of the other subobjects are
6402         // specified, since zero-initialization sets all padding bits to zero.
6403         if (!Value->hasValue() ||
6404             (Value->isUnion() && Value->getUnionField() != FD)) {
6405           if (CD->isUnion())
6406             *Value = APValue(FD);
6407           else
6408             // FIXME: This immediately starts the lifetime of all members of
6409             // an anonymous struct. It would be preferable to strictly start
6410             // member lifetime in initialization order.
6411             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6412         }
6413         // Store Subobject as its parent before updating it for the last element
6414         // in the chain.
6415         if (C == IndirectFieldChain.back())
6416           SubobjectParent = Subobject;
6417         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6418           return false;
6419         if (CD->isUnion())
6420           Value = &Value->getUnionValue();
6421         else {
6422           if (C == IndirectFieldChain.front() && !RD->isUnion())
6423             SkipToField(FD, true);
6424           Value = &Value->getStructField(FD->getFieldIndex());
6425         }
6426       }
6427     } else {
6428       llvm_unreachable("unknown base initializer kind");
6429     }
6430 
6431     // Need to override This for implicit field initializers as in this case
6432     // This refers to innermost anonymous struct/union containing initializer,
6433     // not to currently constructed class.
6434     const Expr *Init = I->getInit();
6435     if (Init->isValueDependent()) {
6436       if (!EvaluateDependentExpr(Init, Info))
6437         return false;
6438     } else {
6439       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6440                                     isa<CXXDefaultInitExpr>(Init));
6441       FullExpressionRAII InitScope(Info);
6442       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6443           (FD && FD->isBitField() &&
6444            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6445         // If we're checking for a potential constant expression, evaluate all
6446         // initializers even if some of them fail.
6447         if (!Info.noteFailure())
6448           return false;
6449         Success = false;
6450       }
6451     }
6452 
6453     // This is the point at which the dynamic type of the object becomes this
6454     // class type.
6455     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6456       EvalObj.finishedConstructingBases();
6457   }
6458 
6459   // Default-initialize any remaining fields.
6460   if (!RD->isUnion()) {
6461     for (; FieldIt != RD->field_end(); ++FieldIt) {
6462       if (!FieldIt->isUnnamedBitfield())
6463         Success &= getDefaultInitValue(
6464             FieldIt->getType(),
6465             Result.getStructField(FieldIt->getFieldIndex()));
6466     }
6467   }
6468 
6469   EvalObj.finishedConstructingFields();
6470 
6471   return Success &&
6472          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6473          LifetimeExtendedScope.destroy();
6474 }
6475 
6476 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6477                                   ArrayRef<const Expr*> Args,
6478                                   const CXXConstructorDecl *Definition,
6479                                   EvalInfo &Info, APValue &Result) {
6480   CallScopeRAII CallScope(Info);
6481   CallRef Call = Info.CurrentCall->createCall(Definition);
6482   if (!EvaluateArgs(Args, Call, Info, Definition))
6483     return false;
6484 
6485   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6486          CallScope.destroy();
6487 }
6488 
6489 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6490                                   const LValue &This, APValue &Value,
6491                                   QualType T) {
6492   // Objects can only be destroyed while they're within their lifetimes.
6493   // FIXME: We have no representation for whether an object of type nullptr_t
6494   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6495   // as indeterminate instead?
6496   if (Value.isAbsent() && !T->isNullPtrType()) {
6497     APValue Printable;
6498     This.moveInto(Printable);
6499     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6500       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6501     return false;
6502   }
6503 
6504   // Invent an expression for location purposes.
6505   // FIXME: We shouldn't need to do this.
6506   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6507 
6508   // For arrays, destroy elements right-to-left.
6509   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6510     uint64_t Size = CAT->getSize().getZExtValue();
6511     QualType ElemT = CAT->getElementType();
6512 
6513     LValue ElemLV = This;
6514     ElemLV.addArray(Info, &LocE, CAT);
6515     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6516       return false;
6517 
6518     // Ensure that we have actual array elements available to destroy; the
6519     // destructors might mutate the value, so we can't run them on the array
6520     // filler.
6521     if (Size && Size > Value.getArrayInitializedElts())
6522       expandArray(Value, Value.getArraySize() - 1);
6523 
6524     for (; Size != 0; --Size) {
6525       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6526       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6527           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6528         return false;
6529     }
6530 
6531     // End the lifetime of this array now.
6532     Value = APValue();
6533     return true;
6534   }
6535 
6536   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6537   if (!RD) {
6538     if (T.isDestructedType()) {
6539       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6540       return false;
6541     }
6542 
6543     Value = APValue();
6544     return true;
6545   }
6546 
6547   if (RD->getNumVBases()) {
6548     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6549     return false;
6550   }
6551 
6552   const CXXDestructorDecl *DD = RD->getDestructor();
6553   if (!DD && !RD->hasTrivialDestructor()) {
6554     Info.FFDiag(CallLoc);
6555     return false;
6556   }
6557 
6558   if (!DD || DD->isTrivial() ||
6559       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6560     // A trivial destructor just ends the lifetime of the object. Check for
6561     // this case before checking for a body, because we might not bother
6562     // building a body for a trivial destructor. Note that it doesn't matter
6563     // whether the destructor is constexpr in this case; all trivial
6564     // destructors are constexpr.
6565     //
6566     // If an anonymous union would be destroyed, some enclosing destructor must
6567     // have been explicitly defined, and the anonymous union destruction should
6568     // have no effect.
6569     Value = APValue();
6570     return true;
6571   }
6572 
6573   if (!Info.CheckCallLimit(CallLoc))
6574     return false;
6575 
6576   const FunctionDecl *Definition = nullptr;
6577   const Stmt *Body = DD->getBody(Definition);
6578 
6579   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6580     return false;
6581 
6582   CallStackFrame Frame(Info, CallLoc, Definition, &This, /*CallExpr=*/nullptr,
6583                        CallRef());
6584 
6585   // We're now in the period of destruction of this object.
6586   unsigned BasesLeft = RD->getNumBases();
6587   EvalInfo::EvaluatingDestructorRAII EvalObj(
6588       Info,
6589       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6590   if (!EvalObj.DidInsert) {
6591     // C++2a [class.dtor]p19:
6592     //   the behavior is undefined if the destructor is invoked for an object
6593     //   whose lifetime has ended
6594     // (Note that formally the lifetime ends when the period of destruction
6595     // begins, even though certain uses of the object remain valid until the
6596     // period of destruction ends.)
6597     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6598     return false;
6599   }
6600 
6601   // FIXME: Creating an APValue just to hold a nonexistent return value is
6602   // wasteful.
6603   APValue RetVal;
6604   StmtResult Ret = {RetVal, nullptr};
6605   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6606     return false;
6607 
6608   // A union destructor does not implicitly destroy its members.
6609   if (RD->isUnion())
6610     return true;
6611 
6612   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6613 
6614   // We don't have a good way to iterate fields in reverse, so collect all the
6615   // fields first and then walk them backwards.
6616   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6617   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6618     if (FD->isUnnamedBitfield())
6619       continue;
6620 
6621     LValue Subobject = This;
6622     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6623       return false;
6624 
6625     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6626     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6627                                FD->getType()))
6628       return false;
6629   }
6630 
6631   if (BasesLeft != 0)
6632     EvalObj.startedDestroyingBases();
6633 
6634   // Destroy base classes in reverse order.
6635   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6636     --BasesLeft;
6637 
6638     QualType BaseType = Base.getType();
6639     LValue Subobject = This;
6640     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6641                                 BaseType->getAsCXXRecordDecl(), &Layout))
6642       return false;
6643 
6644     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6645     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6646                                BaseType))
6647       return false;
6648   }
6649   assert(BasesLeft == 0 && "NumBases was wrong?");
6650 
6651   // The period of destruction ends now. The object is gone.
6652   Value = APValue();
6653   return true;
6654 }
6655 
6656 namespace {
6657 struct DestroyObjectHandler {
6658   EvalInfo &Info;
6659   const Expr *E;
6660   const LValue &This;
6661   const AccessKinds AccessKind;
6662 
6663   typedef bool result_type;
6664   bool failed() { return false; }
6665   bool found(APValue &Subobj, QualType SubobjType) {
6666     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6667                                  SubobjType);
6668   }
6669   bool found(APSInt &Value, QualType SubobjType) {
6670     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6671     return false;
6672   }
6673   bool found(APFloat &Value, QualType SubobjType) {
6674     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6675     return false;
6676   }
6677 };
6678 }
6679 
6680 /// Perform a destructor or pseudo-destructor call on the given object, which
6681 /// might in general not be a complete object.
6682 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6683                               const LValue &This, QualType ThisType) {
6684   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6685   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6686   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6687 }
6688 
6689 /// Destroy and end the lifetime of the given complete object.
6690 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6691                               APValue::LValueBase LVBase, APValue &Value,
6692                               QualType T) {
6693   // If we've had an unmodeled side-effect, we can't rely on mutable state
6694   // (such as the object we're about to destroy) being correct.
6695   if (Info.EvalStatus.HasSideEffects)
6696     return false;
6697 
6698   LValue LV;
6699   LV.set({LVBase});
6700   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6701 }
6702 
6703 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6704 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6705                                   LValue &Result) {
6706   if (Info.checkingPotentialConstantExpression() ||
6707       Info.SpeculativeEvaluationDepth)
6708     return false;
6709 
6710   // This is permitted only within a call to std::allocator<T>::allocate.
6711   auto Caller = Info.getStdAllocatorCaller("allocate");
6712   if (!Caller) {
6713     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6714                                      ? diag::note_constexpr_new_untyped
6715                                      : diag::note_constexpr_new);
6716     return false;
6717   }
6718 
6719   QualType ElemType = Caller.ElemType;
6720   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6721     Info.FFDiag(E->getExprLoc(),
6722                 diag::note_constexpr_new_not_complete_object_type)
6723         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6724     return false;
6725   }
6726 
6727   APSInt ByteSize;
6728   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6729     return false;
6730   bool IsNothrow = false;
6731   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6732     EvaluateIgnoredValue(Info, E->getArg(I));
6733     IsNothrow |= E->getType()->isNothrowT();
6734   }
6735 
6736   CharUnits ElemSize;
6737   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6738     return false;
6739   APInt Size, Remainder;
6740   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6741   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6742   if (Remainder != 0) {
6743     // This likely indicates a bug in the implementation of 'std::allocator'.
6744     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6745         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6746     return false;
6747   }
6748 
6749   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6750     if (IsNothrow) {
6751       Result.setNull(Info.Ctx, E->getType());
6752       return true;
6753     }
6754 
6755     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6756     return false;
6757   }
6758 
6759   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6760                                                      ArrayType::Normal, 0);
6761   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6762   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6763   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6764   return true;
6765 }
6766 
6767 static bool hasVirtualDestructor(QualType T) {
6768   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6769     if (CXXDestructorDecl *DD = RD->getDestructor())
6770       return DD->isVirtual();
6771   return false;
6772 }
6773 
6774 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6775   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6776     if (CXXDestructorDecl *DD = RD->getDestructor())
6777       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6778   return nullptr;
6779 }
6780 
6781 /// Check that the given object is a suitable pointer to a heap allocation that
6782 /// still exists and is of the right kind for the purpose of a deletion.
6783 ///
6784 /// On success, returns the heap allocation to deallocate. On failure, produces
6785 /// a diagnostic and returns std::nullopt.
6786 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6787                                                  const LValue &Pointer,
6788                                                  DynAlloc::Kind DeallocKind) {
6789   auto PointerAsString = [&] {
6790     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6791   };
6792 
6793   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6794   if (!DA) {
6795     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6796         << PointerAsString();
6797     if (Pointer.Base)
6798       NoteLValueLocation(Info, Pointer.Base);
6799     return std::nullopt;
6800   }
6801 
6802   std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6803   if (!Alloc) {
6804     Info.FFDiag(E, diag::note_constexpr_double_delete);
6805     return std::nullopt;
6806   }
6807 
6808   QualType AllocType = Pointer.Base.getDynamicAllocType();
6809   if (DeallocKind != (*Alloc)->getKind()) {
6810     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6811         << DeallocKind << (*Alloc)->getKind() << AllocType;
6812     NoteLValueLocation(Info, Pointer.Base);
6813     return std::nullopt;
6814   }
6815 
6816   bool Subobject = false;
6817   if (DeallocKind == DynAlloc::New) {
6818     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6819                 Pointer.Designator.isOnePastTheEnd();
6820   } else {
6821     Subobject = Pointer.Designator.Entries.size() != 1 ||
6822                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6823   }
6824   if (Subobject) {
6825     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6826         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6827     return std::nullopt;
6828   }
6829 
6830   return Alloc;
6831 }
6832 
6833 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6834 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6835   if (Info.checkingPotentialConstantExpression() ||
6836       Info.SpeculativeEvaluationDepth)
6837     return false;
6838 
6839   // This is permitted only within a call to std::allocator<T>::deallocate.
6840   if (!Info.getStdAllocatorCaller("deallocate")) {
6841     Info.FFDiag(E->getExprLoc());
6842     return true;
6843   }
6844 
6845   LValue Pointer;
6846   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6847     return false;
6848   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6849     EvaluateIgnoredValue(Info, E->getArg(I));
6850 
6851   if (Pointer.Designator.Invalid)
6852     return false;
6853 
6854   // Deleting a null pointer would have no effect, but it's not permitted by
6855   // std::allocator<T>::deallocate's contract.
6856   if (Pointer.isNullPointer()) {
6857     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6858     return true;
6859   }
6860 
6861   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6862     return false;
6863 
6864   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6865   return true;
6866 }
6867 
6868 //===----------------------------------------------------------------------===//
6869 // Generic Evaluation
6870 //===----------------------------------------------------------------------===//
6871 namespace {
6872 
6873 class BitCastBuffer {
6874   // FIXME: We're going to need bit-level granularity when we support
6875   // bit-fields.
6876   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6877   // we don't support a host or target where that is the case. Still, we should
6878   // use a more generic type in case we ever do.
6879   SmallVector<std::optional<unsigned char>, 32> Bytes;
6880 
6881   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6882                 "Need at least 8 bit unsigned char");
6883 
6884   bool TargetIsLittleEndian;
6885 
6886 public:
6887   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6888       : Bytes(Width.getQuantity()),
6889         TargetIsLittleEndian(TargetIsLittleEndian) {}
6890 
6891   [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6892                                 SmallVectorImpl<unsigned char> &Output) const {
6893     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6894       // If a byte of an integer is uninitialized, then the whole integer is
6895       // uninitialized.
6896       if (!Bytes[I.getQuantity()])
6897         return false;
6898       Output.push_back(*Bytes[I.getQuantity()]);
6899     }
6900     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6901       std::reverse(Output.begin(), Output.end());
6902     return true;
6903   }
6904 
6905   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6906     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6907       std::reverse(Input.begin(), Input.end());
6908 
6909     size_t Index = 0;
6910     for (unsigned char Byte : Input) {
6911       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6912       Bytes[Offset.getQuantity() + Index] = Byte;
6913       ++Index;
6914     }
6915   }
6916 
6917   size_t size() { return Bytes.size(); }
6918 };
6919 
6920 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6921 /// target would represent the value at runtime.
6922 class APValueToBufferConverter {
6923   EvalInfo &Info;
6924   BitCastBuffer Buffer;
6925   const CastExpr *BCE;
6926 
6927   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6928                            const CastExpr *BCE)
6929       : Info(Info),
6930         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6931         BCE(BCE) {}
6932 
6933   bool visit(const APValue &Val, QualType Ty) {
6934     return visit(Val, Ty, CharUnits::fromQuantity(0));
6935   }
6936 
6937   // Write out Val with type Ty into Buffer starting at Offset.
6938   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6939     assert((size_t)Offset.getQuantity() <= Buffer.size());
6940 
6941     // As a special case, nullptr_t has an indeterminate value.
6942     if (Ty->isNullPtrType())
6943       return true;
6944 
6945     // Dig through Src to find the byte at SrcOffset.
6946     switch (Val.getKind()) {
6947     case APValue::Indeterminate:
6948     case APValue::None:
6949       return true;
6950 
6951     case APValue::Int:
6952       return visitInt(Val.getInt(), Ty, Offset);
6953     case APValue::Float:
6954       return visitFloat(Val.getFloat(), Ty, Offset);
6955     case APValue::Array:
6956       return visitArray(Val, Ty, Offset);
6957     case APValue::Struct:
6958       return visitRecord(Val, Ty, Offset);
6959 
6960     case APValue::ComplexInt:
6961     case APValue::ComplexFloat:
6962     case APValue::Vector:
6963     case APValue::FixedPoint:
6964       // FIXME: We should support these.
6965 
6966     case APValue::Union:
6967     case APValue::MemberPointer:
6968     case APValue::AddrLabelDiff: {
6969       Info.FFDiag(BCE->getBeginLoc(),
6970                   diag::note_constexpr_bit_cast_unsupported_type)
6971           << Ty;
6972       return false;
6973     }
6974 
6975     case APValue::LValue:
6976       llvm_unreachable("LValue subobject in bit_cast?");
6977     }
6978     llvm_unreachable("Unhandled APValue::ValueKind");
6979   }
6980 
6981   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6982     const RecordDecl *RD = Ty->getAsRecordDecl();
6983     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6984 
6985     // Visit the base classes.
6986     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6987       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6988         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6989         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6990 
6991         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6992                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6993           return false;
6994       }
6995     }
6996 
6997     // Visit the fields.
6998     unsigned FieldIdx = 0;
6999     for (FieldDecl *FD : RD->fields()) {
7000       if (FD->isBitField()) {
7001         Info.FFDiag(BCE->getBeginLoc(),
7002                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7003         return false;
7004       }
7005 
7006       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7007 
7008       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7009              "only bit-fields can have sub-char alignment");
7010       CharUnits FieldOffset =
7011           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7012       QualType FieldTy = FD->getType();
7013       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7014         return false;
7015       ++FieldIdx;
7016     }
7017 
7018     return true;
7019   }
7020 
7021   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7022     const auto *CAT =
7023         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7024     if (!CAT)
7025       return false;
7026 
7027     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7028     unsigned NumInitializedElts = Val.getArrayInitializedElts();
7029     unsigned ArraySize = Val.getArraySize();
7030     // First, initialize the initialized elements.
7031     for (unsigned I = 0; I != NumInitializedElts; ++I) {
7032       const APValue &SubObj = Val.getArrayInitializedElt(I);
7033       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7034         return false;
7035     }
7036 
7037     // Next, initialize the rest of the array using the filler.
7038     if (Val.hasArrayFiller()) {
7039       const APValue &Filler = Val.getArrayFiller();
7040       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7041         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7042           return false;
7043       }
7044     }
7045 
7046     return true;
7047   }
7048 
7049   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7050     APSInt AdjustedVal = Val;
7051     unsigned Width = AdjustedVal.getBitWidth();
7052     if (Ty->isBooleanType()) {
7053       Width = Info.Ctx.getTypeSize(Ty);
7054       AdjustedVal = AdjustedVal.extend(Width);
7055     }
7056 
7057     SmallVector<unsigned char, 8> Bytes(Width / 8);
7058     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7059     Buffer.writeObject(Offset, Bytes);
7060     return true;
7061   }
7062 
7063   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7064     APSInt AsInt(Val.bitcastToAPInt());
7065     return visitInt(AsInt, Ty, Offset);
7066   }
7067 
7068 public:
7069   static std::optional<BitCastBuffer>
7070   convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7071     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7072     APValueToBufferConverter Converter(Info, DstSize, BCE);
7073     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7074       return std::nullopt;
7075     return Converter.Buffer;
7076   }
7077 };
7078 
7079 /// Write an BitCastBuffer into an APValue.
7080 class BufferToAPValueConverter {
7081   EvalInfo &Info;
7082   const BitCastBuffer &Buffer;
7083   const CastExpr *BCE;
7084 
7085   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7086                            const CastExpr *BCE)
7087       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7088 
7089   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7090   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7091   // Ideally this will be unreachable.
7092   std::nullopt_t unsupportedType(QualType Ty) {
7093     Info.FFDiag(BCE->getBeginLoc(),
7094                 diag::note_constexpr_bit_cast_unsupported_type)
7095         << Ty;
7096     return std::nullopt;
7097   }
7098 
7099   std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7100     Info.FFDiag(BCE->getBeginLoc(),
7101                 diag::note_constexpr_bit_cast_unrepresentable_value)
7102         << Ty << toString(Val, /*Radix=*/10);
7103     return std::nullopt;
7104   }
7105 
7106   std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7107                                const EnumType *EnumSugar = nullptr) {
7108     if (T->isNullPtrType()) {
7109       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7110       return APValue((Expr *)nullptr,
7111                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7112                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7113     }
7114 
7115     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7116 
7117     // Work around floating point types that contain unused padding bytes. This
7118     // is really just `long double` on x86, which is the only fundamental type
7119     // with padding bytes.
7120     if (T->isRealFloatingType()) {
7121       const llvm::fltSemantics &Semantics =
7122           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7123       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7124       assert(NumBits % 8 == 0);
7125       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7126       if (NumBytes != SizeOf)
7127         SizeOf = NumBytes;
7128     }
7129 
7130     SmallVector<uint8_t, 8> Bytes;
7131     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7132       // If this is std::byte or unsigned char, then its okay to store an
7133       // indeterminate value.
7134       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7135       bool IsUChar =
7136           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7137                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7138       if (!IsStdByte && !IsUChar) {
7139         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7140         Info.FFDiag(BCE->getExprLoc(),
7141                     diag::note_constexpr_bit_cast_indet_dest)
7142             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7143         return std::nullopt;
7144       }
7145 
7146       return APValue::IndeterminateValue();
7147     }
7148 
7149     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7150     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7151 
7152     if (T->isIntegralOrEnumerationType()) {
7153       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7154 
7155       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7156       if (IntWidth != Val.getBitWidth()) {
7157         APSInt Truncated = Val.trunc(IntWidth);
7158         if (Truncated.extend(Val.getBitWidth()) != Val)
7159           return unrepresentableValue(QualType(T, 0), Val);
7160         Val = Truncated;
7161       }
7162 
7163       return APValue(Val);
7164     }
7165 
7166     if (T->isRealFloatingType()) {
7167       const llvm::fltSemantics &Semantics =
7168           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7169       return APValue(APFloat(Semantics, Val));
7170     }
7171 
7172     return unsupportedType(QualType(T, 0));
7173   }
7174 
7175   std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7176     const RecordDecl *RD = RTy->getAsRecordDecl();
7177     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7178 
7179     unsigned NumBases = 0;
7180     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7181       NumBases = CXXRD->getNumBases();
7182 
7183     APValue ResultVal(APValue::UninitStruct(), NumBases,
7184                       std::distance(RD->field_begin(), RD->field_end()));
7185 
7186     // Visit the base classes.
7187     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7188       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7189         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7190         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7191         if (BaseDecl->isEmpty() ||
7192             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7193           continue;
7194 
7195         std::optional<APValue> SubObj = visitType(
7196             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7197         if (!SubObj)
7198           return std::nullopt;
7199         ResultVal.getStructBase(I) = *SubObj;
7200       }
7201     }
7202 
7203     // Visit the fields.
7204     unsigned FieldIdx = 0;
7205     for (FieldDecl *FD : RD->fields()) {
7206       // FIXME: We don't currently support bit-fields. A lot of the logic for
7207       // this is in CodeGen, so we need to factor it around.
7208       if (FD->isBitField()) {
7209         Info.FFDiag(BCE->getBeginLoc(),
7210                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7211         return std::nullopt;
7212       }
7213 
7214       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7215       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7216 
7217       CharUnits FieldOffset =
7218           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7219           Offset;
7220       QualType FieldTy = FD->getType();
7221       std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7222       if (!SubObj)
7223         return std::nullopt;
7224       ResultVal.getStructField(FieldIdx) = *SubObj;
7225       ++FieldIdx;
7226     }
7227 
7228     return ResultVal;
7229   }
7230 
7231   std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7232     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7233     assert(!RepresentationType.isNull() &&
7234            "enum forward decl should be caught by Sema");
7235     const auto *AsBuiltin =
7236         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7237     // Recurse into the underlying type. Treat std::byte transparently as
7238     // unsigned char.
7239     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7240   }
7241 
7242   std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7243     size_t Size = Ty->getSize().getLimitedValue();
7244     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7245 
7246     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7247     for (size_t I = 0; I != Size; ++I) {
7248       std::optional<APValue> ElementValue =
7249           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7250       if (!ElementValue)
7251         return std::nullopt;
7252       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7253     }
7254 
7255     return ArrayValue;
7256   }
7257 
7258   std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7259     return unsupportedType(QualType(Ty, 0));
7260   }
7261 
7262   std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7263     QualType Can = Ty.getCanonicalType();
7264 
7265     switch (Can->getTypeClass()) {
7266 #define TYPE(Class, Base)                                                      \
7267   case Type::Class:                                                            \
7268     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7269 #define ABSTRACT_TYPE(Class, Base)
7270 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7271   case Type::Class:                                                            \
7272     llvm_unreachable("non-canonical type should be impossible!");
7273 #define DEPENDENT_TYPE(Class, Base)                                            \
7274   case Type::Class:                                                            \
7275     llvm_unreachable(                                                          \
7276         "dependent types aren't supported in the constant evaluator!");
7277 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7278   case Type::Class:                                                            \
7279     llvm_unreachable("either dependent or not canonical!");
7280 #include "clang/AST/TypeNodes.inc"
7281     }
7282     llvm_unreachable("Unhandled Type::TypeClass");
7283   }
7284 
7285 public:
7286   // Pull out a full value of type DstType.
7287   static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7288                                         const CastExpr *BCE) {
7289     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7290     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7291   }
7292 };
7293 
7294 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7295                                                  QualType Ty, EvalInfo *Info,
7296                                                  const ASTContext &Ctx,
7297                                                  bool CheckingDest) {
7298   Ty = Ty.getCanonicalType();
7299 
7300   auto diag = [&](int Reason) {
7301     if (Info)
7302       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7303           << CheckingDest << (Reason == 4) << Reason;
7304     return false;
7305   };
7306   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7307     if (Info)
7308       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7309           << NoteTy << Construct << Ty;
7310     return false;
7311   };
7312 
7313   if (Ty->isUnionType())
7314     return diag(0);
7315   if (Ty->isPointerType())
7316     return diag(1);
7317   if (Ty->isMemberPointerType())
7318     return diag(2);
7319   if (Ty.isVolatileQualified())
7320     return diag(3);
7321 
7322   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7323     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7324       for (CXXBaseSpecifier &BS : CXXRD->bases())
7325         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7326                                                   CheckingDest))
7327           return note(1, BS.getType(), BS.getBeginLoc());
7328     }
7329     for (FieldDecl *FD : Record->fields()) {
7330       if (FD->getType()->isReferenceType())
7331         return diag(4);
7332       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7333                                                 CheckingDest))
7334         return note(0, FD->getType(), FD->getBeginLoc());
7335     }
7336   }
7337 
7338   if (Ty->isArrayType() &&
7339       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7340                                             Info, Ctx, CheckingDest))
7341     return false;
7342 
7343   return true;
7344 }
7345 
7346 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7347                                              const ASTContext &Ctx,
7348                                              const CastExpr *BCE) {
7349   bool DestOK = checkBitCastConstexprEligibilityType(
7350       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7351   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7352                                 BCE->getBeginLoc(),
7353                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7354   return SourceOK;
7355 }
7356 
7357 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7358                                         APValue &SourceValue,
7359                                         const CastExpr *BCE) {
7360   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7361          "no host or target supports non 8-bit chars");
7362   assert(SourceValue.isLValue() &&
7363          "LValueToRValueBitcast requires an lvalue operand!");
7364 
7365   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7366     return false;
7367 
7368   LValue SourceLValue;
7369   APValue SourceRValue;
7370   SourceLValue.setFrom(Info.Ctx, SourceValue);
7371   if (!handleLValueToRValueConversion(
7372           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7373           SourceRValue, /*WantObjectRepresentation=*/true))
7374     return false;
7375 
7376   // Read out SourceValue into a char buffer.
7377   std::optional<BitCastBuffer> Buffer =
7378       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7379   if (!Buffer)
7380     return false;
7381 
7382   // Write out the buffer into a new APValue.
7383   std::optional<APValue> MaybeDestValue =
7384       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7385   if (!MaybeDestValue)
7386     return false;
7387 
7388   DestValue = std::move(*MaybeDestValue);
7389   return true;
7390 }
7391 
7392 template <class Derived>
7393 class ExprEvaluatorBase
7394   : public ConstStmtVisitor<Derived, bool> {
7395 private:
7396   Derived &getDerived() { return static_cast<Derived&>(*this); }
7397   bool DerivedSuccess(const APValue &V, const Expr *E) {
7398     return getDerived().Success(V, E);
7399   }
7400   bool DerivedZeroInitialization(const Expr *E) {
7401     return getDerived().ZeroInitialization(E);
7402   }
7403 
7404   // Check whether a conditional operator with a non-constant condition is a
7405   // potential constant expression. If neither arm is a potential constant
7406   // expression, then the conditional operator is not either.
7407   template<typename ConditionalOperator>
7408   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7409     assert(Info.checkingPotentialConstantExpression());
7410 
7411     // Speculatively evaluate both arms.
7412     SmallVector<PartialDiagnosticAt, 8> Diag;
7413     {
7414       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7415       StmtVisitorTy::Visit(E->getFalseExpr());
7416       if (Diag.empty())
7417         return;
7418     }
7419 
7420     {
7421       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7422       Diag.clear();
7423       StmtVisitorTy::Visit(E->getTrueExpr());
7424       if (Diag.empty())
7425         return;
7426     }
7427 
7428     Error(E, diag::note_constexpr_conditional_never_const);
7429   }
7430 
7431 
7432   template<typename ConditionalOperator>
7433   bool HandleConditionalOperator(const ConditionalOperator *E) {
7434     bool BoolResult;
7435     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7436       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7437         CheckPotentialConstantConditional(E);
7438         return false;
7439       }
7440       if (Info.noteFailure()) {
7441         StmtVisitorTy::Visit(E->getTrueExpr());
7442         StmtVisitorTy::Visit(E->getFalseExpr());
7443       }
7444       return false;
7445     }
7446 
7447     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7448     return StmtVisitorTy::Visit(EvalExpr);
7449   }
7450 
7451 protected:
7452   EvalInfo &Info;
7453   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7454   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7455 
7456   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7457     return Info.CCEDiag(E, D);
7458   }
7459 
7460   bool ZeroInitialization(const Expr *E) { return Error(E); }
7461 
7462   bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7463     unsigned BuiltinOp = E->getBuiltinCallee();
7464     return BuiltinOp != 0 &&
7465            Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7466   }
7467 
7468 public:
7469   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7470 
7471   EvalInfo &getEvalInfo() { return Info; }
7472 
7473   /// Report an evaluation error. This should only be called when an error is
7474   /// first discovered. When propagating an error, just return false.
7475   bool Error(const Expr *E, diag::kind D) {
7476     Info.FFDiag(E, D);
7477     return false;
7478   }
7479   bool Error(const Expr *E) {
7480     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7481   }
7482 
7483   bool VisitStmt(const Stmt *) {
7484     llvm_unreachable("Expression evaluator should not be called on stmts");
7485   }
7486   bool VisitExpr(const Expr *E) {
7487     return Error(E);
7488   }
7489 
7490   bool VisitConstantExpr(const ConstantExpr *E) {
7491     if (E->hasAPValueResult())
7492       return DerivedSuccess(E->getAPValueResult(), E);
7493 
7494     return StmtVisitorTy::Visit(E->getSubExpr());
7495   }
7496 
7497   bool VisitParenExpr(const ParenExpr *E)
7498     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7499   bool VisitUnaryExtension(const UnaryOperator *E)
7500     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7501   bool VisitUnaryPlus(const UnaryOperator *E)
7502     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7503   bool VisitChooseExpr(const ChooseExpr *E)
7504     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7505   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7506     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7507   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7508     { return StmtVisitorTy::Visit(E->getReplacement()); }
7509   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7510     TempVersionRAII RAII(*Info.CurrentCall);
7511     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7512     return StmtVisitorTy::Visit(E->getExpr());
7513   }
7514   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7515     TempVersionRAII RAII(*Info.CurrentCall);
7516     // The initializer may not have been parsed yet, or might be erroneous.
7517     if (!E->getExpr())
7518       return Error(E);
7519     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7520     return StmtVisitorTy::Visit(E->getExpr());
7521   }
7522 
7523   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7524     FullExpressionRAII Scope(Info);
7525     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7526   }
7527 
7528   // Temporaries are registered when created, so we don't care about
7529   // CXXBindTemporaryExpr.
7530   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7531     return StmtVisitorTy::Visit(E->getSubExpr());
7532   }
7533 
7534   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7535     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7536     return static_cast<Derived*>(this)->VisitCastExpr(E);
7537   }
7538   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7539     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7540       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7541     return static_cast<Derived*>(this)->VisitCastExpr(E);
7542   }
7543   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7544     return static_cast<Derived*>(this)->VisitCastExpr(E);
7545   }
7546 
7547   bool VisitBinaryOperator(const BinaryOperator *E) {
7548     switch (E->getOpcode()) {
7549     default:
7550       return Error(E);
7551 
7552     case BO_Comma:
7553       VisitIgnoredValue(E->getLHS());
7554       return StmtVisitorTy::Visit(E->getRHS());
7555 
7556     case BO_PtrMemD:
7557     case BO_PtrMemI: {
7558       LValue Obj;
7559       if (!HandleMemberPointerAccess(Info, E, Obj))
7560         return false;
7561       APValue Result;
7562       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7563         return false;
7564       return DerivedSuccess(Result, E);
7565     }
7566     }
7567   }
7568 
7569   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7570     return StmtVisitorTy::Visit(E->getSemanticForm());
7571   }
7572 
7573   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7574     // Evaluate and cache the common expression. We treat it as a temporary,
7575     // even though it's not quite the same thing.
7576     LValue CommonLV;
7577     if (!Evaluate(Info.CurrentCall->createTemporary(
7578                       E->getOpaqueValue(),
7579                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7580                       ScopeKind::FullExpression, CommonLV),
7581                   Info, E->getCommon()))
7582       return false;
7583 
7584     return HandleConditionalOperator(E);
7585   }
7586 
7587   bool VisitConditionalOperator(const ConditionalOperator *E) {
7588     bool IsBcpCall = false;
7589     // If the condition (ignoring parens) is a __builtin_constant_p call,
7590     // the result is a constant expression if it can be folded without
7591     // side-effects. This is an important GNU extension. See GCC PR38377
7592     // for discussion.
7593     if (const CallExpr *CallCE =
7594           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7595       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7596         IsBcpCall = true;
7597 
7598     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7599     // constant expression; we can't check whether it's potentially foldable.
7600     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7601     // it would return 'false' in this mode.
7602     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7603       return false;
7604 
7605     FoldConstant Fold(Info, IsBcpCall);
7606     if (!HandleConditionalOperator(E)) {
7607       Fold.keepDiagnostics();
7608       return false;
7609     }
7610 
7611     return true;
7612   }
7613 
7614   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7615     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7616       return DerivedSuccess(*Value, E);
7617 
7618     const Expr *Source = E->getSourceExpr();
7619     if (!Source)
7620       return Error(E);
7621     if (Source == E) {
7622       assert(0 && "OpaqueValueExpr recursively refers to itself");
7623       return Error(E);
7624     }
7625     return StmtVisitorTy::Visit(Source);
7626   }
7627 
7628   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7629     for (const Expr *SemE : E->semantics()) {
7630       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7631         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7632         // result expression: there could be two different LValues that would
7633         // refer to the same object in that case, and we can't model that.
7634         if (SemE == E->getResultExpr())
7635           return Error(E);
7636 
7637         // Unique OVEs get evaluated if and when we encounter them when
7638         // emitting the rest of the semantic form, rather than eagerly.
7639         if (OVE->isUnique())
7640           continue;
7641 
7642         LValue LV;
7643         if (!Evaluate(Info.CurrentCall->createTemporary(
7644                           OVE, getStorageType(Info.Ctx, OVE),
7645                           ScopeKind::FullExpression, LV),
7646                       Info, OVE->getSourceExpr()))
7647           return false;
7648       } else if (SemE == E->getResultExpr()) {
7649         if (!StmtVisitorTy::Visit(SemE))
7650           return false;
7651       } else {
7652         if (!EvaluateIgnoredValue(Info, SemE))
7653           return false;
7654       }
7655     }
7656     return true;
7657   }
7658 
7659   bool VisitCallExpr(const CallExpr *E) {
7660     APValue Result;
7661     if (!handleCallExpr(E, Result, nullptr))
7662       return false;
7663     return DerivedSuccess(Result, E);
7664   }
7665 
7666   bool handleCallExpr(const CallExpr *E, APValue &Result,
7667                      const LValue *ResultSlot) {
7668     CallScopeRAII CallScope(Info);
7669 
7670     const Expr *Callee = E->getCallee()->IgnoreParens();
7671     QualType CalleeType = Callee->getType();
7672 
7673     const FunctionDecl *FD = nullptr;
7674     LValue *This = nullptr, ThisVal;
7675     auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7676     bool HasQualifier = false;
7677 
7678     CallRef Call;
7679 
7680     // Extract function decl and 'this' pointer from the callee.
7681     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7682       const CXXMethodDecl *Member = nullptr;
7683       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7684         // Explicit bound member calls, such as x.f() or p->g();
7685         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7686           return false;
7687         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7688         if (!Member)
7689           return Error(Callee);
7690         This = &ThisVal;
7691         HasQualifier = ME->hasQualifier();
7692       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7693         // Indirect bound member calls ('.*' or '->*').
7694         const ValueDecl *D =
7695             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7696         if (!D)
7697           return false;
7698         Member = dyn_cast<CXXMethodDecl>(D);
7699         if (!Member)
7700           return Error(Callee);
7701         This = &ThisVal;
7702       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7703         if (!Info.getLangOpts().CPlusPlus20)
7704           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7705         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7706                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7707       } else
7708         return Error(Callee);
7709       FD = Member;
7710     } else if (CalleeType->isFunctionPointerType()) {
7711       LValue CalleeLV;
7712       if (!EvaluatePointer(Callee, CalleeLV, Info))
7713         return false;
7714 
7715       if (!CalleeLV.getLValueOffset().isZero())
7716         return Error(Callee);
7717       if (CalleeLV.isNullPointer()) {
7718         Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7719             << const_cast<Expr *>(Callee);
7720         return false;
7721       }
7722       FD = dyn_cast_or_null<FunctionDecl>(
7723           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7724       if (!FD)
7725         return Error(Callee);
7726       // Don't call function pointers which have been cast to some other type.
7727       // Per DR (no number yet), the caller and callee can differ in noexcept.
7728       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7729         CalleeType->getPointeeType(), FD->getType())) {
7730         return Error(E);
7731       }
7732 
7733       // For an (overloaded) assignment expression, evaluate the RHS before the
7734       // LHS.
7735       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7736       if (OCE && OCE->isAssignmentOp()) {
7737         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7738         Call = Info.CurrentCall->createCall(FD);
7739         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7740                           Info, FD, /*RightToLeft=*/true))
7741           return false;
7742       }
7743 
7744       // Overloaded operator calls to member functions are represented as normal
7745       // calls with '*this' as the first argument.
7746       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7747       if (MD && !MD->isStatic()) {
7748         // FIXME: When selecting an implicit conversion for an overloaded
7749         // operator delete, we sometimes try to evaluate calls to conversion
7750         // operators without a 'this' parameter!
7751         if (Args.empty())
7752           return Error(E);
7753 
7754         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7755           return false;
7756         This = &ThisVal;
7757 
7758         // If this is syntactically a simple assignment using a trivial
7759         // assignment operator, start the lifetimes of union members as needed,
7760         // per C++20 [class.union]5.
7761         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7762             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7763             !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7764           return false;
7765 
7766         Args = Args.slice(1);
7767       } else if (MD && MD->isLambdaStaticInvoker()) {
7768         // Map the static invoker for the lambda back to the call operator.
7769         // Conveniently, we don't have to slice out the 'this' argument (as is
7770         // being done for the non-static case), since a static member function
7771         // doesn't have an implicit argument passed in.
7772         const CXXRecordDecl *ClosureClass = MD->getParent();
7773         assert(
7774             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7775             "Number of captures must be zero for conversion to function-ptr");
7776 
7777         const CXXMethodDecl *LambdaCallOp =
7778             ClosureClass->getLambdaCallOperator();
7779 
7780         // Set 'FD', the function that will be called below, to the call
7781         // operator.  If the closure object represents a generic lambda, find
7782         // the corresponding specialization of the call operator.
7783 
7784         if (ClosureClass->isGenericLambda()) {
7785           assert(MD->isFunctionTemplateSpecialization() &&
7786                  "A generic lambda's static-invoker function must be a "
7787                  "template specialization");
7788           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7789           FunctionTemplateDecl *CallOpTemplate =
7790               LambdaCallOp->getDescribedFunctionTemplate();
7791           void *InsertPos = nullptr;
7792           FunctionDecl *CorrespondingCallOpSpecialization =
7793               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7794           assert(CorrespondingCallOpSpecialization &&
7795                  "We must always have a function call operator specialization "
7796                  "that corresponds to our static invoker specialization");
7797           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7798         } else
7799           FD = LambdaCallOp;
7800       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7801         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7802             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7803           LValue Ptr;
7804           if (!HandleOperatorNewCall(Info, E, Ptr))
7805             return false;
7806           Ptr.moveInto(Result);
7807           return CallScope.destroy();
7808         } else {
7809           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7810         }
7811       }
7812     } else
7813       return Error(E);
7814 
7815     // Evaluate the arguments now if we've not already done so.
7816     if (!Call) {
7817       Call = Info.CurrentCall->createCall(FD);
7818       if (!EvaluateArgs(Args, Call, Info, FD))
7819         return false;
7820     }
7821 
7822     SmallVector<QualType, 4> CovariantAdjustmentPath;
7823     if (This) {
7824       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7825       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7826         // Perform virtual dispatch, if necessary.
7827         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7828                                    CovariantAdjustmentPath);
7829         if (!FD)
7830           return false;
7831       } else {
7832         // Check that the 'this' pointer points to an object of the right type.
7833         // FIXME: If this is an assignment operator call, we may need to change
7834         // the active union member before we check this.
7835         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7836           return false;
7837       }
7838     }
7839 
7840     // Destructor calls are different enough that they have their own codepath.
7841     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7842       assert(This && "no 'this' pointer for destructor call");
7843       return HandleDestruction(Info, E, *This,
7844                                Info.Ctx.getRecordType(DD->getParent())) &&
7845              CallScope.destroy();
7846     }
7847 
7848     const FunctionDecl *Definition = nullptr;
7849     Stmt *Body = FD->getBody(Definition);
7850 
7851     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7852         !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
7853                             Body, Info, Result, ResultSlot))
7854       return false;
7855 
7856     if (!CovariantAdjustmentPath.empty() &&
7857         !HandleCovariantReturnAdjustment(Info, E, Result,
7858                                          CovariantAdjustmentPath))
7859       return false;
7860 
7861     return CallScope.destroy();
7862   }
7863 
7864   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7865     return StmtVisitorTy::Visit(E->getInitializer());
7866   }
7867   bool VisitInitListExpr(const InitListExpr *E) {
7868     if (E->getNumInits() == 0)
7869       return DerivedZeroInitialization(E);
7870     if (E->getNumInits() == 1)
7871       return StmtVisitorTy::Visit(E->getInit(0));
7872     return Error(E);
7873   }
7874   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7875     return DerivedZeroInitialization(E);
7876   }
7877   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7878     return DerivedZeroInitialization(E);
7879   }
7880   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7881     return DerivedZeroInitialization(E);
7882   }
7883 
7884   /// A member expression where the object is a prvalue is itself a prvalue.
7885   bool VisitMemberExpr(const MemberExpr *E) {
7886     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7887            "missing temporary materialization conversion");
7888     assert(!E->isArrow() && "missing call to bound member function?");
7889 
7890     APValue Val;
7891     if (!Evaluate(Val, Info, E->getBase()))
7892       return false;
7893 
7894     QualType BaseTy = E->getBase()->getType();
7895 
7896     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7897     if (!FD) return Error(E);
7898     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7899     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7900            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7901 
7902     // Note: there is no lvalue base here. But this case should only ever
7903     // happen in C or in C++98, where we cannot be evaluating a constexpr
7904     // constructor, which is the only case the base matters.
7905     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7906     SubobjectDesignator Designator(BaseTy);
7907     Designator.addDeclUnchecked(FD);
7908 
7909     APValue Result;
7910     return extractSubobject(Info, E, Obj, Designator, Result) &&
7911            DerivedSuccess(Result, E);
7912   }
7913 
7914   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7915     APValue Val;
7916     if (!Evaluate(Val, Info, E->getBase()))
7917       return false;
7918 
7919     if (Val.isVector()) {
7920       SmallVector<uint32_t, 4> Indices;
7921       E->getEncodedElementAccess(Indices);
7922       if (Indices.size() == 1) {
7923         // Return scalar.
7924         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7925       } else {
7926         // Construct new APValue vector.
7927         SmallVector<APValue, 4> Elts;
7928         for (unsigned I = 0; I < Indices.size(); ++I) {
7929           Elts.push_back(Val.getVectorElt(Indices[I]));
7930         }
7931         APValue VecResult(Elts.data(), Indices.size());
7932         return DerivedSuccess(VecResult, E);
7933       }
7934     }
7935 
7936     return false;
7937   }
7938 
7939   bool VisitCastExpr(const CastExpr *E) {
7940     switch (E->getCastKind()) {
7941     default:
7942       break;
7943 
7944     case CK_AtomicToNonAtomic: {
7945       APValue AtomicVal;
7946       // This does not need to be done in place even for class/array types:
7947       // atomic-to-non-atomic conversion implies copying the object
7948       // representation.
7949       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7950         return false;
7951       return DerivedSuccess(AtomicVal, E);
7952     }
7953 
7954     case CK_NoOp:
7955     case CK_UserDefinedConversion:
7956       return StmtVisitorTy::Visit(E->getSubExpr());
7957 
7958     case CK_LValueToRValue: {
7959       LValue LVal;
7960       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7961         return false;
7962       APValue RVal;
7963       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7964       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7965                                           LVal, RVal))
7966         return false;
7967       return DerivedSuccess(RVal, E);
7968     }
7969     case CK_LValueToRValueBitCast: {
7970       APValue DestValue, SourceValue;
7971       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7972         return false;
7973       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7974         return false;
7975       return DerivedSuccess(DestValue, E);
7976     }
7977 
7978     case CK_AddressSpaceConversion: {
7979       APValue Value;
7980       if (!Evaluate(Value, Info, E->getSubExpr()))
7981         return false;
7982       return DerivedSuccess(Value, E);
7983     }
7984     }
7985 
7986     return Error(E);
7987   }
7988 
7989   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7990     return VisitUnaryPostIncDec(UO);
7991   }
7992   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7993     return VisitUnaryPostIncDec(UO);
7994   }
7995   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7996     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7997       return Error(UO);
7998 
7999     LValue LVal;
8000     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8001       return false;
8002     APValue RVal;
8003     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8004                       UO->isIncrementOp(), &RVal))
8005       return false;
8006     return DerivedSuccess(RVal, UO);
8007   }
8008 
8009   bool VisitStmtExpr(const StmtExpr *E) {
8010     // We will have checked the full-expressions inside the statement expression
8011     // when they were completed, and don't need to check them again now.
8012     llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8013                                           false);
8014 
8015     const CompoundStmt *CS = E->getSubStmt();
8016     if (CS->body_empty())
8017       return true;
8018 
8019     BlockScopeRAII Scope(Info);
8020     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8021                                            BE = CS->body_end();
8022          /**/; ++BI) {
8023       if (BI + 1 == BE) {
8024         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8025         if (!FinalExpr) {
8026           Info.FFDiag((*BI)->getBeginLoc(),
8027                       diag::note_constexpr_stmt_expr_unsupported);
8028           return false;
8029         }
8030         return this->Visit(FinalExpr) && Scope.destroy();
8031       }
8032 
8033       APValue ReturnValue;
8034       StmtResult Result = { ReturnValue, nullptr };
8035       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8036       if (ESR != ESR_Succeeded) {
8037         // FIXME: If the statement-expression terminated due to 'return',
8038         // 'break', or 'continue', it would be nice to propagate that to
8039         // the outer statement evaluation rather than bailing out.
8040         if (ESR != ESR_Failed)
8041           Info.FFDiag((*BI)->getBeginLoc(),
8042                       diag::note_constexpr_stmt_expr_unsupported);
8043         return false;
8044       }
8045     }
8046 
8047     llvm_unreachable("Return from function from the loop above.");
8048   }
8049 
8050   /// Visit a value which is evaluated, but whose value is ignored.
8051   void VisitIgnoredValue(const Expr *E) {
8052     EvaluateIgnoredValue(Info, E);
8053   }
8054 
8055   /// Potentially visit a MemberExpr's base expression.
8056   void VisitIgnoredBaseExpression(const Expr *E) {
8057     // While MSVC doesn't evaluate the base expression, it does diagnose the
8058     // presence of side-effecting behavior.
8059     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8060       return;
8061     VisitIgnoredValue(E);
8062   }
8063 };
8064 
8065 } // namespace
8066 
8067 //===----------------------------------------------------------------------===//
8068 // Common base class for lvalue and temporary evaluation.
8069 //===----------------------------------------------------------------------===//
8070 namespace {
8071 template<class Derived>
8072 class LValueExprEvaluatorBase
8073   : public ExprEvaluatorBase<Derived> {
8074 protected:
8075   LValue &Result;
8076   bool InvalidBaseOK;
8077   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8078   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8079 
8080   bool Success(APValue::LValueBase B) {
8081     Result.set(B);
8082     return true;
8083   }
8084 
8085   bool evaluatePointer(const Expr *E, LValue &Result) {
8086     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8087   }
8088 
8089 public:
8090   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8091       : ExprEvaluatorBaseTy(Info), Result(Result),
8092         InvalidBaseOK(InvalidBaseOK) {}
8093 
8094   bool Success(const APValue &V, const Expr *E) {
8095     Result.setFrom(this->Info.Ctx, V);
8096     return true;
8097   }
8098 
8099   bool VisitMemberExpr(const MemberExpr *E) {
8100     // Handle non-static data members.
8101     QualType BaseTy;
8102     bool EvalOK;
8103     if (E->isArrow()) {
8104       EvalOK = evaluatePointer(E->getBase(), Result);
8105       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8106     } else if (E->getBase()->isPRValue()) {
8107       assert(E->getBase()->getType()->isRecordType());
8108       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8109       BaseTy = E->getBase()->getType();
8110     } else {
8111       EvalOK = this->Visit(E->getBase());
8112       BaseTy = E->getBase()->getType();
8113     }
8114     if (!EvalOK) {
8115       if (!InvalidBaseOK)
8116         return false;
8117       Result.setInvalid(E);
8118       return true;
8119     }
8120 
8121     const ValueDecl *MD = E->getMemberDecl();
8122     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8123       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8124              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8125       (void)BaseTy;
8126       if (!HandleLValueMember(this->Info, E, Result, FD))
8127         return false;
8128     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8129       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8130         return false;
8131     } else
8132       return this->Error(E);
8133 
8134     if (MD->getType()->isReferenceType()) {
8135       APValue RefValue;
8136       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8137                                           RefValue))
8138         return false;
8139       return Success(RefValue, E);
8140     }
8141     return true;
8142   }
8143 
8144   bool VisitBinaryOperator(const BinaryOperator *E) {
8145     switch (E->getOpcode()) {
8146     default:
8147       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8148 
8149     case BO_PtrMemD:
8150     case BO_PtrMemI:
8151       return HandleMemberPointerAccess(this->Info, E, Result);
8152     }
8153   }
8154 
8155   bool VisitCastExpr(const CastExpr *E) {
8156     switch (E->getCastKind()) {
8157     default:
8158       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8159 
8160     case CK_DerivedToBase:
8161     case CK_UncheckedDerivedToBase:
8162       if (!this->Visit(E->getSubExpr()))
8163         return false;
8164 
8165       // Now figure out the necessary offset to add to the base LV to get from
8166       // the derived class to the base class.
8167       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8168                                   Result);
8169     }
8170   }
8171 };
8172 }
8173 
8174 //===----------------------------------------------------------------------===//
8175 // LValue Evaluation
8176 //
8177 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8178 // function designators (in C), decl references to void objects (in C), and
8179 // temporaries (if building with -Wno-address-of-temporary).
8180 //
8181 // LValue evaluation produces values comprising a base expression of one of the
8182 // following types:
8183 // - Declarations
8184 //  * VarDecl
8185 //  * FunctionDecl
8186 // - Literals
8187 //  * CompoundLiteralExpr in C (and in global scope in C++)
8188 //  * StringLiteral
8189 //  * PredefinedExpr
8190 //  * ObjCStringLiteralExpr
8191 //  * ObjCEncodeExpr
8192 //  * AddrLabelExpr
8193 //  * BlockExpr
8194 //  * CallExpr for a MakeStringConstant builtin
8195 // - typeid(T) expressions, as TypeInfoLValues
8196 // - Locals and temporaries
8197 //  * MaterializeTemporaryExpr
8198 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8199 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8200 //    from the AST (FIXME).
8201 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8202 //    CallIndex, for a lifetime-extended temporary.
8203 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8204 //    immediate invocation.
8205 // plus an offset in bytes.
8206 //===----------------------------------------------------------------------===//
8207 namespace {
8208 class LValueExprEvaluator
8209   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8210 public:
8211   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8212     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8213 
8214   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8215   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8216 
8217   bool VisitCallExpr(const CallExpr *E);
8218   bool VisitDeclRefExpr(const DeclRefExpr *E);
8219   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8220   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8221   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8222   bool VisitMemberExpr(const MemberExpr *E);
8223   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8224   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8225   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8226   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8227   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8228   bool VisitUnaryDeref(const UnaryOperator *E);
8229   bool VisitUnaryReal(const UnaryOperator *E);
8230   bool VisitUnaryImag(const UnaryOperator *E);
8231   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8232     return VisitUnaryPreIncDec(UO);
8233   }
8234   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8235     return VisitUnaryPreIncDec(UO);
8236   }
8237   bool VisitBinAssign(const BinaryOperator *BO);
8238   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8239 
8240   bool VisitCastExpr(const CastExpr *E) {
8241     switch (E->getCastKind()) {
8242     default:
8243       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8244 
8245     case CK_LValueBitCast:
8246       this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8247           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8248       if (!Visit(E->getSubExpr()))
8249         return false;
8250       Result.Designator.setInvalid();
8251       return true;
8252 
8253     case CK_BaseToDerived:
8254       if (!Visit(E->getSubExpr()))
8255         return false;
8256       return HandleBaseToDerivedCast(Info, E, Result);
8257 
8258     case CK_Dynamic:
8259       if (!Visit(E->getSubExpr()))
8260         return false;
8261       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8262     }
8263   }
8264 };
8265 } // end anonymous namespace
8266 
8267 /// Evaluate an expression as an lvalue. This can be legitimately called on
8268 /// expressions which are not glvalues, in three cases:
8269 ///  * function designators in C, and
8270 ///  * "extern void" objects
8271 ///  * @selector() expressions in Objective-C
8272 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8273                            bool InvalidBaseOK) {
8274   assert(!E->isValueDependent());
8275   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8276          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8277   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8278 }
8279 
8280 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8281   const NamedDecl *D = E->getDecl();
8282   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8283           UnnamedGlobalConstantDecl>(D))
8284     return Success(cast<ValueDecl>(D));
8285   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8286     return VisitVarDecl(E, VD);
8287   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8288     return Visit(BD->getBinding());
8289   return Error(E);
8290 }
8291 
8292 
8293 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8294 
8295   // If we are within a lambda's call operator, check whether the 'VD' referred
8296   // to within 'E' actually represents a lambda-capture that maps to a
8297   // data-member/field within the closure object, and if so, evaluate to the
8298   // field or what the field refers to.
8299   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8300       isa<DeclRefExpr>(E) &&
8301       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8302     // We don't always have a complete capture-map when checking or inferring if
8303     // the function call operator meets the requirements of a constexpr function
8304     // - but we don't need to evaluate the captures to determine constexprness
8305     // (dcl.constexpr C++17).
8306     if (Info.checkingPotentialConstantExpression())
8307       return false;
8308 
8309     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8310       // Start with 'Result' referring to the complete closure object...
8311       Result = *Info.CurrentCall->This;
8312       // ... then update it to refer to the field of the closure object
8313       // that represents the capture.
8314       if (!HandleLValueMember(Info, E, Result, FD))
8315         return false;
8316       // And if the field is of reference type, update 'Result' to refer to what
8317       // the field refers to.
8318       if (FD->getType()->isReferenceType()) {
8319         APValue RVal;
8320         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8321                                             RVal))
8322           return false;
8323         Result.setFrom(Info.Ctx, RVal);
8324       }
8325       return true;
8326     }
8327   }
8328 
8329   CallStackFrame *Frame = nullptr;
8330   unsigned Version = 0;
8331   if (VD->hasLocalStorage()) {
8332     // Only if a local variable was declared in the function currently being
8333     // evaluated, do we expect to be able to find its value in the current
8334     // frame. (Otherwise it was likely declared in an enclosing context and
8335     // could either have a valid evaluatable value (for e.g. a constexpr
8336     // variable) or be ill-formed (and trigger an appropriate evaluation
8337     // diagnostic)).
8338     CallStackFrame *CurrFrame = Info.CurrentCall;
8339     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8340       // Function parameters are stored in some caller's frame. (Usually the
8341       // immediate caller, but for an inherited constructor they may be more
8342       // distant.)
8343       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8344         if (CurrFrame->Arguments) {
8345           VD = CurrFrame->Arguments.getOrigParam(PVD);
8346           Frame =
8347               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8348           Version = CurrFrame->Arguments.Version;
8349         }
8350       } else {
8351         Frame = CurrFrame;
8352         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8353       }
8354     }
8355   }
8356 
8357   if (!VD->getType()->isReferenceType()) {
8358     if (Frame) {
8359       Result.set({VD, Frame->Index, Version});
8360       return true;
8361     }
8362     return Success(VD);
8363   }
8364 
8365   if (!Info.getLangOpts().CPlusPlus11) {
8366     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8367         << VD << VD->getType();
8368     Info.Note(VD->getLocation(), diag::note_declared_at);
8369   }
8370 
8371   APValue *V;
8372   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8373     return false;
8374   if (!V->hasValue()) {
8375     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8376     // adjust the diagnostic to say that.
8377     if (!Info.checkingPotentialConstantExpression())
8378       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8379     return false;
8380   }
8381   return Success(*V, E);
8382 }
8383 
8384 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8385   if (!IsConstantEvaluatedBuiltinCall(E))
8386     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8387 
8388   switch (E->getBuiltinCallee()) {
8389   default:
8390     return false;
8391   case Builtin::BIas_const:
8392   case Builtin::BIforward:
8393   case Builtin::BIforward_like:
8394   case Builtin::BImove:
8395   case Builtin::BImove_if_noexcept:
8396     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8397       return Visit(E->getArg(0));
8398     break;
8399   }
8400 
8401   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8402 }
8403 
8404 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8405     const MaterializeTemporaryExpr *E) {
8406   // Walk through the expression to find the materialized temporary itself.
8407   SmallVector<const Expr *, 2> CommaLHSs;
8408   SmallVector<SubobjectAdjustment, 2> Adjustments;
8409   const Expr *Inner =
8410       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8411 
8412   // If we passed any comma operators, evaluate their LHSs.
8413   for (const Expr *E : CommaLHSs)
8414     if (!EvaluateIgnoredValue(Info, E))
8415       return false;
8416 
8417   // A materialized temporary with static storage duration can appear within the
8418   // result of a constant expression evaluation, so we need to preserve its
8419   // value for use outside this evaluation.
8420   APValue *Value;
8421   if (E->getStorageDuration() == SD_Static) {
8422     if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8423       return false;
8424     // FIXME: What about SD_Thread?
8425     Value = E->getOrCreateValue(true);
8426     *Value = APValue();
8427     Result.set(E);
8428   } else {
8429     Value = &Info.CurrentCall->createTemporary(
8430         E, E->getType(),
8431         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8432                                                      : ScopeKind::Block,
8433         Result);
8434   }
8435 
8436   QualType Type = Inner->getType();
8437 
8438   // Materialize the temporary itself.
8439   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8440     *Value = APValue();
8441     return false;
8442   }
8443 
8444   // Adjust our lvalue to refer to the desired subobject.
8445   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8446     --I;
8447     switch (Adjustments[I].Kind) {
8448     case SubobjectAdjustment::DerivedToBaseAdjustment:
8449       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8450                                 Type, Result))
8451         return false;
8452       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8453       break;
8454 
8455     case SubobjectAdjustment::FieldAdjustment:
8456       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8457         return false;
8458       Type = Adjustments[I].Field->getType();
8459       break;
8460 
8461     case SubobjectAdjustment::MemberPointerAdjustment:
8462       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8463                                      Adjustments[I].Ptr.RHS))
8464         return false;
8465       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8466       break;
8467     }
8468   }
8469 
8470   return true;
8471 }
8472 
8473 bool
8474 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8475   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8476          "lvalue compound literal in c++?");
8477   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8478   // only see this when folding in C, so there's no standard to follow here.
8479   return Success(E);
8480 }
8481 
8482 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8483   TypeInfoLValue TypeInfo;
8484 
8485   if (!E->isPotentiallyEvaluated()) {
8486     if (E->isTypeOperand())
8487       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8488     else
8489       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8490   } else {
8491     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8492       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8493         << E->getExprOperand()->getType()
8494         << E->getExprOperand()->getSourceRange();
8495     }
8496 
8497     if (!Visit(E->getExprOperand()))
8498       return false;
8499 
8500     std::optional<DynamicType> DynType =
8501         ComputeDynamicType(Info, E, Result, AK_TypeId);
8502     if (!DynType)
8503       return false;
8504 
8505     TypeInfo =
8506         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8507   }
8508 
8509   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8510 }
8511 
8512 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8513   return Success(E->getGuidDecl());
8514 }
8515 
8516 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8517   // Handle static data members.
8518   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8519     VisitIgnoredBaseExpression(E->getBase());
8520     return VisitVarDecl(E, VD);
8521   }
8522 
8523   // Handle static member functions.
8524   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8525     if (MD->isStatic()) {
8526       VisitIgnoredBaseExpression(E->getBase());
8527       return Success(MD);
8528     }
8529   }
8530 
8531   // Handle non-static data members.
8532   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8533 }
8534 
8535 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8536   // FIXME: Deal with vectors as array subscript bases.
8537   if (E->getBase()->getType()->isVectorType() ||
8538       E->getBase()->getType()->isVLSTBuiltinType())
8539     return Error(E);
8540 
8541   APSInt Index;
8542   bool Success = true;
8543 
8544   // C++17's rules require us to evaluate the LHS first, regardless of which
8545   // side is the base.
8546   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8547     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8548                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8549       if (!Info.noteFailure())
8550         return false;
8551       Success = false;
8552     }
8553   }
8554 
8555   return Success &&
8556          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8557 }
8558 
8559 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8560   return evaluatePointer(E->getSubExpr(), Result);
8561 }
8562 
8563 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8564   if (!Visit(E->getSubExpr()))
8565     return false;
8566   // __real is a no-op on scalar lvalues.
8567   if (E->getSubExpr()->getType()->isAnyComplexType())
8568     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8569   return true;
8570 }
8571 
8572 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8573   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8574          "lvalue __imag__ on scalar?");
8575   if (!Visit(E->getSubExpr()))
8576     return false;
8577   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8578   return true;
8579 }
8580 
8581 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8582   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8583     return Error(UO);
8584 
8585   if (!this->Visit(UO->getSubExpr()))
8586     return false;
8587 
8588   return handleIncDec(
8589       this->Info, UO, Result, UO->getSubExpr()->getType(),
8590       UO->isIncrementOp(), nullptr);
8591 }
8592 
8593 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8594     const CompoundAssignOperator *CAO) {
8595   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8596     return Error(CAO);
8597 
8598   bool Success = true;
8599 
8600   // C++17 onwards require that we evaluate the RHS first.
8601   APValue RHS;
8602   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8603     if (!Info.noteFailure())
8604       return false;
8605     Success = false;
8606   }
8607 
8608   // The overall lvalue result is the result of evaluating the LHS.
8609   if (!this->Visit(CAO->getLHS()) || !Success)
8610     return false;
8611 
8612   return handleCompoundAssignment(
8613       this->Info, CAO,
8614       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8615       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8616 }
8617 
8618 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8619   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8620     return Error(E);
8621 
8622   bool Success = true;
8623 
8624   // C++17 onwards require that we evaluate the RHS first.
8625   APValue NewVal;
8626   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8627     if (!Info.noteFailure())
8628       return false;
8629     Success = false;
8630   }
8631 
8632   if (!this->Visit(E->getLHS()) || !Success)
8633     return false;
8634 
8635   if (Info.getLangOpts().CPlusPlus20 &&
8636       !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8637     return false;
8638 
8639   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8640                           NewVal);
8641 }
8642 
8643 //===----------------------------------------------------------------------===//
8644 // Pointer Evaluation
8645 //===----------------------------------------------------------------------===//
8646 
8647 /// Attempts to compute the number of bytes available at the pointer
8648 /// returned by a function with the alloc_size attribute. Returns true if we
8649 /// were successful. Places an unsigned number into `Result`.
8650 ///
8651 /// This expects the given CallExpr to be a call to a function with an
8652 /// alloc_size attribute.
8653 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8654                                             const CallExpr *Call,
8655                                             llvm::APInt &Result) {
8656   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8657 
8658   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8659   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8660   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8661   if (Call->getNumArgs() <= SizeArgNo)
8662     return false;
8663 
8664   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8665     Expr::EvalResult ExprResult;
8666     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8667       return false;
8668     Into = ExprResult.Val.getInt();
8669     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8670       return false;
8671     Into = Into.zext(BitsInSizeT);
8672     return true;
8673   };
8674 
8675   APSInt SizeOfElem;
8676   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8677     return false;
8678 
8679   if (!AllocSize->getNumElemsParam().isValid()) {
8680     Result = std::move(SizeOfElem);
8681     return true;
8682   }
8683 
8684   APSInt NumberOfElems;
8685   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8686   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8687     return false;
8688 
8689   bool Overflow;
8690   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8691   if (Overflow)
8692     return false;
8693 
8694   Result = std::move(BytesAvailable);
8695   return true;
8696 }
8697 
8698 /// Convenience function. LVal's base must be a call to an alloc_size
8699 /// function.
8700 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8701                                             const LValue &LVal,
8702                                             llvm::APInt &Result) {
8703   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8704          "Can't get the size of a non alloc_size function");
8705   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8706   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8707   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8708 }
8709 
8710 /// Attempts to evaluate the given LValueBase as the result of a call to
8711 /// a function with the alloc_size attribute. If it was possible to do so, this
8712 /// function will return true, make Result's Base point to said function call,
8713 /// and mark Result's Base as invalid.
8714 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8715                                       LValue &Result) {
8716   if (Base.isNull())
8717     return false;
8718 
8719   // Because we do no form of static analysis, we only support const variables.
8720   //
8721   // Additionally, we can't support parameters, nor can we support static
8722   // variables (in the latter case, use-before-assign isn't UB; in the former,
8723   // we have no clue what they'll be assigned to).
8724   const auto *VD =
8725       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8726   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8727     return false;
8728 
8729   const Expr *Init = VD->getAnyInitializer();
8730   if (!Init || Init->getType().isNull())
8731     return false;
8732 
8733   const Expr *E = Init->IgnoreParens();
8734   if (!tryUnwrapAllocSizeCall(E))
8735     return false;
8736 
8737   // Store E instead of E unwrapped so that the type of the LValue's base is
8738   // what the user wanted.
8739   Result.setInvalid(E);
8740 
8741   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8742   Result.addUnsizedArray(Info, E, Pointee);
8743   return true;
8744 }
8745 
8746 namespace {
8747 class PointerExprEvaluator
8748   : public ExprEvaluatorBase<PointerExprEvaluator> {
8749   LValue &Result;
8750   bool InvalidBaseOK;
8751 
8752   bool Success(const Expr *E) {
8753     Result.set(E);
8754     return true;
8755   }
8756 
8757   bool evaluateLValue(const Expr *E, LValue &Result) {
8758     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8759   }
8760 
8761   bool evaluatePointer(const Expr *E, LValue &Result) {
8762     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8763   }
8764 
8765   bool visitNonBuiltinCallExpr(const CallExpr *E);
8766 public:
8767 
8768   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8769       : ExprEvaluatorBaseTy(info), Result(Result),
8770         InvalidBaseOK(InvalidBaseOK) {}
8771 
8772   bool Success(const APValue &V, const Expr *E) {
8773     Result.setFrom(Info.Ctx, V);
8774     return true;
8775   }
8776   bool ZeroInitialization(const Expr *E) {
8777     Result.setNull(Info.Ctx, E->getType());
8778     return true;
8779   }
8780 
8781   bool VisitBinaryOperator(const BinaryOperator *E);
8782   bool VisitCastExpr(const CastExpr* E);
8783   bool VisitUnaryAddrOf(const UnaryOperator *E);
8784   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8785       { return Success(E); }
8786   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8787     if (E->isExpressibleAsConstantInitializer())
8788       return Success(E);
8789     if (Info.noteFailure())
8790       EvaluateIgnoredValue(Info, E->getSubExpr());
8791     return Error(E);
8792   }
8793   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8794       { return Success(E); }
8795   bool VisitCallExpr(const CallExpr *E);
8796   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8797   bool VisitBlockExpr(const BlockExpr *E) {
8798     if (!E->getBlockDecl()->hasCaptures())
8799       return Success(E);
8800     return Error(E);
8801   }
8802   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8803     // Can't look at 'this' when checking a potential constant expression.
8804     if (Info.checkingPotentialConstantExpression())
8805       return false;
8806     if (!Info.CurrentCall->This) {
8807       if (Info.getLangOpts().CPlusPlus11)
8808         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8809       else
8810         Info.FFDiag(E);
8811       return false;
8812     }
8813     Result = *Info.CurrentCall->This;
8814 
8815     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8816       // Ensure we actually have captured 'this'. If something was wrong with
8817       // 'this' capture, the error would have been previously reported.
8818       // Otherwise we can be inside of a default initialization of an object
8819       // declared by lambda's body, so no need to return false.
8820       if (!Info.CurrentCall->LambdaThisCaptureField)
8821         return true;
8822 
8823       // If we have captured 'this',  the 'this' expression refers
8824       // to the enclosing '*this' object (either by value or reference) which is
8825       // either copied into the closure object's field that represents the
8826       // '*this' or refers to '*this'.
8827       // Update 'Result' to refer to the data member/field of the closure object
8828       // that represents the '*this' capture.
8829       if (!HandleLValueMember(Info, E, Result,
8830                              Info.CurrentCall->LambdaThisCaptureField))
8831         return false;
8832       // If we captured '*this' by reference, replace the field with its referent.
8833       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8834               ->isPointerType()) {
8835         APValue RVal;
8836         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8837                                             RVal))
8838           return false;
8839 
8840         Result.setFrom(Info.Ctx, RVal);
8841       }
8842     }
8843     return true;
8844   }
8845 
8846   bool VisitCXXNewExpr(const CXXNewExpr *E);
8847 
8848   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8849     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8850     APValue LValResult = E->EvaluateInContext(
8851         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8852     Result.setFrom(Info.Ctx, LValResult);
8853     return true;
8854   }
8855 
8856   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8857     std::string ResultStr = E->ComputeName(Info.Ctx);
8858 
8859     QualType CharTy = Info.Ctx.CharTy.withConst();
8860     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8861                ResultStr.size() + 1);
8862     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8863                                                      ArrayType::Normal, 0);
8864 
8865     StringLiteral *SL =
8866         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8867                               /*Pascal*/ false, ArrayTy, E->getLocation());
8868 
8869     evaluateLValue(SL, Result);
8870     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8871     return true;
8872   }
8873 
8874   // FIXME: Missing: @protocol, @selector
8875 };
8876 } // end anonymous namespace
8877 
8878 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8879                             bool InvalidBaseOK) {
8880   assert(!E->isValueDependent());
8881   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8882   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8883 }
8884 
8885 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8886   if (E->getOpcode() != BO_Add &&
8887       E->getOpcode() != BO_Sub)
8888     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8889 
8890   const Expr *PExp = E->getLHS();
8891   const Expr *IExp = E->getRHS();
8892   if (IExp->getType()->isPointerType())
8893     std::swap(PExp, IExp);
8894 
8895   bool EvalPtrOK = evaluatePointer(PExp, Result);
8896   if (!EvalPtrOK && !Info.noteFailure())
8897     return false;
8898 
8899   llvm::APSInt Offset;
8900   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8901     return false;
8902 
8903   if (E->getOpcode() == BO_Sub)
8904     negateAsSigned(Offset);
8905 
8906   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8907   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8908 }
8909 
8910 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8911   return evaluateLValue(E->getSubExpr(), Result);
8912 }
8913 
8914 // Is the provided decl 'std::source_location::current'?
8915 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8916   if (!FD)
8917     return false;
8918   const IdentifierInfo *FnII = FD->getIdentifier();
8919   if (!FnII || !FnII->isStr("current"))
8920     return false;
8921 
8922   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8923   if (!RD)
8924     return false;
8925 
8926   const IdentifierInfo *ClassII = RD->getIdentifier();
8927   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8928 }
8929 
8930 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8931   const Expr *SubExpr = E->getSubExpr();
8932 
8933   switch (E->getCastKind()) {
8934   default:
8935     break;
8936   case CK_BitCast:
8937   case CK_CPointerToObjCPointerCast:
8938   case CK_BlockPointerToObjCPointerCast:
8939   case CK_AnyPointerToBlockPointerCast:
8940   case CK_AddressSpaceConversion:
8941     if (!Visit(SubExpr))
8942       return false;
8943     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8944     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8945     // also static_casts, but we disallow them as a resolution to DR1312.
8946     if (!E->getType()->isVoidPointerType()) {
8947       // In some circumstances, we permit casting from void* to cv1 T*, when the
8948       // actual pointee object is actually a cv2 T.
8949       bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
8950                             !Result.IsNullPtr;
8951       bool VoidPtrCastMaybeOK =
8952           HasValidResult &&
8953           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8954                                           E->getType()->getPointeeType());
8955       // 1. We'll allow it in std::allocator::allocate, and anything which that
8956       //    calls.
8957       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8958       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8959       //    We'll allow it in the body of std::source_location::current.  GCC's
8960       //    implementation had a parameter of type `void*`, and casts from
8961       //    that back to `const __impl*` in its body.
8962       if (VoidPtrCastMaybeOK &&
8963           (Info.getStdAllocatorCaller("allocate") ||
8964            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
8965            Info.getLangOpts().CPlusPlus26)) {
8966         // Permitted.
8967       } else {
8968         if (SubExpr->getType()->isVoidPointerType()) {
8969           if (HasValidResult)
8970             CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
8971                 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
8972                 << Result.Designator.getType(Info.Ctx).getCanonicalType()
8973                 << E->getType()->getPointeeType();
8974           else
8975             CCEDiag(E, diag::note_constexpr_invalid_cast)
8976                 << 3 << SubExpr->getType();
8977         } else
8978           CCEDiag(E, diag::note_constexpr_invalid_cast)
8979               << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8980         Result.Designator.setInvalid();
8981       }
8982     }
8983     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8984       ZeroInitialization(E);
8985     return true;
8986 
8987   case CK_DerivedToBase:
8988   case CK_UncheckedDerivedToBase:
8989     if (!evaluatePointer(E->getSubExpr(), Result))
8990       return false;
8991     if (!Result.Base && Result.Offset.isZero())
8992       return true;
8993 
8994     // Now figure out the necessary offset to add to the base LV to get from
8995     // the derived class to the base class.
8996     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8997                                   castAs<PointerType>()->getPointeeType(),
8998                                 Result);
8999 
9000   case CK_BaseToDerived:
9001     if (!Visit(E->getSubExpr()))
9002       return false;
9003     if (!Result.Base && Result.Offset.isZero())
9004       return true;
9005     return HandleBaseToDerivedCast(Info, E, Result);
9006 
9007   case CK_Dynamic:
9008     if (!Visit(E->getSubExpr()))
9009       return false;
9010     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9011 
9012   case CK_NullToPointer:
9013     VisitIgnoredValue(E->getSubExpr());
9014     return ZeroInitialization(E);
9015 
9016   case CK_IntegralToPointer: {
9017     CCEDiag(E, diag::note_constexpr_invalid_cast)
9018         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9019 
9020     APValue Value;
9021     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9022       break;
9023 
9024     if (Value.isInt()) {
9025       unsigned Size = Info.Ctx.getTypeSize(E->getType());
9026       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9027       Result.Base = (Expr*)nullptr;
9028       Result.InvalidBase = false;
9029       Result.Offset = CharUnits::fromQuantity(N);
9030       Result.Designator.setInvalid();
9031       Result.IsNullPtr = false;
9032       return true;
9033     } else {
9034       // Cast is of an lvalue, no need to change value.
9035       Result.setFrom(Info.Ctx, Value);
9036       return true;
9037     }
9038   }
9039 
9040   case CK_ArrayToPointerDecay: {
9041     if (SubExpr->isGLValue()) {
9042       if (!evaluateLValue(SubExpr, Result))
9043         return false;
9044     } else {
9045       APValue &Value = Info.CurrentCall->createTemporary(
9046           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9047       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9048         return false;
9049     }
9050     // The result is a pointer to the first element of the array.
9051     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9052     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9053       Result.addArray(Info, E, CAT);
9054     else
9055       Result.addUnsizedArray(Info, E, AT->getElementType());
9056     return true;
9057   }
9058 
9059   case CK_FunctionToPointerDecay:
9060     return evaluateLValue(SubExpr, Result);
9061 
9062   case CK_LValueToRValue: {
9063     LValue LVal;
9064     if (!evaluateLValue(E->getSubExpr(), LVal))
9065       return false;
9066 
9067     APValue RVal;
9068     // Note, we use the subexpression's type in order to retain cv-qualifiers.
9069     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9070                                         LVal, RVal))
9071       return InvalidBaseOK &&
9072              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9073     return Success(RVal, E);
9074   }
9075   }
9076 
9077   return ExprEvaluatorBaseTy::VisitCastExpr(E);
9078 }
9079 
9080 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9081                                 UnaryExprOrTypeTrait ExprKind) {
9082   // C++ [expr.alignof]p3:
9083   //     When alignof is applied to a reference type, the result is the
9084   //     alignment of the referenced type.
9085   T = T.getNonReferenceType();
9086 
9087   if (T.getQualifiers().hasUnaligned())
9088     return CharUnits::One();
9089 
9090   const bool AlignOfReturnsPreferred =
9091       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9092 
9093   // __alignof is defined to return the preferred alignment.
9094   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9095   // as well.
9096   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9097     return Info.Ctx.toCharUnitsFromBits(
9098       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9099   // alignof and _Alignof are defined to return the ABI alignment.
9100   else if (ExprKind == UETT_AlignOf)
9101     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9102   else
9103     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9104 }
9105 
9106 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9107                                 UnaryExprOrTypeTrait ExprKind) {
9108   E = E->IgnoreParens();
9109 
9110   // The kinds of expressions that we have special-case logic here for
9111   // should be kept up to date with the special checks for those
9112   // expressions in Sema.
9113 
9114   // alignof decl is always accepted, even if it doesn't make sense: we default
9115   // to 1 in those cases.
9116   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9117     return Info.Ctx.getDeclAlign(DRE->getDecl(),
9118                                  /*RefAsPointee*/true);
9119 
9120   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9121     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9122                                  /*RefAsPointee*/true);
9123 
9124   return GetAlignOfType(Info, E->getType(), ExprKind);
9125 }
9126 
9127 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9128   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9129     return Info.Ctx.getDeclAlign(VD);
9130   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9131     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9132   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9133 }
9134 
9135 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9136 /// __builtin_is_aligned and __builtin_assume_aligned.
9137 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9138                                  EvalInfo &Info, APSInt &Alignment) {
9139   if (!EvaluateInteger(E, Alignment, Info))
9140     return false;
9141   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9142     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9143     return false;
9144   }
9145   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9146   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9147   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9148     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9149         << MaxValue << ForType << Alignment;
9150     return false;
9151   }
9152   // Ensure both alignment and source value have the same bit width so that we
9153   // don't assert when computing the resulting value.
9154   APSInt ExtAlignment =
9155       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9156   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9157          "Alignment should not be changed by ext/trunc");
9158   Alignment = ExtAlignment;
9159   assert(Alignment.getBitWidth() == SrcWidth);
9160   return true;
9161 }
9162 
9163 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9164 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9165   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9166     return true;
9167 
9168   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9169     return false;
9170 
9171   Result.setInvalid(E);
9172   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9173   Result.addUnsizedArray(Info, E, PointeeTy);
9174   return true;
9175 }
9176 
9177 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9178   if (!IsConstantEvaluatedBuiltinCall(E))
9179     return visitNonBuiltinCallExpr(E);
9180   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9181 }
9182 
9183 // Determine if T is a character type for which we guarantee that
9184 // sizeof(T) == 1.
9185 static bool isOneByteCharacterType(QualType T) {
9186   return T->isCharType() || T->isChar8Type();
9187 }
9188 
9189 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9190                                                 unsigned BuiltinOp) {
9191   if (IsNoOpCall(E))
9192     return Success(E);
9193 
9194   switch (BuiltinOp) {
9195   case Builtin::BIaddressof:
9196   case Builtin::BI__addressof:
9197   case Builtin::BI__builtin_addressof:
9198     return evaluateLValue(E->getArg(0), Result);
9199   case Builtin::BI__builtin_assume_aligned: {
9200     // We need to be very careful here because: if the pointer does not have the
9201     // asserted alignment, then the behavior is undefined, and undefined
9202     // behavior is non-constant.
9203     if (!evaluatePointer(E->getArg(0), Result))
9204       return false;
9205 
9206     LValue OffsetResult(Result);
9207     APSInt Alignment;
9208     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9209                               Alignment))
9210       return false;
9211     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9212 
9213     if (E->getNumArgs() > 2) {
9214       APSInt Offset;
9215       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9216         return false;
9217 
9218       int64_t AdditionalOffset = -Offset.getZExtValue();
9219       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9220     }
9221 
9222     // If there is a base object, then it must have the correct alignment.
9223     if (OffsetResult.Base) {
9224       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9225 
9226       if (BaseAlignment < Align) {
9227         Result.Designator.setInvalid();
9228         // FIXME: Add support to Diagnostic for long / long long.
9229         CCEDiag(E->getArg(0),
9230                 diag::note_constexpr_baa_insufficient_alignment) << 0
9231           << (unsigned)BaseAlignment.getQuantity()
9232           << (unsigned)Align.getQuantity();
9233         return false;
9234       }
9235     }
9236 
9237     // The offset must also have the correct alignment.
9238     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9239       Result.Designator.setInvalid();
9240 
9241       (OffsetResult.Base
9242            ? CCEDiag(E->getArg(0),
9243                      diag::note_constexpr_baa_insufficient_alignment) << 1
9244            : CCEDiag(E->getArg(0),
9245                      diag::note_constexpr_baa_value_insufficient_alignment))
9246         << (int)OffsetResult.Offset.getQuantity()
9247         << (unsigned)Align.getQuantity();
9248       return false;
9249     }
9250 
9251     return true;
9252   }
9253   case Builtin::BI__builtin_align_up:
9254   case Builtin::BI__builtin_align_down: {
9255     if (!evaluatePointer(E->getArg(0), Result))
9256       return false;
9257     APSInt Alignment;
9258     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9259                               Alignment))
9260       return false;
9261     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9262     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9263     // For align_up/align_down, we can return the same value if the alignment
9264     // is known to be greater or equal to the requested value.
9265     if (PtrAlign.getQuantity() >= Alignment)
9266       return true;
9267 
9268     // The alignment could be greater than the minimum at run-time, so we cannot
9269     // infer much about the resulting pointer value. One case is possible:
9270     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9271     // can infer the correct index if the requested alignment is smaller than
9272     // the base alignment so we can perform the computation on the offset.
9273     if (BaseAlignment.getQuantity() >= Alignment) {
9274       assert(Alignment.getBitWidth() <= 64 &&
9275              "Cannot handle > 64-bit address-space");
9276       uint64_t Alignment64 = Alignment.getZExtValue();
9277       CharUnits NewOffset = CharUnits::fromQuantity(
9278           BuiltinOp == Builtin::BI__builtin_align_down
9279               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9280               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9281       Result.adjustOffset(NewOffset - Result.Offset);
9282       // TODO: diagnose out-of-bounds values/only allow for arrays?
9283       return true;
9284     }
9285     // Otherwise, we cannot constant-evaluate the result.
9286     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9287         << Alignment;
9288     return false;
9289   }
9290   case Builtin::BI__builtin_operator_new:
9291     return HandleOperatorNewCall(Info, E, Result);
9292   case Builtin::BI__builtin_launder:
9293     return evaluatePointer(E->getArg(0), Result);
9294   case Builtin::BIstrchr:
9295   case Builtin::BIwcschr:
9296   case Builtin::BImemchr:
9297   case Builtin::BIwmemchr:
9298     if (Info.getLangOpts().CPlusPlus11)
9299       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9300           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9301           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9302     else
9303       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9304     [[fallthrough]];
9305   case Builtin::BI__builtin_strchr:
9306   case Builtin::BI__builtin_wcschr:
9307   case Builtin::BI__builtin_memchr:
9308   case Builtin::BI__builtin_char_memchr:
9309   case Builtin::BI__builtin_wmemchr: {
9310     if (!Visit(E->getArg(0)))
9311       return false;
9312     APSInt Desired;
9313     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9314       return false;
9315     uint64_t MaxLength = uint64_t(-1);
9316     if (BuiltinOp != Builtin::BIstrchr &&
9317         BuiltinOp != Builtin::BIwcschr &&
9318         BuiltinOp != Builtin::BI__builtin_strchr &&
9319         BuiltinOp != Builtin::BI__builtin_wcschr) {
9320       APSInt N;
9321       if (!EvaluateInteger(E->getArg(2), N, Info))
9322         return false;
9323       MaxLength = N.getExtValue();
9324     }
9325     // We cannot find the value if there are no candidates to match against.
9326     if (MaxLength == 0u)
9327       return ZeroInitialization(E);
9328     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9329         Result.Designator.Invalid)
9330       return false;
9331     QualType CharTy = Result.Designator.getType(Info.Ctx);
9332     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9333                      BuiltinOp == Builtin::BI__builtin_memchr;
9334     assert(IsRawByte ||
9335            Info.Ctx.hasSameUnqualifiedType(
9336                CharTy, E->getArg(0)->getType()->getPointeeType()));
9337     // Pointers to const void may point to objects of incomplete type.
9338     if (IsRawByte && CharTy->isIncompleteType()) {
9339       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9340       return false;
9341     }
9342     // Give up on byte-oriented matching against multibyte elements.
9343     // FIXME: We can compare the bytes in the correct order.
9344     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9345       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9346           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9347           << CharTy;
9348       return false;
9349     }
9350     // Figure out what value we're actually looking for (after converting to
9351     // the corresponding unsigned type if necessary).
9352     uint64_t DesiredVal;
9353     bool StopAtNull = false;
9354     switch (BuiltinOp) {
9355     case Builtin::BIstrchr:
9356     case Builtin::BI__builtin_strchr:
9357       // strchr compares directly to the passed integer, and therefore
9358       // always fails if given an int that is not a char.
9359       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9360                                                   E->getArg(1)->getType(),
9361                                                   Desired),
9362                                Desired))
9363         return ZeroInitialization(E);
9364       StopAtNull = true;
9365       [[fallthrough]];
9366     case Builtin::BImemchr:
9367     case Builtin::BI__builtin_memchr:
9368     case Builtin::BI__builtin_char_memchr:
9369       // memchr compares by converting both sides to unsigned char. That's also
9370       // correct for strchr if we get this far (to cope with plain char being
9371       // unsigned in the strchr case).
9372       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9373       break;
9374 
9375     case Builtin::BIwcschr:
9376     case Builtin::BI__builtin_wcschr:
9377       StopAtNull = true;
9378       [[fallthrough]];
9379     case Builtin::BIwmemchr:
9380     case Builtin::BI__builtin_wmemchr:
9381       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9382       DesiredVal = Desired.getZExtValue();
9383       break;
9384     }
9385 
9386     for (; MaxLength; --MaxLength) {
9387       APValue Char;
9388       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9389           !Char.isInt())
9390         return false;
9391       if (Char.getInt().getZExtValue() == DesiredVal)
9392         return true;
9393       if (StopAtNull && !Char.getInt())
9394         break;
9395       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9396         return false;
9397     }
9398     // Not found: return nullptr.
9399     return ZeroInitialization(E);
9400   }
9401 
9402   case Builtin::BImemcpy:
9403   case Builtin::BImemmove:
9404   case Builtin::BIwmemcpy:
9405   case Builtin::BIwmemmove:
9406     if (Info.getLangOpts().CPlusPlus11)
9407       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9408           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9409           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9410     else
9411       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9412     [[fallthrough]];
9413   case Builtin::BI__builtin_memcpy:
9414   case Builtin::BI__builtin_memmove:
9415   case Builtin::BI__builtin_wmemcpy:
9416   case Builtin::BI__builtin_wmemmove: {
9417     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9418                  BuiltinOp == Builtin::BIwmemmove ||
9419                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9420                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9421     bool Move = BuiltinOp == Builtin::BImemmove ||
9422                 BuiltinOp == Builtin::BIwmemmove ||
9423                 BuiltinOp == Builtin::BI__builtin_memmove ||
9424                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9425 
9426     // The result of mem* is the first argument.
9427     if (!Visit(E->getArg(0)))
9428       return false;
9429     LValue Dest = Result;
9430 
9431     LValue Src;
9432     if (!EvaluatePointer(E->getArg(1), Src, Info))
9433       return false;
9434 
9435     APSInt N;
9436     if (!EvaluateInteger(E->getArg(2), N, Info))
9437       return false;
9438     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9439 
9440     // If the size is zero, we treat this as always being a valid no-op.
9441     // (Even if one of the src and dest pointers is null.)
9442     if (!N)
9443       return true;
9444 
9445     // Otherwise, if either of the operands is null, we can't proceed. Don't
9446     // try to determine the type of the copied objects, because there aren't
9447     // any.
9448     if (!Src.Base || !Dest.Base) {
9449       APValue Val;
9450       (!Src.Base ? Src : Dest).moveInto(Val);
9451       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9452           << Move << WChar << !!Src.Base
9453           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9454       return false;
9455     }
9456     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9457       return false;
9458 
9459     // We require that Src and Dest are both pointers to arrays of
9460     // trivially-copyable type. (For the wide version, the designator will be
9461     // invalid if the designated object is not a wchar_t.)
9462     QualType T = Dest.Designator.getType(Info.Ctx);
9463     QualType SrcT = Src.Designator.getType(Info.Ctx);
9464     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9465       // FIXME: Consider using our bit_cast implementation to support this.
9466       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9467       return false;
9468     }
9469     if (T->isIncompleteType()) {
9470       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9471       return false;
9472     }
9473     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9474       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9475       return false;
9476     }
9477 
9478     // Figure out how many T's we're copying.
9479     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9480     if (!WChar) {
9481       uint64_t Remainder;
9482       llvm::APInt OrigN = N;
9483       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9484       if (Remainder) {
9485         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9486             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9487             << (unsigned)TSize;
9488         return false;
9489       }
9490     }
9491 
9492     // Check that the copying will remain within the arrays, just so that we
9493     // can give a more meaningful diagnostic. This implicitly also checks that
9494     // N fits into 64 bits.
9495     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9496     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9497     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9498       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9499           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9500           << toString(N, 10, /*Signed*/false);
9501       return false;
9502     }
9503     uint64_t NElems = N.getZExtValue();
9504     uint64_t NBytes = NElems * TSize;
9505 
9506     // Check for overlap.
9507     int Direction = 1;
9508     if (HasSameBase(Src, Dest)) {
9509       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9510       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9511       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9512         // Dest is inside the source region.
9513         if (!Move) {
9514           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9515           return false;
9516         }
9517         // For memmove and friends, copy backwards.
9518         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9519             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9520           return false;
9521         Direction = -1;
9522       } else if (!Move && SrcOffset >= DestOffset &&
9523                  SrcOffset - DestOffset < NBytes) {
9524         // Src is inside the destination region for memcpy: invalid.
9525         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9526         return false;
9527       }
9528     }
9529 
9530     while (true) {
9531       APValue Val;
9532       // FIXME: Set WantObjectRepresentation to true if we're copying a
9533       // char-like type?
9534       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9535           !handleAssignment(Info, E, Dest, T, Val))
9536         return false;
9537       // Do not iterate past the last element; if we're copying backwards, that
9538       // might take us off the start of the array.
9539       if (--NElems == 0)
9540         return true;
9541       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9542           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9543         return false;
9544     }
9545   }
9546 
9547   default:
9548     return false;
9549   }
9550 }
9551 
9552 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9553                                      APValue &Result, const InitListExpr *ILE,
9554                                      QualType AllocType);
9555 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9556                                           APValue &Result,
9557                                           const CXXConstructExpr *CCE,
9558                                           QualType AllocType);
9559 
9560 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9561   if (!Info.getLangOpts().CPlusPlus20)
9562     Info.CCEDiag(E, diag::note_constexpr_new);
9563 
9564   // We cannot speculatively evaluate a delete expression.
9565   if (Info.SpeculativeEvaluationDepth)
9566     return false;
9567 
9568   FunctionDecl *OperatorNew = E->getOperatorNew();
9569 
9570   bool IsNothrow = false;
9571   bool IsPlacement = false;
9572   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9573       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9574     // FIXME Support array placement new.
9575     assert(E->getNumPlacementArgs() == 1);
9576     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9577       return false;
9578     if (Result.Designator.Invalid)
9579       return false;
9580     IsPlacement = true;
9581   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9582     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9583         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9584     return false;
9585   } else if (E->getNumPlacementArgs()) {
9586     // The only new-placement list we support is of the form (std::nothrow).
9587     //
9588     // FIXME: There is no restriction on this, but it's not clear that any
9589     // other form makes any sense. We get here for cases such as:
9590     //
9591     //   new (std::align_val_t{N}) X(int)
9592     //
9593     // (which should presumably be valid only if N is a multiple of
9594     // alignof(int), and in any case can't be deallocated unless N is
9595     // alignof(X) and X has new-extended alignment).
9596     if (E->getNumPlacementArgs() != 1 ||
9597         !E->getPlacementArg(0)->getType()->isNothrowT())
9598       return Error(E, diag::note_constexpr_new_placement);
9599 
9600     LValue Nothrow;
9601     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9602       return false;
9603     IsNothrow = true;
9604   }
9605 
9606   const Expr *Init = E->getInitializer();
9607   const InitListExpr *ResizedArrayILE = nullptr;
9608   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9609   bool ValueInit = false;
9610 
9611   QualType AllocType = E->getAllocatedType();
9612   if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9613     const Expr *Stripped = *ArraySize;
9614     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9615          Stripped = ICE->getSubExpr())
9616       if (ICE->getCastKind() != CK_NoOp &&
9617           ICE->getCastKind() != CK_IntegralCast)
9618         break;
9619 
9620     llvm::APSInt ArrayBound;
9621     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9622       return false;
9623 
9624     // C++ [expr.new]p9:
9625     //   The expression is erroneous if:
9626     //   -- [...] its value before converting to size_t [or] applying the
9627     //      second standard conversion sequence is less than zero
9628     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9629       if (IsNothrow)
9630         return ZeroInitialization(E);
9631 
9632       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9633           << ArrayBound << (*ArraySize)->getSourceRange();
9634       return false;
9635     }
9636 
9637     //   -- its value is such that the size of the allocated object would
9638     //      exceed the implementation-defined limit
9639     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9640                                                 ArrayBound) >
9641         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9642       if (IsNothrow)
9643         return ZeroInitialization(E);
9644 
9645       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9646         << ArrayBound << (*ArraySize)->getSourceRange();
9647       return false;
9648     }
9649 
9650     //   -- the new-initializer is a braced-init-list and the number of
9651     //      array elements for which initializers are provided [...]
9652     //      exceeds the number of elements to initialize
9653     if (!Init) {
9654       // No initialization is performed.
9655     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9656                isa<ImplicitValueInitExpr>(Init)) {
9657       ValueInit = true;
9658     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9659       ResizedArrayCCE = CCE;
9660     } else {
9661       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9662       assert(CAT && "unexpected type for array initializer");
9663 
9664       unsigned Bits =
9665           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9666       llvm::APInt InitBound = CAT->getSize().zext(Bits);
9667       llvm::APInt AllocBound = ArrayBound.zext(Bits);
9668       if (InitBound.ugt(AllocBound)) {
9669         if (IsNothrow)
9670           return ZeroInitialization(E);
9671 
9672         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9673             << toString(AllocBound, 10, /*Signed=*/false)
9674             << toString(InitBound, 10, /*Signed=*/false)
9675             << (*ArraySize)->getSourceRange();
9676         return false;
9677       }
9678 
9679       // If the sizes differ, we must have an initializer list, and we need
9680       // special handling for this case when we initialize.
9681       if (InitBound != AllocBound)
9682         ResizedArrayILE = cast<InitListExpr>(Init);
9683     }
9684 
9685     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9686                                               ArrayType::Normal, 0);
9687   } else {
9688     assert(!AllocType->isArrayType() &&
9689            "array allocation with non-array new");
9690   }
9691 
9692   APValue *Val;
9693   if (IsPlacement) {
9694     AccessKinds AK = AK_Construct;
9695     struct FindObjectHandler {
9696       EvalInfo &Info;
9697       const Expr *E;
9698       QualType AllocType;
9699       const AccessKinds AccessKind;
9700       APValue *Value;
9701 
9702       typedef bool result_type;
9703       bool failed() { return false; }
9704       bool found(APValue &Subobj, QualType SubobjType) {
9705         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9706         // old name of the object to be used to name the new object.
9707         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9708           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9709             SubobjType << AllocType;
9710           return false;
9711         }
9712         Value = &Subobj;
9713         return true;
9714       }
9715       bool found(APSInt &Value, QualType SubobjType) {
9716         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9717         return false;
9718       }
9719       bool found(APFloat &Value, QualType SubobjType) {
9720         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9721         return false;
9722       }
9723     } Handler = {Info, E, AllocType, AK, nullptr};
9724 
9725     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9726     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9727       return false;
9728 
9729     Val = Handler.Value;
9730 
9731     // [basic.life]p1:
9732     //   The lifetime of an object o of type T ends when [...] the storage
9733     //   which the object occupies is [...] reused by an object that is not
9734     //   nested within o (6.6.2).
9735     *Val = APValue();
9736   } else {
9737     // Perform the allocation and obtain a pointer to the resulting object.
9738     Val = Info.createHeapAlloc(E, AllocType, Result);
9739     if (!Val)
9740       return false;
9741   }
9742 
9743   if (ValueInit) {
9744     ImplicitValueInitExpr VIE(AllocType);
9745     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9746       return false;
9747   } else if (ResizedArrayILE) {
9748     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9749                                   AllocType))
9750       return false;
9751   } else if (ResizedArrayCCE) {
9752     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9753                                        AllocType))
9754       return false;
9755   } else if (Init) {
9756     if (!EvaluateInPlace(*Val, Info, Result, Init))
9757       return false;
9758   } else if (!getDefaultInitValue(AllocType, *Val)) {
9759     return false;
9760   }
9761 
9762   // Array new returns a pointer to the first element, not a pointer to the
9763   // array.
9764   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9765     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9766 
9767   return true;
9768 }
9769 //===----------------------------------------------------------------------===//
9770 // Member Pointer Evaluation
9771 //===----------------------------------------------------------------------===//
9772 
9773 namespace {
9774 class MemberPointerExprEvaluator
9775   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9776   MemberPtr &Result;
9777 
9778   bool Success(const ValueDecl *D) {
9779     Result = MemberPtr(D);
9780     return true;
9781   }
9782 public:
9783 
9784   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9785     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9786 
9787   bool Success(const APValue &V, const Expr *E) {
9788     Result.setFrom(V);
9789     return true;
9790   }
9791   bool ZeroInitialization(const Expr *E) {
9792     return Success((const ValueDecl*)nullptr);
9793   }
9794 
9795   bool VisitCastExpr(const CastExpr *E);
9796   bool VisitUnaryAddrOf(const UnaryOperator *E);
9797 };
9798 } // end anonymous namespace
9799 
9800 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9801                                   EvalInfo &Info) {
9802   assert(!E->isValueDependent());
9803   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9804   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9805 }
9806 
9807 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9808   switch (E->getCastKind()) {
9809   default:
9810     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9811 
9812   case CK_NullToMemberPointer:
9813     VisitIgnoredValue(E->getSubExpr());
9814     return ZeroInitialization(E);
9815 
9816   case CK_BaseToDerivedMemberPointer: {
9817     if (!Visit(E->getSubExpr()))
9818       return false;
9819     if (E->path_empty())
9820       return true;
9821     // Base-to-derived member pointer casts store the path in derived-to-base
9822     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9823     // the wrong end of the derived->base arc, so stagger the path by one class.
9824     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9825     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9826          PathI != PathE; ++PathI) {
9827       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9828       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9829       if (!Result.castToDerived(Derived))
9830         return Error(E);
9831     }
9832     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9833     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9834       return Error(E);
9835     return true;
9836   }
9837 
9838   case CK_DerivedToBaseMemberPointer:
9839     if (!Visit(E->getSubExpr()))
9840       return false;
9841     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9842          PathE = E->path_end(); PathI != PathE; ++PathI) {
9843       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9844       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9845       if (!Result.castToBase(Base))
9846         return Error(E);
9847     }
9848     return true;
9849   }
9850 }
9851 
9852 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9853   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9854   // member can be formed.
9855   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9856 }
9857 
9858 //===----------------------------------------------------------------------===//
9859 // Record Evaluation
9860 //===----------------------------------------------------------------------===//
9861 
9862 namespace {
9863   class RecordExprEvaluator
9864   : public ExprEvaluatorBase<RecordExprEvaluator> {
9865     const LValue &This;
9866     APValue &Result;
9867   public:
9868 
9869     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9870       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9871 
9872     bool Success(const APValue &V, const Expr *E) {
9873       Result = V;
9874       return true;
9875     }
9876     bool ZeroInitialization(const Expr *E) {
9877       return ZeroInitialization(E, E->getType());
9878     }
9879     bool ZeroInitialization(const Expr *E, QualType T);
9880 
9881     bool VisitCallExpr(const CallExpr *E) {
9882       return handleCallExpr(E, Result, &This);
9883     }
9884     bool VisitCastExpr(const CastExpr *E);
9885     bool VisitInitListExpr(const InitListExpr *E);
9886     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9887       return VisitCXXConstructExpr(E, E->getType());
9888     }
9889     bool VisitLambdaExpr(const LambdaExpr *E);
9890     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9891     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9892     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9893     bool VisitBinCmp(const BinaryOperator *E);
9894     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
9895     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
9896                                          ArrayRef<Expr *> Args);
9897   };
9898 }
9899 
9900 /// Perform zero-initialization on an object of non-union class type.
9901 /// C++11 [dcl.init]p5:
9902 ///  To zero-initialize an object or reference of type T means:
9903 ///    [...]
9904 ///    -- if T is a (possibly cv-qualified) non-union class type,
9905 ///       each non-static data member and each base-class subobject is
9906 ///       zero-initialized
9907 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9908                                           const RecordDecl *RD,
9909                                           const LValue &This, APValue &Result) {
9910   assert(!RD->isUnion() && "Expected non-union class type");
9911   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9912   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9913                    std::distance(RD->field_begin(), RD->field_end()));
9914 
9915   if (RD->isInvalidDecl()) return false;
9916   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9917 
9918   if (CD) {
9919     unsigned Index = 0;
9920     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9921            End = CD->bases_end(); I != End; ++I, ++Index) {
9922       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9923       LValue Subobject = This;
9924       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9925         return false;
9926       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9927                                          Result.getStructBase(Index)))
9928         return false;
9929     }
9930   }
9931 
9932   for (const auto *I : RD->fields()) {
9933     // -- if T is a reference type, no initialization is performed.
9934     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9935       continue;
9936 
9937     LValue Subobject = This;
9938     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9939       return false;
9940 
9941     ImplicitValueInitExpr VIE(I->getType());
9942     if (!EvaluateInPlace(
9943           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9944       return false;
9945   }
9946 
9947   return true;
9948 }
9949 
9950 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9951   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9952   if (RD->isInvalidDecl()) return false;
9953   if (RD->isUnion()) {
9954     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9955     // object's first non-static named data member is zero-initialized
9956     RecordDecl::field_iterator I = RD->field_begin();
9957     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9958       ++I;
9959     if (I == RD->field_end()) {
9960       Result = APValue((const FieldDecl*)nullptr);
9961       return true;
9962     }
9963 
9964     LValue Subobject = This;
9965     if (!HandleLValueMember(Info, E, Subobject, *I))
9966       return false;
9967     Result = APValue(*I);
9968     ImplicitValueInitExpr VIE(I->getType());
9969     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9970   }
9971 
9972   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9973     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9974     return false;
9975   }
9976 
9977   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9978 }
9979 
9980 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9981   switch (E->getCastKind()) {
9982   default:
9983     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9984 
9985   case CK_ConstructorConversion:
9986     return Visit(E->getSubExpr());
9987 
9988   case CK_DerivedToBase:
9989   case CK_UncheckedDerivedToBase: {
9990     APValue DerivedObject;
9991     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9992       return false;
9993     if (!DerivedObject.isStruct())
9994       return Error(E->getSubExpr());
9995 
9996     // Derived-to-base rvalue conversion: just slice off the derived part.
9997     APValue *Value = &DerivedObject;
9998     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9999     for (CastExpr::path_const_iterator PathI = E->path_begin(),
10000          PathE = E->path_end(); PathI != PathE; ++PathI) {
10001       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10002       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10003       Value = &Value->getStructBase(getBaseIndex(RD, Base));
10004       RD = Base;
10005     }
10006     Result = *Value;
10007     return true;
10008   }
10009   }
10010 }
10011 
10012 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10013   if (E->isTransparent())
10014     return Visit(E->getInit(0));
10015   return VisitCXXParenListOrInitListExpr(E, E->inits());
10016 }
10017 
10018 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10019     const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10020   const RecordDecl *RD =
10021       ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10022   if (RD->isInvalidDecl()) return false;
10023   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10024   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10025 
10026   EvalInfo::EvaluatingConstructorRAII EvalObj(
10027       Info,
10028       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10029       CXXRD && CXXRD->getNumBases());
10030 
10031   if (RD->isUnion()) {
10032     const FieldDecl *Field;
10033     if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10034       Field = ILE->getInitializedFieldInUnion();
10035     } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10036       Field = PLIE->getInitializedFieldInUnion();
10037     } else {
10038       llvm_unreachable(
10039           "Expression is neither an init list nor a C++ paren list");
10040     }
10041 
10042     Result = APValue(Field);
10043     if (!Field)
10044       return true;
10045 
10046     // If the initializer list for a union does not contain any elements, the
10047     // first element of the union is value-initialized.
10048     // FIXME: The element should be initialized from an initializer list.
10049     //        Is this difference ever observable for initializer lists which
10050     //        we don't build?
10051     ImplicitValueInitExpr VIE(Field->getType());
10052     const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10053 
10054     LValue Subobject = This;
10055     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10056       return false;
10057 
10058     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10059     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10060                                   isa<CXXDefaultInitExpr>(InitExpr));
10061 
10062     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10063       if (Field->isBitField())
10064         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10065                                      Field);
10066       return true;
10067     }
10068 
10069     return false;
10070   }
10071 
10072   if (!Result.hasValue())
10073     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10074                      std::distance(RD->field_begin(), RD->field_end()));
10075   unsigned ElementNo = 0;
10076   bool Success = true;
10077 
10078   // Initialize base classes.
10079   if (CXXRD && CXXRD->getNumBases()) {
10080     for (const auto &Base : CXXRD->bases()) {
10081       assert(ElementNo < Args.size() && "missing init for base class");
10082       const Expr *Init = Args[ElementNo];
10083 
10084       LValue Subobject = This;
10085       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10086         return false;
10087 
10088       APValue &FieldVal = Result.getStructBase(ElementNo);
10089       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10090         if (!Info.noteFailure())
10091           return false;
10092         Success = false;
10093       }
10094       ++ElementNo;
10095     }
10096 
10097     EvalObj.finishedConstructingBases();
10098   }
10099 
10100   // Initialize members.
10101   for (const auto *Field : RD->fields()) {
10102     // Anonymous bit-fields are not considered members of the class for
10103     // purposes of aggregate initialization.
10104     if (Field->isUnnamedBitfield())
10105       continue;
10106 
10107     LValue Subobject = This;
10108 
10109     bool HaveInit = ElementNo < Args.size();
10110 
10111     // FIXME: Diagnostics here should point to the end of the initializer
10112     // list, not the start.
10113     if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10114                             Subobject, Field, &Layout))
10115       return false;
10116 
10117     // Perform an implicit value-initialization for members beyond the end of
10118     // the initializer list.
10119     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10120     const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10121 
10122     if (Field->getType()->isIncompleteArrayType()) {
10123       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10124         if (!CAT->getSize().isZero()) {
10125           // Bail out for now. This might sort of "work", but the rest of the
10126           // code isn't really prepared to handle it.
10127           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10128           return false;
10129         }
10130       }
10131     }
10132 
10133     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10134     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10135                                   isa<CXXDefaultInitExpr>(Init));
10136 
10137     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10138     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10139         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10140                                                        FieldVal, Field))) {
10141       if (!Info.noteFailure())
10142         return false;
10143       Success = false;
10144     }
10145   }
10146 
10147   EvalObj.finishedConstructingFields();
10148 
10149   return Success;
10150 }
10151 
10152 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10153                                                 QualType T) {
10154   // Note that E's type is not necessarily the type of our class here; we might
10155   // be initializing an array element instead.
10156   const CXXConstructorDecl *FD = E->getConstructor();
10157   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10158 
10159   bool ZeroInit = E->requiresZeroInitialization();
10160   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10161     // If we've already performed zero-initialization, we're already done.
10162     if (Result.hasValue())
10163       return true;
10164 
10165     if (ZeroInit)
10166       return ZeroInitialization(E, T);
10167 
10168     return getDefaultInitValue(T, Result);
10169   }
10170 
10171   const FunctionDecl *Definition = nullptr;
10172   auto Body = FD->getBody(Definition);
10173 
10174   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10175     return false;
10176 
10177   // Avoid materializing a temporary for an elidable copy/move constructor.
10178   if (E->isElidable() && !ZeroInit) {
10179     // FIXME: This only handles the simplest case, where the source object
10180     //        is passed directly as the first argument to the constructor.
10181     //        This should also handle stepping though implicit casts and
10182     //        and conversion sequences which involve two steps, with a
10183     //        conversion operator followed by a converting constructor.
10184     const Expr *SrcObj = E->getArg(0);
10185     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10186     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10187     if (const MaterializeTemporaryExpr *ME =
10188             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10189       return Visit(ME->getSubExpr());
10190   }
10191 
10192   if (ZeroInit && !ZeroInitialization(E, T))
10193     return false;
10194 
10195   auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10196   return HandleConstructorCall(E, This, Args,
10197                                cast<CXXConstructorDecl>(Definition), Info,
10198                                Result);
10199 }
10200 
10201 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10202     const CXXInheritedCtorInitExpr *E) {
10203   if (!Info.CurrentCall) {
10204     assert(Info.checkingPotentialConstantExpression());
10205     return false;
10206   }
10207 
10208   const CXXConstructorDecl *FD = E->getConstructor();
10209   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10210     return false;
10211 
10212   const FunctionDecl *Definition = nullptr;
10213   auto Body = FD->getBody(Definition);
10214 
10215   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10216     return false;
10217 
10218   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10219                                cast<CXXConstructorDecl>(Definition), Info,
10220                                Result);
10221 }
10222 
10223 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10224     const CXXStdInitializerListExpr *E) {
10225   const ConstantArrayType *ArrayType =
10226       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10227 
10228   LValue Array;
10229   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10230     return false;
10231 
10232   assert(ArrayType && "unexpected type for array initializer");
10233 
10234   // Get a pointer to the first element of the array.
10235   Array.addArray(Info, E, ArrayType);
10236 
10237   auto InvalidType = [&] {
10238     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10239       << E->getType();
10240     return false;
10241   };
10242 
10243   // FIXME: Perform the checks on the field types in SemaInit.
10244   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10245   RecordDecl::field_iterator Field = Record->field_begin();
10246   if (Field == Record->field_end())
10247     return InvalidType();
10248 
10249   // Start pointer.
10250   if (!Field->getType()->isPointerType() ||
10251       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10252                             ArrayType->getElementType()))
10253     return InvalidType();
10254 
10255   // FIXME: What if the initializer_list type has base classes, etc?
10256   Result = APValue(APValue::UninitStruct(), 0, 2);
10257   Array.moveInto(Result.getStructField(0));
10258 
10259   if (++Field == Record->field_end())
10260     return InvalidType();
10261 
10262   if (Field->getType()->isPointerType() &&
10263       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10264                            ArrayType->getElementType())) {
10265     // End pointer.
10266     if (!HandleLValueArrayAdjustment(Info, E, Array,
10267                                      ArrayType->getElementType(),
10268                                      ArrayType->getSize().getZExtValue()))
10269       return false;
10270     Array.moveInto(Result.getStructField(1));
10271   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10272     // Length.
10273     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10274   else
10275     return InvalidType();
10276 
10277   if (++Field != Record->field_end())
10278     return InvalidType();
10279 
10280   return true;
10281 }
10282 
10283 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10284   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10285   if (ClosureClass->isInvalidDecl())
10286     return false;
10287 
10288   const size_t NumFields =
10289       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10290 
10291   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10292                                             E->capture_init_end()) &&
10293          "The number of lambda capture initializers should equal the number of "
10294          "fields within the closure type");
10295 
10296   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10297   // Iterate through all the lambda's closure object's fields and initialize
10298   // them.
10299   auto *CaptureInitIt = E->capture_init_begin();
10300   bool Success = true;
10301   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10302   for (const auto *Field : ClosureClass->fields()) {
10303     assert(CaptureInitIt != E->capture_init_end());
10304     // Get the initializer for this field
10305     Expr *const CurFieldInit = *CaptureInitIt++;
10306 
10307     // If there is no initializer, either this is a VLA or an error has
10308     // occurred.
10309     if (!CurFieldInit)
10310       return Error(E);
10311 
10312     LValue Subobject = This;
10313 
10314     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10315       return false;
10316 
10317     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10318     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10319       if (!Info.keepEvaluatingAfterFailure())
10320         return false;
10321       Success = false;
10322     }
10323   }
10324   return Success;
10325 }
10326 
10327 static bool EvaluateRecord(const Expr *E, const LValue &This,
10328                            APValue &Result, EvalInfo &Info) {
10329   assert(!E->isValueDependent());
10330   assert(E->isPRValue() && E->getType()->isRecordType() &&
10331          "can't evaluate expression as a record rvalue");
10332   return RecordExprEvaluator(Info, This, Result).Visit(E);
10333 }
10334 
10335 //===----------------------------------------------------------------------===//
10336 // Temporary Evaluation
10337 //
10338 // Temporaries are represented in the AST as rvalues, but generally behave like
10339 // lvalues. The full-object of which the temporary is a subobject is implicitly
10340 // materialized so that a reference can bind to it.
10341 //===----------------------------------------------------------------------===//
10342 namespace {
10343 class TemporaryExprEvaluator
10344   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10345 public:
10346   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10347     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10348 
10349   /// Visit an expression which constructs the value of this temporary.
10350   bool VisitConstructExpr(const Expr *E) {
10351     APValue &Value = Info.CurrentCall->createTemporary(
10352         E, E->getType(), ScopeKind::FullExpression, Result);
10353     return EvaluateInPlace(Value, Info, Result, E);
10354   }
10355 
10356   bool VisitCastExpr(const CastExpr *E) {
10357     switch (E->getCastKind()) {
10358     default:
10359       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10360 
10361     case CK_ConstructorConversion:
10362       return VisitConstructExpr(E->getSubExpr());
10363     }
10364   }
10365   bool VisitInitListExpr(const InitListExpr *E) {
10366     return VisitConstructExpr(E);
10367   }
10368   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10369     return VisitConstructExpr(E);
10370   }
10371   bool VisitCallExpr(const CallExpr *E) {
10372     return VisitConstructExpr(E);
10373   }
10374   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10375     return VisitConstructExpr(E);
10376   }
10377   bool VisitLambdaExpr(const LambdaExpr *E) {
10378     return VisitConstructExpr(E);
10379   }
10380 };
10381 } // end anonymous namespace
10382 
10383 /// Evaluate an expression of record type as a temporary.
10384 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10385   assert(!E->isValueDependent());
10386   assert(E->isPRValue() && E->getType()->isRecordType());
10387   return TemporaryExprEvaluator(Info, Result).Visit(E);
10388 }
10389 
10390 //===----------------------------------------------------------------------===//
10391 // Vector Evaluation
10392 //===----------------------------------------------------------------------===//
10393 
10394 namespace {
10395   class VectorExprEvaluator
10396   : public ExprEvaluatorBase<VectorExprEvaluator> {
10397     APValue &Result;
10398   public:
10399 
10400     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10401       : ExprEvaluatorBaseTy(info), Result(Result) {}
10402 
10403     bool Success(ArrayRef<APValue> V, const Expr *E) {
10404       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10405       // FIXME: remove this APValue copy.
10406       Result = APValue(V.data(), V.size());
10407       return true;
10408     }
10409     bool Success(const APValue &V, const Expr *E) {
10410       assert(V.isVector());
10411       Result = V;
10412       return true;
10413     }
10414     bool ZeroInitialization(const Expr *E);
10415 
10416     bool VisitUnaryReal(const UnaryOperator *E)
10417       { return Visit(E->getSubExpr()); }
10418     bool VisitCastExpr(const CastExpr* E);
10419     bool VisitInitListExpr(const InitListExpr *E);
10420     bool VisitUnaryImag(const UnaryOperator *E);
10421     bool VisitBinaryOperator(const BinaryOperator *E);
10422     bool VisitUnaryOperator(const UnaryOperator *E);
10423     // FIXME: Missing: conditional operator (for GNU
10424     //                 conditional select), shufflevector, ExtVectorElementExpr
10425   };
10426 } // end anonymous namespace
10427 
10428 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10429   assert(E->isPRValue() && E->getType()->isVectorType() &&
10430          "not a vector prvalue");
10431   return VectorExprEvaluator(Info, Result).Visit(E);
10432 }
10433 
10434 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10435   const VectorType *VTy = E->getType()->castAs<VectorType>();
10436   unsigned NElts = VTy->getNumElements();
10437 
10438   const Expr *SE = E->getSubExpr();
10439   QualType SETy = SE->getType();
10440 
10441   switch (E->getCastKind()) {
10442   case CK_VectorSplat: {
10443     APValue Val = APValue();
10444     if (SETy->isIntegerType()) {
10445       APSInt IntResult;
10446       if (!EvaluateInteger(SE, IntResult, Info))
10447         return false;
10448       Val = APValue(std::move(IntResult));
10449     } else if (SETy->isRealFloatingType()) {
10450       APFloat FloatResult(0.0);
10451       if (!EvaluateFloat(SE, FloatResult, Info))
10452         return false;
10453       Val = APValue(std::move(FloatResult));
10454     } else {
10455       return Error(E);
10456     }
10457 
10458     // Splat and create vector APValue.
10459     SmallVector<APValue, 4> Elts(NElts, Val);
10460     return Success(Elts, E);
10461   }
10462   case CK_BitCast: {
10463     // Evaluate the operand into an APInt we can extract from.
10464     llvm::APInt SValInt;
10465     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10466       return false;
10467     // Extract the elements
10468     QualType EltTy = VTy->getElementType();
10469     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10470     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10471     SmallVector<APValue, 4> Elts;
10472     if (EltTy->isRealFloatingType()) {
10473       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10474       unsigned FloatEltSize = EltSize;
10475       if (&Sem == &APFloat::x87DoubleExtended())
10476         FloatEltSize = 80;
10477       for (unsigned i = 0; i < NElts; i++) {
10478         llvm::APInt Elt;
10479         if (BigEndian)
10480           Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10481         else
10482           Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10483         Elts.push_back(APValue(APFloat(Sem, Elt)));
10484       }
10485     } else if (EltTy->isIntegerType()) {
10486       for (unsigned i = 0; i < NElts; i++) {
10487         llvm::APInt Elt;
10488         if (BigEndian)
10489           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10490         else
10491           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10492         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10493       }
10494     } else {
10495       return Error(E);
10496     }
10497     return Success(Elts, E);
10498   }
10499   default:
10500     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10501   }
10502 }
10503 
10504 bool
10505 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10506   const VectorType *VT = E->getType()->castAs<VectorType>();
10507   unsigned NumInits = E->getNumInits();
10508   unsigned NumElements = VT->getNumElements();
10509 
10510   QualType EltTy = VT->getElementType();
10511   SmallVector<APValue, 4> Elements;
10512 
10513   // The number of initializers can be less than the number of
10514   // vector elements. For OpenCL, this can be due to nested vector
10515   // initialization. For GCC compatibility, missing trailing elements
10516   // should be initialized with zeroes.
10517   unsigned CountInits = 0, CountElts = 0;
10518   while (CountElts < NumElements) {
10519     // Handle nested vector initialization.
10520     if (CountInits < NumInits
10521         && E->getInit(CountInits)->getType()->isVectorType()) {
10522       APValue v;
10523       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10524         return Error(E);
10525       unsigned vlen = v.getVectorLength();
10526       for (unsigned j = 0; j < vlen; j++)
10527         Elements.push_back(v.getVectorElt(j));
10528       CountElts += vlen;
10529     } else if (EltTy->isIntegerType()) {
10530       llvm::APSInt sInt(32);
10531       if (CountInits < NumInits) {
10532         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10533           return false;
10534       } else // trailing integer zero.
10535         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10536       Elements.push_back(APValue(sInt));
10537       CountElts++;
10538     } else {
10539       llvm::APFloat f(0.0);
10540       if (CountInits < NumInits) {
10541         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10542           return false;
10543       } else // trailing float zero.
10544         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10545       Elements.push_back(APValue(f));
10546       CountElts++;
10547     }
10548     CountInits++;
10549   }
10550   return Success(Elements, E);
10551 }
10552 
10553 bool
10554 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10555   const auto *VT = E->getType()->castAs<VectorType>();
10556   QualType EltTy = VT->getElementType();
10557   APValue ZeroElement;
10558   if (EltTy->isIntegerType())
10559     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10560   else
10561     ZeroElement =
10562         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10563 
10564   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10565   return Success(Elements, E);
10566 }
10567 
10568 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10569   VisitIgnoredValue(E->getSubExpr());
10570   return ZeroInitialization(E);
10571 }
10572 
10573 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10574   BinaryOperatorKind Op = E->getOpcode();
10575   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10576          "Operation not supported on vector types");
10577 
10578   if (Op == BO_Comma)
10579     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10580 
10581   Expr *LHS = E->getLHS();
10582   Expr *RHS = E->getRHS();
10583 
10584   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10585          "Must both be vector types");
10586   // Checking JUST the types are the same would be fine, except shifts don't
10587   // need to have their types be the same (since you always shift by an int).
10588   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10589              E->getType()->castAs<VectorType>()->getNumElements() &&
10590          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10591              E->getType()->castAs<VectorType>()->getNumElements() &&
10592          "All operands must be the same size.");
10593 
10594   APValue LHSValue;
10595   APValue RHSValue;
10596   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10597   if (!LHSOK && !Info.noteFailure())
10598     return false;
10599   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10600     return false;
10601 
10602   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10603     return false;
10604 
10605   return Success(LHSValue, E);
10606 }
10607 
10608 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10609                                                         QualType ResultTy,
10610                                                         UnaryOperatorKind Op,
10611                                                         APValue Elt) {
10612   switch (Op) {
10613   case UO_Plus:
10614     // Nothing to do here.
10615     return Elt;
10616   case UO_Minus:
10617     if (Elt.getKind() == APValue::Int) {
10618       Elt.getInt().negate();
10619     } else {
10620       assert(Elt.getKind() == APValue::Float &&
10621              "Vector can only be int or float type");
10622       Elt.getFloat().changeSign();
10623     }
10624     return Elt;
10625   case UO_Not:
10626     // This is only valid for integral types anyway, so we don't have to handle
10627     // float here.
10628     assert(Elt.getKind() == APValue::Int &&
10629            "Vector operator ~ can only be int");
10630     Elt.getInt().flipAllBits();
10631     return Elt;
10632   case UO_LNot: {
10633     if (Elt.getKind() == APValue::Int) {
10634       Elt.getInt() = !Elt.getInt();
10635       // operator ! on vectors returns -1 for 'truth', so negate it.
10636       Elt.getInt().negate();
10637       return Elt;
10638     }
10639     assert(Elt.getKind() == APValue::Float &&
10640            "Vector can only be int or float type");
10641     // Float types result in an int of the same size, but -1 for true, or 0 for
10642     // false.
10643     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10644                      ResultTy->isUnsignedIntegerType()};
10645     if (Elt.getFloat().isZero())
10646       EltResult.setAllBits();
10647     else
10648       EltResult.clearAllBits();
10649 
10650     return APValue{EltResult};
10651   }
10652   default:
10653     // FIXME: Implement the rest of the unary operators.
10654     return std::nullopt;
10655   }
10656 }
10657 
10658 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10659   Expr *SubExpr = E->getSubExpr();
10660   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10661   // This result element type differs in the case of negating a floating point
10662   // vector, since the result type is the a vector of the equivilant sized
10663   // integer.
10664   const QualType ResultEltTy = VD->getElementType();
10665   UnaryOperatorKind Op = E->getOpcode();
10666 
10667   APValue SubExprValue;
10668   if (!Evaluate(SubExprValue, Info, SubExpr))
10669     return false;
10670 
10671   // FIXME: This vector evaluator someday needs to be changed to be LValue
10672   // aware/keep LValue information around, rather than dealing with just vector
10673   // types directly. Until then, we cannot handle cases where the operand to
10674   // these unary operators is an LValue. The only case I've been able to see
10675   // cause this is operator++ assigning to a member expression (only valid in
10676   // altivec compilations) in C mode, so this shouldn't limit us too much.
10677   if (SubExprValue.isLValue())
10678     return false;
10679 
10680   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10681          "Vector length doesn't match type?");
10682 
10683   SmallVector<APValue, 4> ResultElements;
10684   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10685     std::optional<APValue> Elt = handleVectorUnaryOperator(
10686         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10687     if (!Elt)
10688       return false;
10689     ResultElements.push_back(*Elt);
10690   }
10691   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10692 }
10693 
10694 //===----------------------------------------------------------------------===//
10695 // Array Evaluation
10696 //===----------------------------------------------------------------------===//
10697 
10698 namespace {
10699   class ArrayExprEvaluator
10700   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10701     const LValue &This;
10702     APValue &Result;
10703   public:
10704 
10705     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10706       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10707 
10708     bool Success(const APValue &V, const Expr *E) {
10709       assert(V.isArray() && "expected array");
10710       Result = V;
10711       return true;
10712     }
10713 
10714     bool ZeroInitialization(const Expr *E) {
10715       const ConstantArrayType *CAT =
10716           Info.Ctx.getAsConstantArrayType(E->getType());
10717       if (!CAT) {
10718         if (E->getType()->isIncompleteArrayType()) {
10719           // We can be asked to zero-initialize a flexible array member; this
10720           // is represented as an ImplicitValueInitExpr of incomplete array
10721           // type. In this case, the array has zero elements.
10722           Result = APValue(APValue::UninitArray(), 0, 0);
10723           return true;
10724         }
10725         // FIXME: We could handle VLAs here.
10726         return Error(E);
10727       }
10728 
10729       Result = APValue(APValue::UninitArray(), 0,
10730                        CAT->getSize().getZExtValue());
10731       if (!Result.hasArrayFiller())
10732         return true;
10733 
10734       // Zero-initialize all elements.
10735       LValue Subobject = This;
10736       Subobject.addArray(Info, E, CAT);
10737       ImplicitValueInitExpr VIE(CAT->getElementType());
10738       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10739     }
10740 
10741     bool VisitCallExpr(const CallExpr *E) {
10742       return handleCallExpr(E, Result, &This);
10743     }
10744     bool VisitInitListExpr(const InitListExpr *E,
10745                            QualType AllocType = QualType());
10746     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10747     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10748     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10749                                const LValue &Subobject,
10750                                APValue *Value, QualType Type);
10751     bool VisitStringLiteral(const StringLiteral *E,
10752                             QualType AllocType = QualType()) {
10753       expandStringLiteral(Info, E, Result, AllocType);
10754       return true;
10755     }
10756     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10757     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10758                                          ArrayRef<Expr *> Args,
10759                                          const Expr *ArrayFiller,
10760                                          QualType AllocType = QualType());
10761   };
10762 } // end anonymous namespace
10763 
10764 static bool EvaluateArray(const Expr *E, const LValue &This,
10765                           APValue &Result, EvalInfo &Info) {
10766   assert(!E->isValueDependent());
10767   assert(E->isPRValue() && E->getType()->isArrayType() &&
10768          "not an array prvalue");
10769   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10770 }
10771 
10772 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10773                                      APValue &Result, const InitListExpr *ILE,
10774                                      QualType AllocType) {
10775   assert(!ILE->isValueDependent());
10776   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10777          "not an array prvalue");
10778   return ArrayExprEvaluator(Info, This, Result)
10779       .VisitInitListExpr(ILE, AllocType);
10780 }
10781 
10782 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10783                                           APValue &Result,
10784                                           const CXXConstructExpr *CCE,
10785                                           QualType AllocType) {
10786   assert(!CCE->isValueDependent());
10787   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10788          "not an array prvalue");
10789   return ArrayExprEvaluator(Info, This, Result)
10790       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10791 }
10792 
10793 // Return true iff the given array filler may depend on the element index.
10794 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10795   // For now, just allow non-class value-initialization and initialization
10796   // lists comprised of them.
10797   if (isa<ImplicitValueInitExpr>(FillerExpr))
10798     return false;
10799   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10800     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10801       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10802         return true;
10803     }
10804 
10805     if (ILE->hasArrayFiller() &&
10806         MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
10807       return true;
10808 
10809     return false;
10810   }
10811   return true;
10812 }
10813 
10814 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10815                                            QualType AllocType) {
10816   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10817       AllocType.isNull() ? E->getType() : AllocType);
10818   if (!CAT)
10819     return Error(E);
10820 
10821   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10822   // an appropriately-typed string literal enclosed in braces.
10823   if (E->isStringLiteralInit()) {
10824     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10825     // FIXME: Support ObjCEncodeExpr here once we support it in
10826     // ArrayExprEvaluator generally.
10827     if (!SL)
10828       return Error(E);
10829     return VisitStringLiteral(SL, AllocType);
10830   }
10831   // Any other transparent list init will need proper handling of the
10832   // AllocType; we can't just recurse to the inner initializer.
10833   assert(!E->isTransparent() &&
10834          "transparent array list initialization is not string literal init?");
10835 
10836   return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
10837                                          AllocType);
10838 }
10839 
10840 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
10841     const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
10842     QualType AllocType) {
10843   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10844       AllocType.isNull() ? ExprToVisit->getType() : AllocType);
10845 
10846   bool Success = true;
10847 
10848   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10849          "zero-initialized array shouldn't have any initialized elts");
10850   APValue Filler;
10851   if (Result.isArray() && Result.hasArrayFiller())
10852     Filler = Result.getArrayFiller();
10853 
10854   unsigned NumEltsToInit = Args.size();
10855   unsigned NumElts = CAT->getSize().getZExtValue();
10856 
10857   // If the initializer might depend on the array index, run it for each
10858   // array element.
10859   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
10860     NumEltsToInit = NumElts;
10861 
10862   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10863                           << NumEltsToInit << ".\n");
10864 
10865   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10866 
10867   // If the array was previously zero-initialized, preserve the
10868   // zero-initialized values.
10869   if (Filler.hasValue()) {
10870     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10871       Result.getArrayInitializedElt(I) = Filler;
10872     if (Result.hasArrayFiller())
10873       Result.getArrayFiller() = Filler;
10874   }
10875 
10876   LValue Subobject = This;
10877   Subobject.addArray(Info, ExprToVisit, CAT);
10878   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10879     const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
10880     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10881                          Info, Subobject, Init) ||
10882         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10883                                      CAT->getElementType(), 1)) {
10884       if (!Info.noteFailure())
10885         return false;
10886       Success = false;
10887     }
10888   }
10889 
10890   if (!Result.hasArrayFiller())
10891     return Success;
10892 
10893   // If we get here, we have a trivial filler, which we can just evaluate
10894   // once and splat over the rest of the array elements.
10895   assert(ArrayFiller && "no array filler for incomplete init list");
10896   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10897                          ArrayFiller) &&
10898          Success;
10899 }
10900 
10901 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10902   LValue CommonLV;
10903   if (E->getCommonExpr() &&
10904       !Evaluate(Info.CurrentCall->createTemporary(
10905                     E->getCommonExpr(),
10906                     getStorageType(Info.Ctx, E->getCommonExpr()),
10907                     ScopeKind::FullExpression, CommonLV),
10908                 Info, E->getCommonExpr()->getSourceExpr()))
10909     return false;
10910 
10911   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10912 
10913   uint64_t Elements = CAT->getSize().getZExtValue();
10914   Result = APValue(APValue::UninitArray(), Elements, Elements);
10915 
10916   LValue Subobject = This;
10917   Subobject.addArray(Info, E, CAT);
10918 
10919   bool Success = true;
10920   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10921     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10922                          Info, Subobject, E->getSubExpr()) ||
10923         !HandleLValueArrayAdjustment(Info, E, Subobject,
10924                                      CAT->getElementType(), 1)) {
10925       if (!Info.noteFailure())
10926         return false;
10927       Success = false;
10928     }
10929   }
10930 
10931   return Success;
10932 }
10933 
10934 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10935   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10936 }
10937 
10938 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10939                                                const LValue &Subobject,
10940                                                APValue *Value,
10941                                                QualType Type) {
10942   bool HadZeroInit = Value->hasValue();
10943 
10944   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10945     unsigned FinalSize = CAT->getSize().getZExtValue();
10946 
10947     // Preserve the array filler if we had prior zero-initialization.
10948     APValue Filler =
10949       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10950                                              : APValue();
10951 
10952     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10953     if (FinalSize == 0)
10954       return true;
10955 
10956     bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
10957         Info, E->getExprLoc(), E->getConstructor(),
10958         E->requiresZeroInitialization());
10959     LValue ArrayElt = Subobject;
10960     ArrayElt.addArray(Info, E, CAT);
10961     // We do the whole initialization in two passes, first for just one element,
10962     // then for the whole array. It's possible we may find out we can't do const
10963     // init in the first pass, in which case we avoid allocating a potentially
10964     // large array. We don't do more passes because expanding array requires
10965     // copying the data, which is wasteful.
10966     for (const unsigned N : {1u, FinalSize}) {
10967       unsigned OldElts = Value->getArrayInitializedElts();
10968       if (OldElts == N)
10969         break;
10970 
10971       // Expand the array to appropriate size.
10972       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10973       for (unsigned I = 0; I < OldElts; ++I)
10974         NewValue.getArrayInitializedElt(I).swap(
10975             Value->getArrayInitializedElt(I));
10976       Value->swap(NewValue);
10977 
10978       if (HadZeroInit)
10979         for (unsigned I = OldElts; I < N; ++I)
10980           Value->getArrayInitializedElt(I) = Filler;
10981 
10982       if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
10983         // If we have a trivial constructor, only evaluate it once and copy
10984         // the result into all the array elements.
10985         APValue &FirstResult = Value->getArrayInitializedElt(0);
10986         for (unsigned I = OldElts; I < FinalSize; ++I)
10987           Value->getArrayInitializedElt(I) = FirstResult;
10988       } else {
10989         for (unsigned I = OldElts; I < N; ++I) {
10990           if (!VisitCXXConstructExpr(E, ArrayElt,
10991                                      &Value->getArrayInitializedElt(I),
10992                                      CAT->getElementType()) ||
10993               !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10994                                            CAT->getElementType(), 1))
10995             return false;
10996           // When checking for const initilization any diagnostic is considered
10997           // an error.
10998           if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10999               !Info.keepEvaluatingAfterFailure())
11000             return false;
11001         }
11002       }
11003     }
11004 
11005     return true;
11006   }
11007 
11008   if (!Type->isRecordType())
11009     return Error(E);
11010 
11011   return RecordExprEvaluator(Info, Subobject, *Value)
11012              .VisitCXXConstructExpr(E, Type);
11013 }
11014 
11015 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11016     const CXXParenListInitExpr *E) {
11017   assert(dyn_cast<ConstantArrayType>(E->getType()) &&
11018          "Expression result is not a constant array type");
11019 
11020   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11021                                          E->getArrayFiller());
11022 }
11023 
11024 //===----------------------------------------------------------------------===//
11025 // Integer Evaluation
11026 //
11027 // As a GNU extension, we support casting pointers to sufficiently-wide integer
11028 // types and back in constant folding. Integer values are thus represented
11029 // either as an integer-valued APValue, or as an lvalue-valued APValue.
11030 //===----------------------------------------------------------------------===//
11031 
11032 namespace {
11033 class IntExprEvaluator
11034         : public ExprEvaluatorBase<IntExprEvaluator> {
11035   APValue &Result;
11036 public:
11037   IntExprEvaluator(EvalInfo &info, APValue &result)
11038       : ExprEvaluatorBaseTy(info), Result(result) {}
11039 
11040   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11041     assert(E->getType()->isIntegralOrEnumerationType() &&
11042            "Invalid evaluation result.");
11043     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11044            "Invalid evaluation result.");
11045     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11046            "Invalid evaluation result.");
11047     Result = APValue(SI);
11048     return true;
11049   }
11050   bool Success(const llvm::APSInt &SI, const Expr *E) {
11051     return Success(SI, E, Result);
11052   }
11053 
11054   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11055     assert(E->getType()->isIntegralOrEnumerationType() &&
11056            "Invalid evaluation result.");
11057     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11058            "Invalid evaluation result.");
11059     Result = APValue(APSInt(I));
11060     Result.getInt().setIsUnsigned(
11061                             E->getType()->isUnsignedIntegerOrEnumerationType());
11062     return true;
11063   }
11064   bool Success(const llvm::APInt &I, const Expr *E) {
11065     return Success(I, E, Result);
11066   }
11067 
11068   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11069     assert(E->getType()->isIntegralOrEnumerationType() &&
11070            "Invalid evaluation result.");
11071     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11072     return true;
11073   }
11074   bool Success(uint64_t Value, const Expr *E) {
11075     return Success(Value, E, Result);
11076   }
11077 
11078   bool Success(CharUnits Size, const Expr *E) {
11079     return Success(Size.getQuantity(), E);
11080   }
11081 
11082   bool Success(const APValue &V, const Expr *E) {
11083     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11084       Result = V;
11085       return true;
11086     }
11087     return Success(V.getInt(), E);
11088   }
11089 
11090   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11091 
11092   //===--------------------------------------------------------------------===//
11093   //                            Visitor Methods
11094   //===--------------------------------------------------------------------===//
11095 
11096   bool VisitIntegerLiteral(const IntegerLiteral *E) {
11097     return Success(E->getValue(), E);
11098   }
11099   bool VisitCharacterLiteral(const CharacterLiteral *E) {
11100     return Success(E->getValue(), E);
11101   }
11102 
11103   bool CheckReferencedDecl(const Expr *E, const Decl *D);
11104   bool VisitDeclRefExpr(const DeclRefExpr *E) {
11105     if (CheckReferencedDecl(E, E->getDecl()))
11106       return true;
11107 
11108     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11109   }
11110   bool VisitMemberExpr(const MemberExpr *E) {
11111     if (CheckReferencedDecl(E, E->getMemberDecl())) {
11112       VisitIgnoredBaseExpression(E->getBase());
11113       return true;
11114     }
11115 
11116     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11117   }
11118 
11119   bool VisitCallExpr(const CallExpr *E);
11120   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11121   bool VisitBinaryOperator(const BinaryOperator *E);
11122   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11123   bool VisitUnaryOperator(const UnaryOperator *E);
11124 
11125   bool VisitCastExpr(const CastExpr* E);
11126   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11127 
11128   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11129     return Success(E->getValue(), E);
11130   }
11131 
11132   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11133     return Success(E->getValue(), E);
11134   }
11135 
11136   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11137     if (Info.ArrayInitIndex == uint64_t(-1)) {
11138       // We were asked to evaluate this subexpression independent of the
11139       // enclosing ArrayInitLoopExpr. We can't do that.
11140       Info.FFDiag(E);
11141       return false;
11142     }
11143     return Success(Info.ArrayInitIndex, E);
11144   }
11145 
11146   // Note, GNU defines __null as an integer, not a pointer.
11147   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11148     return ZeroInitialization(E);
11149   }
11150 
11151   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11152     return Success(E->getValue(), E);
11153   }
11154 
11155   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11156     return Success(E->getValue(), E);
11157   }
11158 
11159   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11160     return Success(E->getValue(), E);
11161   }
11162 
11163   bool VisitUnaryReal(const UnaryOperator *E);
11164   bool VisitUnaryImag(const UnaryOperator *E);
11165 
11166   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11167   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11168   bool VisitSourceLocExpr(const SourceLocExpr *E);
11169   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11170   bool VisitRequiresExpr(const RequiresExpr *E);
11171   // FIXME: Missing: array subscript of vector, member of vector
11172 };
11173 
11174 class FixedPointExprEvaluator
11175     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11176   APValue &Result;
11177 
11178  public:
11179   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11180       : ExprEvaluatorBaseTy(info), Result(result) {}
11181 
11182   bool Success(const llvm::APInt &I, const Expr *E) {
11183     return Success(
11184         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11185   }
11186 
11187   bool Success(uint64_t Value, const Expr *E) {
11188     return Success(
11189         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11190   }
11191 
11192   bool Success(const APValue &V, const Expr *E) {
11193     return Success(V.getFixedPoint(), E);
11194   }
11195 
11196   bool Success(const APFixedPoint &V, const Expr *E) {
11197     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11198     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11199            "Invalid evaluation result.");
11200     Result = APValue(V);
11201     return true;
11202   }
11203 
11204   //===--------------------------------------------------------------------===//
11205   //                            Visitor Methods
11206   //===--------------------------------------------------------------------===//
11207 
11208   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11209     return Success(E->getValue(), E);
11210   }
11211 
11212   bool VisitCastExpr(const CastExpr *E);
11213   bool VisitUnaryOperator(const UnaryOperator *E);
11214   bool VisitBinaryOperator(const BinaryOperator *E);
11215 };
11216 } // end anonymous namespace
11217 
11218 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11219 /// produce either the integer value or a pointer.
11220 ///
11221 /// GCC has a heinous extension which folds casts between pointer types and
11222 /// pointer-sized integral types. We support this by allowing the evaluation of
11223 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11224 /// Some simple arithmetic on such values is supported (they are treated much
11225 /// like char*).
11226 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11227                                     EvalInfo &Info) {
11228   assert(!E->isValueDependent());
11229   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11230   return IntExprEvaluator(Info, Result).Visit(E);
11231 }
11232 
11233 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11234   assert(!E->isValueDependent());
11235   APValue Val;
11236   if (!EvaluateIntegerOrLValue(E, Val, Info))
11237     return false;
11238   if (!Val.isInt()) {
11239     // FIXME: It would be better to produce the diagnostic for casting
11240     //        a pointer to an integer.
11241     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11242     return false;
11243   }
11244   Result = Val.getInt();
11245   return true;
11246 }
11247 
11248 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11249   APValue Evaluated = E->EvaluateInContext(
11250       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11251   return Success(Evaluated, E);
11252 }
11253 
11254 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11255                                EvalInfo &Info) {
11256   assert(!E->isValueDependent());
11257   if (E->getType()->isFixedPointType()) {
11258     APValue Val;
11259     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11260       return false;
11261     if (!Val.isFixedPoint())
11262       return false;
11263 
11264     Result = Val.getFixedPoint();
11265     return true;
11266   }
11267   return false;
11268 }
11269 
11270 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11271                                         EvalInfo &Info) {
11272   assert(!E->isValueDependent());
11273   if (E->getType()->isIntegerType()) {
11274     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11275     APSInt Val;
11276     if (!EvaluateInteger(E, Val, Info))
11277       return false;
11278     Result = APFixedPoint(Val, FXSema);
11279     return true;
11280   } else if (E->getType()->isFixedPointType()) {
11281     return EvaluateFixedPoint(E, Result, Info);
11282   }
11283   return false;
11284 }
11285 
11286 /// Check whether the given declaration can be directly converted to an integral
11287 /// rvalue. If not, no diagnostic is produced; there are other things we can
11288 /// try.
11289 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11290   // Enums are integer constant exprs.
11291   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11292     // Check for signedness/width mismatches between E type and ECD value.
11293     bool SameSign = (ECD->getInitVal().isSigned()
11294                      == E->getType()->isSignedIntegerOrEnumerationType());
11295     bool SameWidth = (ECD->getInitVal().getBitWidth()
11296                       == Info.Ctx.getIntWidth(E->getType()));
11297     if (SameSign && SameWidth)
11298       return Success(ECD->getInitVal(), E);
11299     else {
11300       // Get rid of mismatch (otherwise Success assertions will fail)
11301       // by computing a new value matching the type of E.
11302       llvm::APSInt Val = ECD->getInitVal();
11303       if (!SameSign)
11304         Val.setIsSigned(!ECD->getInitVal().isSigned());
11305       if (!SameWidth)
11306         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11307       return Success(Val, E);
11308     }
11309   }
11310   return false;
11311 }
11312 
11313 /// Values returned by __builtin_classify_type, chosen to match the values
11314 /// produced by GCC's builtin.
11315 enum class GCCTypeClass {
11316   None = -1,
11317   Void = 0,
11318   Integer = 1,
11319   // GCC reserves 2 for character types, but instead classifies them as
11320   // integers.
11321   Enum = 3,
11322   Bool = 4,
11323   Pointer = 5,
11324   // GCC reserves 6 for references, but appears to never use it (because
11325   // expressions never have reference type, presumably).
11326   PointerToDataMember = 7,
11327   RealFloat = 8,
11328   Complex = 9,
11329   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11330   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11331   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11332   // uses 12 for that purpose, same as for a class or struct. Maybe it
11333   // internally implements a pointer to member as a struct?  Who knows.
11334   PointerToMemberFunction = 12, // Not a bug, see above.
11335   ClassOrStruct = 12,
11336   Union = 13,
11337   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11338   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11339   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11340   // literals.
11341 };
11342 
11343 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11344 /// as GCC.
11345 static GCCTypeClass
11346 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11347   assert(!T->isDependentType() && "unexpected dependent type");
11348 
11349   QualType CanTy = T.getCanonicalType();
11350 
11351   switch (CanTy->getTypeClass()) {
11352 #define TYPE(ID, BASE)
11353 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11354 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11355 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11356 #include "clang/AST/TypeNodes.inc"
11357   case Type::Auto:
11358   case Type::DeducedTemplateSpecialization:
11359       llvm_unreachable("unexpected non-canonical or dependent type");
11360 
11361   case Type::Builtin:
11362       switch (cast<BuiltinType>(CanTy)->getKind()) {
11363 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11364 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11365     case BuiltinType::ID: return GCCTypeClass::Integer;
11366 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11367     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11368 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11369     case BuiltinType::ID: break;
11370 #include "clang/AST/BuiltinTypes.def"
11371     case BuiltinType::Void:
11372       return GCCTypeClass::Void;
11373 
11374     case BuiltinType::Bool:
11375       return GCCTypeClass::Bool;
11376 
11377     case BuiltinType::Char_U:
11378     case BuiltinType::UChar:
11379     case BuiltinType::WChar_U:
11380     case BuiltinType::Char8:
11381     case BuiltinType::Char16:
11382     case BuiltinType::Char32:
11383     case BuiltinType::UShort:
11384     case BuiltinType::UInt:
11385     case BuiltinType::ULong:
11386     case BuiltinType::ULongLong:
11387     case BuiltinType::UInt128:
11388       return GCCTypeClass::Integer;
11389 
11390     case BuiltinType::UShortAccum:
11391     case BuiltinType::UAccum:
11392     case BuiltinType::ULongAccum:
11393     case BuiltinType::UShortFract:
11394     case BuiltinType::UFract:
11395     case BuiltinType::ULongFract:
11396     case BuiltinType::SatUShortAccum:
11397     case BuiltinType::SatUAccum:
11398     case BuiltinType::SatULongAccum:
11399     case BuiltinType::SatUShortFract:
11400     case BuiltinType::SatUFract:
11401     case BuiltinType::SatULongFract:
11402       return GCCTypeClass::None;
11403 
11404     case BuiltinType::NullPtr:
11405 
11406     case BuiltinType::ObjCId:
11407     case BuiltinType::ObjCClass:
11408     case BuiltinType::ObjCSel:
11409 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11410     case BuiltinType::Id:
11411 #include "clang/Basic/OpenCLImageTypes.def"
11412 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11413     case BuiltinType::Id:
11414 #include "clang/Basic/OpenCLExtensionTypes.def"
11415     case BuiltinType::OCLSampler:
11416     case BuiltinType::OCLEvent:
11417     case BuiltinType::OCLClkEvent:
11418     case BuiltinType::OCLQueue:
11419     case BuiltinType::OCLReserveID:
11420 #define SVE_TYPE(Name, Id, SingletonId) \
11421     case BuiltinType::Id:
11422 #include "clang/Basic/AArch64SVEACLETypes.def"
11423 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11424     case BuiltinType::Id:
11425 #include "clang/Basic/PPCTypes.def"
11426 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11427 #include "clang/Basic/RISCVVTypes.def"
11428 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11429 #include "clang/Basic/WebAssemblyReferenceTypes.def"
11430       return GCCTypeClass::None;
11431 
11432     case BuiltinType::Dependent:
11433       llvm_unreachable("unexpected dependent type");
11434     };
11435     llvm_unreachable("unexpected placeholder type");
11436 
11437   case Type::Enum:
11438     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11439 
11440   case Type::Pointer:
11441   case Type::ConstantArray:
11442   case Type::VariableArray:
11443   case Type::IncompleteArray:
11444   case Type::FunctionNoProto:
11445   case Type::FunctionProto:
11446     return GCCTypeClass::Pointer;
11447 
11448   case Type::MemberPointer:
11449     return CanTy->isMemberDataPointerType()
11450                ? GCCTypeClass::PointerToDataMember
11451                : GCCTypeClass::PointerToMemberFunction;
11452 
11453   case Type::Complex:
11454     return GCCTypeClass::Complex;
11455 
11456   case Type::Record:
11457     return CanTy->isUnionType() ? GCCTypeClass::Union
11458                                 : GCCTypeClass::ClassOrStruct;
11459 
11460   case Type::Atomic:
11461     // GCC classifies _Atomic T the same as T.
11462     return EvaluateBuiltinClassifyType(
11463         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11464 
11465   case Type::BlockPointer:
11466   case Type::Vector:
11467   case Type::ExtVector:
11468   case Type::ConstantMatrix:
11469   case Type::ObjCObject:
11470   case Type::ObjCInterface:
11471   case Type::ObjCObjectPointer:
11472   case Type::Pipe:
11473   case Type::BitInt:
11474     // GCC classifies vectors as None. We follow its lead and classify all
11475     // other types that don't fit into the regular classification the same way.
11476     return GCCTypeClass::None;
11477 
11478   case Type::LValueReference:
11479   case Type::RValueReference:
11480     llvm_unreachable("invalid type for expression");
11481   }
11482 
11483   llvm_unreachable("unexpected type class");
11484 }
11485 
11486 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11487 /// as GCC.
11488 static GCCTypeClass
11489 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11490   // If no argument was supplied, default to None. This isn't
11491   // ideal, however it is what gcc does.
11492   if (E->getNumArgs() == 0)
11493     return GCCTypeClass::None;
11494 
11495   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11496   // being an ICE, but still folds it to a constant using the type of the first
11497   // argument.
11498   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11499 }
11500 
11501 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11502 /// __builtin_constant_p when applied to the given pointer.
11503 ///
11504 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11505 /// or it points to the first character of a string literal.
11506 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11507   APValue::LValueBase Base = LV.getLValueBase();
11508   if (Base.isNull()) {
11509     // A null base is acceptable.
11510     return true;
11511   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11512     if (!isa<StringLiteral>(E))
11513       return false;
11514     return LV.getLValueOffset().isZero();
11515   } else if (Base.is<TypeInfoLValue>()) {
11516     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11517     // evaluate to true.
11518     return true;
11519   } else {
11520     // Any other base is not constant enough for GCC.
11521     return false;
11522   }
11523 }
11524 
11525 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11526 /// GCC as we can manage.
11527 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11528   // This evaluation is not permitted to have side-effects, so evaluate it in
11529   // a speculative evaluation context.
11530   SpeculativeEvaluationRAII SpeculativeEval(Info);
11531 
11532   // Constant-folding is always enabled for the operand of __builtin_constant_p
11533   // (even when the enclosing evaluation context otherwise requires a strict
11534   // language-specific constant expression).
11535   FoldConstant Fold(Info, true);
11536 
11537   QualType ArgType = Arg->getType();
11538 
11539   // __builtin_constant_p always has one operand. The rules which gcc follows
11540   // are not precisely documented, but are as follows:
11541   //
11542   //  - If the operand is of integral, floating, complex or enumeration type,
11543   //    and can be folded to a known value of that type, it returns 1.
11544   //  - If the operand can be folded to a pointer to the first character
11545   //    of a string literal (or such a pointer cast to an integral type)
11546   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11547   //
11548   // Otherwise, it returns 0.
11549   //
11550   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11551   // its support for this did not work prior to GCC 9 and is not yet well
11552   // understood.
11553   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11554       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11555       ArgType->isNullPtrType()) {
11556     APValue V;
11557     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11558       Fold.keepDiagnostics();
11559       return false;
11560     }
11561 
11562     // For a pointer (possibly cast to integer), there are special rules.
11563     if (V.getKind() == APValue::LValue)
11564       return EvaluateBuiltinConstantPForLValue(V);
11565 
11566     // Otherwise, any constant value is good enough.
11567     return V.hasValue();
11568   }
11569 
11570   // Anything else isn't considered to be sufficiently constant.
11571   return false;
11572 }
11573 
11574 /// Retrieves the "underlying object type" of the given expression,
11575 /// as used by __builtin_object_size.
11576 static QualType getObjectType(APValue::LValueBase B) {
11577   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11578     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11579       return VD->getType();
11580   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11581     if (isa<CompoundLiteralExpr>(E))
11582       return E->getType();
11583   } else if (B.is<TypeInfoLValue>()) {
11584     return B.getTypeInfoType();
11585   } else if (B.is<DynamicAllocLValue>()) {
11586     return B.getDynamicAllocType();
11587   }
11588 
11589   return QualType();
11590 }
11591 
11592 /// A more selective version of E->IgnoreParenCasts for
11593 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11594 /// to change the type of E.
11595 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11596 ///
11597 /// Always returns an RValue with a pointer representation.
11598 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11599   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11600 
11601   auto *NoParens = E->IgnoreParens();
11602   auto *Cast = dyn_cast<CastExpr>(NoParens);
11603   if (Cast == nullptr)
11604     return NoParens;
11605 
11606   // We only conservatively allow a few kinds of casts, because this code is
11607   // inherently a simple solution that seeks to support the common case.
11608   auto CastKind = Cast->getCastKind();
11609   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11610       CastKind != CK_AddressSpaceConversion)
11611     return NoParens;
11612 
11613   auto *SubExpr = Cast->getSubExpr();
11614   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11615     return NoParens;
11616   return ignorePointerCastsAndParens(SubExpr);
11617 }
11618 
11619 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11620 /// record layout. e.g.
11621 ///   struct { struct { int a, b; } fst, snd; } obj;
11622 ///   obj.fst   // no
11623 ///   obj.snd   // yes
11624 ///   obj.fst.a // no
11625 ///   obj.fst.b // no
11626 ///   obj.snd.a // no
11627 ///   obj.snd.b // yes
11628 ///
11629 /// Please note: this function is specialized for how __builtin_object_size
11630 /// views "objects".
11631 ///
11632 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11633 /// correct result, it will always return true.
11634 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11635   assert(!LVal.Designator.Invalid);
11636 
11637   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11638     const RecordDecl *Parent = FD->getParent();
11639     Invalid = Parent->isInvalidDecl();
11640     if (Invalid || Parent->isUnion())
11641       return true;
11642     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11643     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11644   };
11645 
11646   auto &Base = LVal.getLValueBase();
11647   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11648     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11649       bool Invalid;
11650       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11651         return Invalid;
11652     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11653       for (auto *FD : IFD->chain()) {
11654         bool Invalid;
11655         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11656           return Invalid;
11657       }
11658     }
11659   }
11660 
11661   unsigned I = 0;
11662   QualType BaseType = getType(Base);
11663   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11664     // If we don't know the array bound, conservatively assume we're looking at
11665     // the final array element.
11666     ++I;
11667     if (BaseType->isIncompleteArrayType())
11668       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11669     else
11670       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11671   }
11672 
11673   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11674     const auto &Entry = LVal.Designator.Entries[I];
11675     if (BaseType->isArrayType()) {
11676       // Because __builtin_object_size treats arrays as objects, we can ignore
11677       // the index iff this is the last array in the Designator.
11678       if (I + 1 == E)
11679         return true;
11680       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11681       uint64_t Index = Entry.getAsArrayIndex();
11682       if (Index + 1 != CAT->getSize())
11683         return false;
11684       BaseType = CAT->getElementType();
11685     } else if (BaseType->isAnyComplexType()) {
11686       const auto *CT = BaseType->castAs<ComplexType>();
11687       uint64_t Index = Entry.getAsArrayIndex();
11688       if (Index != 1)
11689         return false;
11690       BaseType = CT->getElementType();
11691     } else if (auto *FD = getAsField(Entry)) {
11692       bool Invalid;
11693       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11694         return Invalid;
11695       BaseType = FD->getType();
11696     } else {
11697       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11698       return false;
11699     }
11700   }
11701   return true;
11702 }
11703 
11704 /// Tests to see if the LValue has a user-specified designator (that isn't
11705 /// necessarily valid). Note that this always returns 'true' if the LValue has
11706 /// an unsized array as its first designator entry, because there's currently no
11707 /// way to tell if the user typed *foo or foo[0].
11708 static bool refersToCompleteObject(const LValue &LVal) {
11709   if (LVal.Designator.Invalid)
11710     return false;
11711 
11712   if (!LVal.Designator.Entries.empty())
11713     return LVal.Designator.isMostDerivedAnUnsizedArray();
11714 
11715   if (!LVal.InvalidBase)
11716     return true;
11717 
11718   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11719   // the LValueBase.
11720   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11721   return !E || !isa<MemberExpr>(E);
11722 }
11723 
11724 /// Attempts to detect a user writing into a piece of memory that's impossible
11725 /// to figure out the size of by just using types.
11726 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11727   const SubobjectDesignator &Designator = LVal.Designator;
11728   // Notes:
11729   // - Users can only write off of the end when we have an invalid base. Invalid
11730   //   bases imply we don't know where the memory came from.
11731   // - We used to be a bit more aggressive here; we'd only be conservative if
11732   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11733   //   broke some common standard library extensions (PR30346), but was
11734   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11735   //   with some sort of list. OTOH, it seems that GCC is always
11736   //   conservative with the last element in structs (if it's an array), so our
11737   //   current behavior is more compatible than an explicit list approach would
11738   //   be.
11739   auto isFlexibleArrayMember = [&] {
11740     using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11741     FAMKind StrictFlexArraysLevel =
11742         Ctx.getLangOpts().getStrictFlexArraysLevel();
11743 
11744     if (Designator.isMostDerivedAnUnsizedArray())
11745       return true;
11746 
11747     if (StrictFlexArraysLevel == FAMKind::Default)
11748       return true;
11749 
11750     if (Designator.getMostDerivedArraySize() == 0 &&
11751         StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11752       return true;
11753 
11754     if (Designator.getMostDerivedArraySize() == 1 &&
11755         StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11756       return true;
11757 
11758     return false;
11759   };
11760 
11761   return LVal.InvalidBase &&
11762          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11763          Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11764          isDesignatorAtObjectEnd(Ctx, LVal);
11765 }
11766 
11767 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11768 /// Fails if the conversion would cause loss of precision.
11769 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11770                                             CharUnits &Result) {
11771   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11772   if (Int.ugt(CharUnitsMax))
11773     return false;
11774   Result = CharUnits::fromQuantity(Int.getZExtValue());
11775   return true;
11776 }
11777 
11778 /// If we're evaluating the object size of an instance of a struct that
11779 /// contains a flexible array member, add the size of the initializer.
11780 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
11781                                            const LValue &LV, CharUnits &Size) {
11782   if (!T.isNull() && T->isStructureType() &&
11783       T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
11784     if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
11785       if (const auto *VD = dyn_cast<VarDecl>(V))
11786         if (VD->hasInit())
11787           Size += VD->getFlexibleArrayInitChars(Info.Ctx);
11788 }
11789 
11790 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11791 /// determine how many bytes exist from the beginning of the object to either
11792 /// the end of the current subobject, or the end of the object itself, depending
11793 /// on what the LValue looks like + the value of Type.
11794 ///
11795 /// If this returns false, the value of Result is undefined.
11796 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11797                                unsigned Type, const LValue &LVal,
11798                                CharUnits &EndOffset) {
11799   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11800 
11801   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11802     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11803       return false;
11804     return HandleSizeof(Info, ExprLoc, Ty, Result);
11805   };
11806 
11807   // We want to evaluate the size of the entire object. This is a valid fallback
11808   // for when Type=1 and the designator is invalid, because we're asked for an
11809   // upper-bound.
11810   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11811     // Type=3 wants a lower bound, so we can't fall back to this.
11812     if (Type == 3 && !DetermineForCompleteObject)
11813       return false;
11814 
11815     llvm::APInt APEndOffset;
11816     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11817         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11818       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11819 
11820     if (LVal.InvalidBase)
11821       return false;
11822 
11823     QualType BaseTy = getObjectType(LVal.getLValueBase());
11824     const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
11825     addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
11826     return Ret;
11827   }
11828 
11829   // We want to evaluate the size of a subobject.
11830   const SubobjectDesignator &Designator = LVal.Designator;
11831 
11832   // The following is a moderately common idiom in C:
11833   //
11834   // struct Foo { int a; char c[1]; };
11835   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11836   // strcpy(&F->c[0], Bar);
11837   //
11838   // In order to not break too much legacy code, we need to support it.
11839   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11840     // If we can resolve this to an alloc_size call, we can hand that back,
11841     // because we know for certain how many bytes there are to write to.
11842     llvm::APInt APEndOffset;
11843     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11844         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11845       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11846 
11847     // If we cannot determine the size of the initial allocation, then we can't
11848     // given an accurate upper-bound. However, we are still able to give
11849     // conservative lower-bounds for Type=3.
11850     if (Type == 1)
11851       return false;
11852   }
11853 
11854   CharUnits BytesPerElem;
11855   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11856     return false;
11857 
11858   // According to the GCC documentation, we want the size of the subobject
11859   // denoted by the pointer. But that's not quite right -- what we actually
11860   // want is the size of the immediately-enclosing array, if there is one.
11861   int64_t ElemsRemaining;
11862   if (Designator.MostDerivedIsArrayElement &&
11863       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11864     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11865     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11866     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11867   } else {
11868     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11869   }
11870 
11871   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11872   return true;
11873 }
11874 
11875 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11876 /// returns true and stores the result in @p Size.
11877 ///
11878 /// If @p WasError is non-null, this will report whether the failure to evaluate
11879 /// is to be treated as an Error in IntExprEvaluator.
11880 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11881                                          EvalInfo &Info, uint64_t &Size) {
11882   // Determine the denoted object.
11883   LValue LVal;
11884   {
11885     // The operand of __builtin_object_size is never evaluated for side-effects.
11886     // If there are any, but we can determine the pointed-to object anyway, then
11887     // ignore the side-effects.
11888     SpeculativeEvaluationRAII SpeculativeEval(Info);
11889     IgnoreSideEffectsRAII Fold(Info);
11890 
11891     if (E->isGLValue()) {
11892       // It's possible for us to be given GLValues if we're called via
11893       // Expr::tryEvaluateObjectSize.
11894       APValue RVal;
11895       if (!EvaluateAsRValue(Info, E, RVal))
11896         return false;
11897       LVal.setFrom(Info.Ctx, RVal);
11898     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11899                                 /*InvalidBaseOK=*/true))
11900       return false;
11901   }
11902 
11903   // If we point to before the start of the object, there are no accessible
11904   // bytes.
11905   if (LVal.getLValueOffset().isNegative()) {
11906     Size = 0;
11907     return true;
11908   }
11909 
11910   CharUnits EndOffset;
11911   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11912     return false;
11913 
11914   // If we've fallen outside of the end offset, just pretend there's nothing to
11915   // write to/read from.
11916   if (EndOffset <= LVal.getLValueOffset())
11917     Size = 0;
11918   else
11919     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11920   return true;
11921 }
11922 
11923 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11924   if (!IsConstantEvaluatedBuiltinCall(E))
11925     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11926   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
11927 }
11928 
11929 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11930                                      APValue &Val, APSInt &Alignment) {
11931   QualType SrcTy = E->getArg(0)->getType();
11932   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11933     return false;
11934   // Even though we are evaluating integer expressions we could get a pointer
11935   // argument for the __builtin_is_aligned() case.
11936   if (SrcTy->isPointerType()) {
11937     LValue Ptr;
11938     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11939       return false;
11940     Ptr.moveInto(Val);
11941   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11942     Info.FFDiag(E->getArg(0));
11943     return false;
11944   } else {
11945     APSInt SrcInt;
11946     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11947       return false;
11948     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11949            "Bit widths must be the same");
11950     Val = APValue(SrcInt);
11951   }
11952   assert(Val.hasValue());
11953   return true;
11954 }
11955 
11956 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11957                                             unsigned BuiltinOp) {
11958   switch (BuiltinOp) {
11959   default:
11960     return false;
11961 
11962   case Builtin::BI__builtin_dynamic_object_size:
11963   case Builtin::BI__builtin_object_size: {
11964     // The type was checked when we built the expression.
11965     unsigned Type =
11966         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11967     assert(Type <= 3 && "unexpected type");
11968 
11969     uint64_t Size;
11970     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11971       return Success(Size, E);
11972 
11973     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11974       return Success((Type & 2) ? 0 : -1, E);
11975 
11976     // Expression had no side effects, but we couldn't statically determine the
11977     // size of the referenced object.
11978     switch (Info.EvalMode) {
11979     case EvalInfo::EM_ConstantExpression:
11980     case EvalInfo::EM_ConstantFold:
11981     case EvalInfo::EM_IgnoreSideEffects:
11982       // Leave it to IR generation.
11983       return Error(E);
11984     case EvalInfo::EM_ConstantExpressionUnevaluated:
11985       // Reduce it to a constant now.
11986       return Success((Type & 2) ? 0 : -1, E);
11987     }
11988 
11989     llvm_unreachable("unexpected EvalMode");
11990   }
11991 
11992   case Builtin::BI__builtin_os_log_format_buffer_size: {
11993     analyze_os_log::OSLogBufferLayout Layout;
11994     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11995     return Success(Layout.size().getQuantity(), E);
11996   }
11997 
11998   case Builtin::BI__builtin_is_aligned: {
11999     APValue Src;
12000     APSInt Alignment;
12001     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12002       return false;
12003     if (Src.isLValue()) {
12004       // If we evaluated a pointer, check the minimum known alignment.
12005       LValue Ptr;
12006       Ptr.setFrom(Info.Ctx, Src);
12007       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12008       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12009       // We can return true if the known alignment at the computed offset is
12010       // greater than the requested alignment.
12011       assert(PtrAlign.isPowerOfTwo());
12012       assert(Alignment.isPowerOf2());
12013       if (PtrAlign.getQuantity() >= Alignment)
12014         return Success(1, E);
12015       // If the alignment is not known to be sufficient, some cases could still
12016       // be aligned at run time. However, if the requested alignment is less or
12017       // equal to the base alignment and the offset is not aligned, we know that
12018       // the run-time value can never be aligned.
12019       if (BaseAlignment.getQuantity() >= Alignment &&
12020           PtrAlign.getQuantity() < Alignment)
12021         return Success(0, E);
12022       // Otherwise we can't infer whether the value is sufficiently aligned.
12023       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12024       //  in cases where we can't fully evaluate the pointer.
12025       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12026           << Alignment;
12027       return false;
12028     }
12029     assert(Src.isInt());
12030     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12031   }
12032   case Builtin::BI__builtin_align_up: {
12033     APValue Src;
12034     APSInt Alignment;
12035     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12036       return false;
12037     if (!Src.isInt())
12038       return Error(E);
12039     APSInt AlignedVal =
12040         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12041                Src.getInt().isUnsigned());
12042     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12043     return Success(AlignedVal, E);
12044   }
12045   case Builtin::BI__builtin_align_down: {
12046     APValue Src;
12047     APSInt Alignment;
12048     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12049       return false;
12050     if (!Src.isInt())
12051       return Error(E);
12052     APSInt AlignedVal =
12053         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12054     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12055     return Success(AlignedVal, E);
12056   }
12057 
12058   case Builtin::BI__builtin_bitreverse8:
12059   case Builtin::BI__builtin_bitreverse16:
12060   case Builtin::BI__builtin_bitreverse32:
12061   case Builtin::BI__builtin_bitreverse64: {
12062     APSInt Val;
12063     if (!EvaluateInteger(E->getArg(0), Val, Info))
12064       return false;
12065 
12066     return Success(Val.reverseBits(), E);
12067   }
12068 
12069   case Builtin::BI__builtin_bswap16:
12070   case Builtin::BI__builtin_bswap32:
12071   case Builtin::BI__builtin_bswap64: {
12072     APSInt Val;
12073     if (!EvaluateInteger(E->getArg(0), Val, Info))
12074       return false;
12075 
12076     return Success(Val.byteSwap(), E);
12077   }
12078 
12079   case Builtin::BI__builtin_classify_type:
12080     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12081 
12082   case Builtin::BI__builtin_clrsb:
12083   case Builtin::BI__builtin_clrsbl:
12084   case Builtin::BI__builtin_clrsbll: {
12085     APSInt Val;
12086     if (!EvaluateInteger(E->getArg(0), Val, Info))
12087       return false;
12088 
12089     return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12090   }
12091 
12092   case Builtin::BI__builtin_clz:
12093   case Builtin::BI__builtin_clzl:
12094   case Builtin::BI__builtin_clzll:
12095   case Builtin::BI__builtin_clzs: {
12096     APSInt Val;
12097     if (!EvaluateInteger(E->getArg(0), Val, Info))
12098       return false;
12099     if (!Val)
12100       return Error(E);
12101 
12102     return Success(Val.countl_zero(), E);
12103   }
12104 
12105   case Builtin::BI__builtin_constant_p: {
12106     const Expr *Arg = E->getArg(0);
12107     if (EvaluateBuiltinConstantP(Info, Arg))
12108       return Success(true, E);
12109     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12110       // Outside a constant context, eagerly evaluate to false in the presence
12111       // of side-effects in order to avoid -Wunsequenced false-positives in
12112       // a branch on __builtin_constant_p(expr).
12113       return Success(false, E);
12114     }
12115     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12116     return false;
12117   }
12118 
12119   case Builtin::BI__builtin_is_constant_evaluated: {
12120     const auto *Callee = Info.CurrentCall->getCallee();
12121     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12122         (Info.CallStackDepth == 1 ||
12123          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12124           Callee->getIdentifier() &&
12125           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12126       // FIXME: Find a better way to avoid duplicated diagnostics.
12127       if (Info.EvalStatus.Diag)
12128         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
12129                                                : Info.CurrentCall->CallLoc,
12130                     diag::warn_is_constant_evaluated_always_true_constexpr)
12131             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12132                                          : "std::is_constant_evaluated");
12133     }
12134 
12135     return Success(Info.InConstantContext, E);
12136   }
12137 
12138   case Builtin::BI__builtin_ctz:
12139   case Builtin::BI__builtin_ctzl:
12140   case Builtin::BI__builtin_ctzll:
12141   case Builtin::BI__builtin_ctzs: {
12142     APSInt Val;
12143     if (!EvaluateInteger(E->getArg(0), Val, Info))
12144       return false;
12145     if (!Val)
12146       return Error(E);
12147 
12148     return Success(Val.countr_zero(), E);
12149   }
12150 
12151   case Builtin::BI__builtin_eh_return_data_regno: {
12152     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12153     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12154     return Success(Operand, E);
12155   }
12156 
12157   case Builtin::BI__builtin_expect:
12158   case Builtin::BI__builtin_expect_with_probability:
12159     return Visit(E->getArg(0));
12160 
12161   case Builtin::BI__builtin_ffs:
12162   case Builtin::BI__builtin_ffsl:
12163   case Builtin::BI__builtin_ffsll: {
12164     APSInt Val;
12165     if (!EvaluateInteger(E->getArg(0), Val, Info))
12166       return false;
12167 
12168     unsigned N = Val.countr_zero();
12169     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12170   }
12171 
12172   case Builtin::BI__builtin_fpclassify: {
12173     APFloat Val(0.0);
12174     if (!EvaluateFloat(E->getArg(5), Val, Info))
12175       return false;
12176     unsigned Arg;
12177     switch (Val.getCategory()) {
12178     case APFloat::fcNaN: Arg = 0; break;
12179     case APFloat::fcInfinity: Arg = 1; break;
12180     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12181     case APFloat::fcZero: Arg = 4; break;
12182     }
12183     return Visit(E->getArg(Arg));
12184   }
12185 
12186   case Builtin::BI__builtin_isinf_sign: {
12187     APFloat Val(0.0);
12188     return EvaluateFloat(E->getArg(0), Val, Info) &&
12189            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12190   }
12191 
12192   case Builtin::BI__builtin_isinf: {
12193     APFloat Val(0.0);
12194     return EvaluateFloat(E->getArg(0), Val, Info) &&
12195            Success(Val.isInfinity() ? 1 : 0, E);
12196   }
12197 
12198   case Builtin::BI__builtin_isfinite: {
12199     APFloat Val(0.0);
12200     return EvaluateFloat(E->getArg(0), Val, Info) &&
12201            Success(Val.isFinite() ? 1 : 0, E);
12202   }
12203 
12204   case Builtin::BI__builtin_isnan: {
12205     APFloat Val(0.0);
12206     return EvaluateFloat(E->getArg(0), Val, Info) &&
12207            Success(Val.isNaN() ? 1 : 0, E);
12208   }
12209 
12210   case Builtin::BI__builtin_isnormal: {
12211     APFloat Val(0.0);
12212     return EvaluateFloat(E->getArg(0), Val, Info) &&
12213            Success(Val.isNormal() ? 1 : 0, E);
12214   }
12215 
12216   case Builtin::BI__builtin_isfpclass: {
12217     APSInt MaskVal;
12218     if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
12219       return false;
12220     unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
12221     APFloat Val(0.0);
12222     return EvaluateFloat(E->getArg(0), Val, Info) &&
12223            Success((Val.classify() & Test) ? 1 : 0, E);
12224   }
12225 
12226   case Builtin::BI__builtin_parity:
12227   case Builtin::BI__builtin_parityl:
12228   case Builtin::BI__builtin_parityll: {
12229     APSInt Val;
12230     if (!EvaluateInteger(E->getArg(0), Val, Info))
12231       return false;
12232 
12233     return Success(Val.popcount() % 2, E);
12234   }
12235 
12236   case Builtin::BI__builtin_popcount:
12237   case Builtin::BI__builtin_popcountl:
12238   case Builtin::BI__builtin_popcountll: {
12239     APSInt Val;
12240     if (!EvaluateInteger(E->getArg(0), Val, Info))
12241       return false;
12242 
12243     return Success(Val.popcount(), E);
12244   }
12245 
12246   case Builtin::BI__builtin_rotateleft8:
12247   case Builtin::BI__builtin_rotateleft16:
12248   case Builtin::BI__builtin_rotateleft32:
12249   case Builtin::BI__builtin_rotateleft64:
12250   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12251   case Builtin::BI_rotl16:
12252   case Builtin::BI_rotl:
12253   case Builtin::BI_lrotl:
12254   case Builtin::BI_rotl64: {
12255     APSInt Val, Amt;
12256     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12257         !EvaluateInteger(E->getArg(1), Amt, Info))
12258       return false;
12259 
12260     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12261   }
12262 
12263   case Builtin::BI__builtin_rotateright8:
12264   case Builtin::BI__builtin_rotateright16:
12265   case Builtin::BI__builtin_rotateright32:
12266   case Builtin::BI__builtin_rotateright64:
12267   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12268   case Builtin::BI_rotr16:
12269   case Builtin::BI_rotr:
12270   case Builtin::BI_lrotr:
12271   case Builtin::BI_rotr64: {
12272     APSInt Val, Amt;
12273     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12274         !EvaluateInteger(E->getArg(1), Amt, Info))
12275       return false;
12276 
12277     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12278   }
12279 
12280   case Builtin::BIstrlen:
12281   case Builtin::BIwcslen:
12282     // A call to strlen is not a constant expression.
12283     if (Info.getLangOpts().CPlusPlus11)
12284       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12285           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12286           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12287     else
12288       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12289     [[fallthrough]];
12290   case Builtin::BI__builtin_strlen:
12291   case Builtin::BI__builtin_wcslen: {
12292     // As an extension, we support __builtin_strlen() as a constant expression,
12293     // and support folding strlen() to a constant.
12294     uint64_t StrLen;
12295     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12296       return Success(StrLen, E);
12297     return false;
12298   }
12299 
12300   case Builtin::BIstrcmp:
12301   case Builtin::BIwcscmp:
12302   case Builtin::BIstrncmp:
12303   case Builtin::BIwcsncmp:
12304   case Builtin::BImemcmp:
12305   case Builtin::BIbcmp:
12306   case Builtin::BIwmemcmp:
12307     // A call to strlen is not a constant expression.
12308     if (Info.getLangOpts().CPlusPlus11)
12309       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12310           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12311           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12312     else
12313       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12314     [[fallthrough]];
12315   case Builtin::BI__builtin_strcmp:
12316   case Builtin::BI__builtin_wcscmp:
12317   case Builtin::BI__builtin_strncmp:
12318   case Builtin::BI__builtin_wcsncmp:
12319   case Builtin::BI__builtin_memcmp:
12320   case Builtin::BI__builtin_bcmp:
12321   case Builtin::BI__builtin_wmemcmp: {
12322     LValue String1, String2;
12323     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12324         !EvaluatePointer(E->getArg(1), String2, Info))
12325       return false;
12326 
12327     uint64_t MaxLength = uint64_t(-1);
12328     if (BuiltinOp != Builtin::BIstrcmp &&
12329         BuiltinOp != Builtin::BIwcscmp &&
12330         BuiltinOp != Builtin::BI__builtin_strcmp &&
12331         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12332       APSInt N;
12333       if (!EvaluateInteger(E->getArg(2), N, Info))
12334         return false;
12335       MaxLength = N.getExtValue();
12336     }
12337 
12338     // Empty substrings compare equal by definition.
12339     if (MaxLength == 0u)
12340       return Success(0, E);
12341 
12342     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12343         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12344         String1.Designator.Invalid || String2.Designator.Invalid)
12345       return false;
12346 
12347     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12348     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12349 
12350     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12351                      BuiltinOp == Builtin::BIbcmp ||
12352                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12353                      BuiltinOp == Builtin::BI__builtin_bcmp;
12354 
12355     assert(IsRawByte ||
12356            (Info.Ctx.hasSameUnqualifiedType(
12357                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12358             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12359 
12360     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12361     // 'char8_t', but no other types.
12362     if (IsRawByte &&
12363         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12364       // FIXME: Consider using our bit_cast implementation to support this.
12365       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12366           << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12367           << CharTy1 << CharTy2;
12368       return false;
12369     }
12370 
12371     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12372       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12373              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12374              Char1.isInt() && Char2.isInt();
12375     };
12376     const auto &AdvanceElems = [&] {
12377       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12378              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12379     };
12380 
12381     bool StopAtNull =
12382         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12383          BuiltinOp != Builtin::BIwmemcmp &&
12384          BuiltinOp != Builtin::BI__builtin_memcmp &&
12385          BuiltinOp != Builtin::BI__builtin_bcmp &&
12386          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12387     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12388                   BuiltinOp == Builtin::BIwcsncmp ||
12389                   BuiltinOp == Builtin::BIwmemcmp ||
12390                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12391                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12392                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12393 
12394     for (; MaxLength; --MaxLength) {
12395       APValue Char1, Char2;
12396       if (!ReadCurElems(Char1, Char2))
12397         return false;
12398       if (Char1.getInt().ne(Char2.getInt())) {
12399         if (IsWide) // wmemcmp compares with wchar_t signedness.
12400           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12401         // memcmp always compares unsigned chars.
12402         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12403       }
12404       if (StopAtNull && !Char1.getInt())
12405         return Success(0, E);
12406       assert(!(StopAtNull && !Char2.getInt()));
12407       if (!AdvanceElems())
12408         return false;
12409     }
12410     // We hit the strncmp / memcmp limit.
12411     return Success(0, E);
12412   }
12413 
12414   case Builtin::BI__atomic_always_lock_free:
12415   case Builtin::BI__atomic_is_lock_free:
12416   case Builtin::BI__c11_atomic_is_lock_free: {
12417     APSInt SizeVal;
12418     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12419       return false;
12420 
12421     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12422     // of two less than or equal to the maximum inline atomic width, we know it
12423     // is lock-free.  If the size isn't a power of two, or greater than the
12424     // maximum alignment where we promote atomics, we know it is not lock-free
12425     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12426     // the answer can only be determined at runtime; for example, 16-byte
12427     // atomics have lock-free implementations on some, but not all,
12428     // x86-64 processors.
12429 
12430     // Check power-of-two.
12431     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12432     if (Size.isPowerOfTwo()) {
12433       // Check against inlining width.
12434       unsigned InlineWidthBits =
12435           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12436       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12437         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12438             Size == CharUnits::One() ||
12439             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12440                                                 Expr::NPC_NeverValueDependent))
12441           // OK, we will inline appropriately-aligned operations of this size,
12442           // and _Atomic(T) is appropriately-aligned.
12443           return Success(1, E);
12444 
12445         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12446           castAs<PointerType>()->getPointeeType();
12447         if (!PointeeType->isIncompleteType() &&
12448             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12449           // OK, we will inline operations on this object.
12450           return Success(1, E);
12451         }
12452       }
12453     }
12454 
12455     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12456         Success(0, E) : Error(E);
12457   }
12458   case Builtin::BI__builtin_add_overflow:
12459   case Builtin::BI__builtin_sub_overflow:
12460   case Builtin::BI__builtin_mul_overflow:
12461   case Builtin::BI__builtin_sadd_overflow:
12462   case Builtin::BI__builtin_uadd_overflow:
12463   case Builtin::BI__builtin_uaddl_overflow:
12464   case Builtin::BI__builtin_uaddll_overflow:
12465   case Builtin::BI__builtin_usub_overflow:
12466   case Builtin::BI__builtin_usubl_overflow:
12467   case Builtin::BI__builtin_usubll_overflow:
12468   case Builtin::BI__builtin_umul_overflow:
12469   case Builtin::BI__builtin_umull_overflow:
12470   case Builtin::BI__builtin_umulll_overflow:
12471   case Builtin::BI__builtin_saddl_overflow:
12472   case Builtin::BI__builtin_saddll_overflow:
12473   case Builtin::BI__builtin_ssub_overflow:
12474   case Builtin::BI__builtin_ssubl_overflow:
12475   case Builtin::BI__builtin_ssubll_overflow:
12476   case Builtin::BI__builtin_smul_overflow:
12477   case Builtin::BI__builtin_smull_overflow:
12478   case Builtin::BI__builtin_smulll_overflow: {
12479     LValue ResultLValue;
12480     APSInt LHS, RHS;
12481 
12482     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12483     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12484         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12485         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12486       return false;
12487 
12488     APSInt Result;
12489     bool DidOverflow = false;
12490 
12491     // If the types don't have to match, enlarge all 3 to the largest of them.
12492     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12493         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12494         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12495       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12496                       ResultType->isSignedIntegerOrEnumerationType();
12497       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12498                       ResultType->isSignedIntegerOrEnumerationType();
12499       uint64_t LHSSize = LHS.getBitWidth();
12500       uint64_t RHSSize = RHS.getBitWidth();
12501       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12502       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12503 
12504       // Add an additional bit if the signedness isn't uniformly agreed to. We
12505       // could do this ONLY if there is a signed and an unsigned that both have
12506       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12507       // caught in the shrink-to-result later anyway.
12508       if (IsSigned && !AllSigned)
12509         ++MaxBits;
12510 
12511       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12512       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12513       Result = APSInt(MaxBits, !IsSigned);
12514     }
12515 
12516     // Find largest int.
12517     switch (BuiltinOp) {
12518     default:
12519       llvm_unreachable("Invalid value for BuiltinOp");
12520     case Builtin::BI__builtin_add_overflow:
12521     case Builtin::BI__builtin_sadd_overflow:
12522     case Builtin::BI__builtin_saddl_overflow:
12523     case Builtin::BI__builtin_saddll_overflow:
12524     case Builtin::BI__builtin_uadd_overflow:
12525     case Builtin::BI__builtin_uaddl_overflow:
12526     case Builtin::BI__builtin_uaddll_overflow:
12527       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12528                               : LHS.uadd_ov(RHS, DidOverflow);
12529       break;
12530     case Builtin::BI__builtin_sub_overflow:
12531     case Builtin::BI__builtin_ssub_overflow:
12532     case Builtin::BI__builtin_ssubl_overflow:
12533     case Builtin::BI__builtin_ssubll_overflow:
12534     case Builtin::BI__builtin_usub_overflow:
12535     case Builtin::BI__builtin_usubl_overflow:
12536     case Builtin::BI__builtin_usubll_overflow:
12537       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12538                               : LHS.usub_ov(RHS, DidOverflow);
12539       break;
12540     case Builtin::BI__builtin_mul_overflow:
12541     case Builtin::BI__builtin_smul_overflow:
12542     case Builtin::BI__builtin_smull_overflow:
12543     case Builtin::BI__builtin_smulll_overflow:
12544     case Builtin::BI__builtin_umul_overflow:
12545     case Builtin::BI__builtin_umull_overflow:
12546     case Builtin::BI__builtin_umulll_overflow:
12547       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12548                               : LHS.umul_ov(RHS, DidOverflow);
12549       break;
12550     }
12551 
12552     // In the case where multiple sizes are allowed, truncate and see if
12553     // the values are the same.
12554     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12555         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12556         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12557       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12558       // since it will give us the behavior of a TruncOrSelf in the case where
12559       // its parameter <= its size.  We previously set Result to be at least the
12560       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12561       // will work exactly like TruncOrSelf.
12562       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12563       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12564 
12565       if (!APSInt::isSameValue(Temp, Result))
12566         DidOverflow = true;
12567       Result = Temp;
12568     }
12569 
12570     APValue APV{Result};
12571     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12572       return false;
12573     return Success(DidOverflow, E);
12574   }
12575   }
12576 }
12577 
12578 /// Determine whether this is a pointer past the end of the complete
12579 /// object referred to by the lvalue.
12580 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12581                                             const LValue &LV) {
12582   // A null pointer can be viewed as being "past the end" but we don't
12583   // choose to look at it that way here.
12584   if (!LV.getLValueBase())
12585     return false;
12586 
12587   // If the designator is valid and refers to a subobject, we're not pointing
12588   // past the end.
12589   if (!LV.getLValueDesignator().Invalid &&
12590       !LV.getLValueDesignator().isOnePastTheEnd())
12591     return false;
12592 
12593   // A pointer to an incomplete type might be past-the-end if the type's size is
12594   // zero.  We cannot tell because the type is incomplete.
12595   QualType Ty = getType(LV.getLValueBase());
12596   if (Ty->isIncompleteType())
12597     return true;
12598 
12599   // We're a past-the-end pointer if we point to the byte after the object,
12600   // no matter what our type or path is.
12601   auto Size = Ctx.getTypeSizeInChars(Ty);
12602   return LV.getLValueOffset() == Size;
12603 }
12604 
12605 namespace {
12606 
12607 /// Data recursive integer evaluator of certain binary operators.
12608 ///
12609 /// We use a data recursive algorithm for binary operators so that we are able
12610 /// to handle extreme cases of chained binary operators without causing stack
12611 /// overflow.
12612 class DataRecursiveIntBinOpEvaluator {
12613   struct EvalResult {
12614     APValue Val;
12615     bool Failed;
12616 
12617     EvalResult() : Failed(false) { }
12618 
12619     void swap(EvalResult &RHS) {
12620       Val.swap(RHS.Val);
12621       Failed = RHS.Failed;
12622       RHS.Failed = false;
12623     }
12624   };
12625 
12626   struct Job {
12627     const Expr *E;
12628     EvalResult LHSResult; // meaningful only for binary operator expression.
12629     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12630 
12631     Job() = default;
12632     Job(Job &&) = default;
12633 
12634     void startSpeculativeEval(EvalInfo &Info) {
12635       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12636     }
12637 
12638   private:
12639     SpeculativeEvaluationRAII SpecEvalRAII;
12640   };
12641 
12642   SmallVector<Job, 16> Queue;
12643 
12644   IntExprEvaluator &IntEval;
12645   EvalInfo &Info;
12646   APValue &FinalResult;
12647 
12648 public:
12649   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12650     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12651 
12652   /// True if \param E is a binary operator that we are going to handle
12653   /// data recursively.
12654   /// We handle binary operators that are comma, logical, or that have operands
12655   /// with integral or enumeration type.
12656   static bool shouldEnqueue(const BinaryOperator *E) {
12657     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12658            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12659             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12660             E->getRHS()->getType()->isIntegralOrEnumerationType());
12661   }
12662 
12663   bool Traverse(const BinaryOperator *E) {
12664     enqueue(E);
12665     EvalResult PrevResult;
12666     while (!Queue.empty())
12667       process(PrevResult);
12668 
12669     if (PrevResult.Failed) return false;
12670 
12671     FinalResult.swap(PrevResult.Val);
12672     return true;
12673   }
12674 
12675 private:
12676   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12677     return IntEval.Success(Value, E, Result);
12678   }
12679   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12680     return IntEval.Success(Value, E, Result);
12681   }
12682   bool Error(const Expr *E) {
12683     return IntEval.Error(E);
12684   }
12685   bool Error(const Expr *E, diag::kind D) {
12686     return IntEval.Error(E, D);
12687   }
12688 
12689   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12690     return Info.CCEDiag(E, D);
12691   }
12692 
12693   // Returns true if visiting the RHS is necessary, false otherwise.
12694   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12695                          bool &SuppressRHSDiags);
12696 
12697   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12698                   const BinaryOperator *E, APValue &Result);
12699 
12700   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12701     Result.Failed = !Evaluate(Result.Val, Info, E);
12702     if (Result.Failed)
12703       Result.Val = APValue();
12704   }
12705 
12706   void process(EvalResult &Result);
12707 
12708   void enqueue(const Expr *E) {
12709     E = E->IgnoreParens();
12710     Queue.resize(Queue.size()+1);
12711     Queue.back().E = E;
12712     Queue.back().Kind = Job::AnyExprKind;
12713   }
12714 };
12715 
12716 }
12717 
12718 bool DataRecursiveIntBinOpEvaluator::
12719        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12720                          bool &SuppressRHSDiags) {
12721   if (E->getOpcode() == BO_Comma) {
12722     // Ignore LHS but note if we could not evaluate it.
12723     if (LHSResult.Failed)
12724       return Info.noteSideEffect();
12725     return true;
12726   }
12727 
12728   if (E->isLogicalOp()) {
12729     bool LHSAsBool;
12730     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12731       // We were able to evaluate the LHS, see if we can get away with not
12732       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12733       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12734         Success(LHSAsBool, E, LHSResult.Val);
12735         return false; // Ignore RHS
12736       }
12737     } else {
12738       LHSResult.Failed = true;
12739 
12740       // Since we weren't able to evaluate the left hand side, it
12741       // might have had side effects.
12742       if (!Info.noteSideEffect())
12743         return false;
12744 
12745       // We can't evaluate the LHS; however, sometimes the result
12746       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12747       // Don't ignore RHS and suppress diagnostics from this arm.
12748       SuppressRHSDiags = true;
12749     }
12750 
12751     return true;
12752   }
12753 
12754   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12755          E->getRHS()->getType()->isIntegralOrEnumerationType());
12756 
12757   if (LHSResult.Failed && !Info.noteFailure())
12758     return false; // Ignore RHS;
12759 
12760   return true;
12761 }
12762 
12763 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12764                                     bool IsSub) {
12765   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12766   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12767   // offsets.
12768   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12769   CharUnits &Offset = LVal.getLValueOffset();
12770   uint64_t Offset64 = Offset.getQuantity();
12771   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12772   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12773                                          : Offset64 + Index64);
12774 }
12775 
12776 bool DataRecursiveIntBinOpEvaluator::
12777        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12778                   const BinaryOperator *E, APValue &Result) {
12779   if (E->getOpcode() == BO_Comma) {
12780     if (RHSResult.Failed)
12781       return false;
12782     Result = RHSResult.Val;
12783     return true;
12784   }
12785 
12786   if (E->isLogicalOp()) {
12787     bool lhsResult, rhsResult;
12788     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12789     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12790 
12791     if (LHSIsOK) {
12792       if (RHSIsOK) {
12793         if (E->getOpcode() == BO_LOr)
12794           return Success(lhsResult || rhsResult, E, Result);
12795         else
12796           return Success(lhsResult && rhsResult, E, Result);
12797       }
12798     } else {
12799       if (RHSIsOK) {
12800         // We can't evaluate the LHS; however, sometimes the result
12801         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12802         if (rhsResult == (E->getOpcode() == BO_LOr))
12803           return Success(rhsResult, E, Result);
12804       }
12805     }
12806 
12807     return false;
12808   }
12809 
12810   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12811          E->getRHS()->getType()->isIntegralOrEnumerationType());
12812 
12813   if (LHSResult.Failed || RHSResult.Failed)
12814     return false;
12815 
12816   const APValue &LHSVal = LHSResult.Val;
12817   const APValue &RHSVal = RHSResult.Val;
12818 
12819   // Handle cases like (unsigned long)&a + 4.
12820   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12821     Result = LHSVal;
12822     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12823     return true;
12824   }
12825 
12826   // Handle cases like 4 + (unsigned long)&a
12827   if (E->getOpcode() == BO_Add &&
12828       RHSVal.isLValue() && LHSVal.isInt()) {
12829     Result = RHSVal;
12830     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12831     return true;
12832   }
12833 
12834   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12835     // Handle (intptr_t)&&A - (intptr_t)&&B.
12836     if (!LHSVal.getLValueOffset().isZero() ||
12837         !RHSVal.getLValueOffset().isZero())
12838       return false;
12839     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12840     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12841     if (!LHSExpr || !RHSExpr)
12842       return false;
12843     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12844     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12845     if (!LHSAddrExpr || !RHSAddrExpr)
12846       return false;
12847     // Make sure both labels come from the same function.
12848     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12849         RHSAddrExpr->getLabel()->getDeclContext())
12850       return false;
12851     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12852     return true;
12853   }
12854 
12855   // All the remaining cases expect both operands to be an integer
12856   if (!LHSVal.isInt() || !RHSVal.isInt())
12857     return Error(E);
12858 
12859   // Set up the width and signedness manually, in case it can't be deduced
12860   // from the operation we're performing.
12861   // FIXME: Don't do this in the cases where we can deduce it.
12862   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12863                E->getType()->isUnsignedIntegerOrEnumerationType());
12864   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12865                          RHSVal.getInt(), Value))
12866     return false;
12867   return Success(Value, E, Result);
12868 }
12869 
12870 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12871   Job &job = Queue.back();
12872 
12873   switch (job.Kind) {
12874     case Job::AnyExprKind: {
12875       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12876         if (shouldEnqueue(Bop)) {
12877           job.Kind = Job::BinOpKind;
12878           enqueue(Bop->getLHS());
12879           return;
12880         }
12881       }
12882 
12883       EvaluateExpr(job.E, Result);
12884       Queue.pop_back();
12885       return;
12886     }
12887 
12888     case Job::BinOpKind: {
12889       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12890       bool SuppressRHSDiags = false;
12891       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12892         Queue.pop_back();
12893         return;
12894       }
12895       if (SuppressRHSDiags)
12896         job.startSpeculativeEval(Info);
12897       job.LHSResult.swap(Result);
12898       job.Kind = Job::BinOpVisitedLHSKind;
12899       enqueue(Bop->getRHS());
12900       return;
12901     }
12902 
12903     case Job::BinOpVisitedLHSKind: {
12904       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12905       EvalResult RHS;
12906       RHS.swap(Result);
12907       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12908       Queue.pop_back();
12909       return;
12910     }
12911   }
12912 
12913   llvm_unreachable("Invalid Job::Kind!");
12914 }
12915 
12916 namespace {
12917 enum class CmpResult {
12918   Unequal,
12919   Less,
12920   Equal,
12921   Greater,
12922   Unordered,
12923 };
12924 }
12925 
12926 template <class SuccessCB, class AfterCB>
12927 static bool
12928 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12929                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12930   assert(!E->isValueDependent());
12931   assert(E->isComparisonOp() && "expected comparison operator");
12932   assert((E->getOpcode() == BO_Cmp ||
12933           E->getType()->isIntegralOrEnumerationType()) &&
12934          "unsupported binary expression evaluation");
12935   auto Error = [&](const Expr *E) {
12936     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12937     return false;
12938   };
12939 
12940   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12941   bool IsEquality = E->isEqualityOp();
12942 
12943   QualType LHSTy = E->getLHS()->getType();
12944   QualType RHSTy = E->getRHS()->getType();
12945 
12946   if (LHSTy->isIntegralOrEnumerationType() &&
12947       RHSTy->isIntegralOrEnumerationType()) {
12948     APSInt LHS, RHS;
12949     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12950     if (!LHSOK && !Info.noteFailure())
12951       return false;
12952     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12953       return false;
12954     if (LHS < RHS)
12955       return Success(CmpResult::Less, E);
12956     if (LHS > RHS)
12957       return Success(CmpResult::Greater, E);
12958     return Success(CmpResult::Equal, E);
12959   }
12960 
12961   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12962     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12963     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12964 
12965     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12966     if (!LHSOK && !Info.noteFailure())
12967       return false;
12968     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12969       return false;
12970     if (LHSFX < RHSFX)
12971       return Success(CmpResult::Less, E);
12972     if (LHSFX > RHSFX)
12973       return Success(CmpResult::Greater, E);
12974     return Success(CmpResult::Equal, E);
12975   }
12976 
12977   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12978     ComplexValue LHS, RHS;
12979     bool LHSOK;
12980     if (E->isAssignmentOp()) {
12981       LValue LV;
12982       EvaluateLValue(E->getLHS(), LV, Info);
12983       LHSOK = false;
12984     } else if (LHSTy->isRealFloatingType()) {
12985       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12986       if (LHSOK) {
12987         LHS.makeComplexFloat();
12988         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12989       }
12990     } else {
12991       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12992     }
12993     if (!LHSOK && !Info.noteFailure())
12994       return false;
12995 
12996     if (E->getRHS()->getType()->isRealFloatingType()) {
12997       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12998         return false;
12999       RHS.makeComplexFloat();
13000       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13001     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13002       return false;
13003 
13004     if (LHS.isComplexFloat()) {
13005       APFloat::cmpResult CR_r =
13006         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13007       APFloat::cmpResult CR_i =
13008         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13009       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
13010       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13011     } else {
13012       assert(IsEquality && "invalid complex comparison");
13013       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13014                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
13015       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13016     }
13017   }
13018 
13019   if (LHSTy->isRealFloatingType() &&
13020       RHSTy->isRealFloatingType()) {
13021     APFloat RHS(0.0), LHS(0.0);
13022 
13023     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13024     if (!LHSOK && !Info.noteFailure())
13025       return false;
13026 
13027     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
13028       return false;
13029 
13030     assert(E->isComparisonOp() && "Invalid binary operator!");
13031     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13032     if (!Info.InConstantContext &&
13033         APFloatCmpResult == APFloat::cmpUnordered &&
13034         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
13035       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13036       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13037       return false;
13038     }
13039     auto GetCmpRes = [&]() {
13040       switch (APFloatCmpResult) {
13041       case APFloat::cmpEqual:
13042         return CmpResult::Equal;
13043       case APFloat::cmpLessThan:
13044         return CmpResult::Less;
13045       case APFloat::cmpGreaterThan:
13046         return CmpResult::Greater;
13047       case APFloat::cmpUnordered:
13048         return CmpResult::Unordered;
13049       }
13050       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13051     };
13052     return Success(GetCmpRes(), E);
13053   }
13054 
13055   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13056     LValue LHSValue, RHSValue;
13057 
13058     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13059     if (!LHSOK && !Info.noteFailure())
13060       return false;
13061 
13062     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13063       return false;
13064 
13065     // Reject differing bases from the normal codepath; we special-case
13066     // comparisons to null.
13067     if (!HasSameBase(LHSValue, RHSValue)) {
13068       auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13069         std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13070         std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13071         Info.FFDiag(E, DiagID)
13072             << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13073         return false;
13074       };
13075       // Inequalities and subtractions between unrelated pointers have
13076       // unspecified or undefined behavior.
13077       if (!IsEquality)
13078         return DiagComparison(
13079             diag::note_constexpr_pointer_comparison_unspecified);
13080       // A constant address may compare equal to the address of a symbol.
13081       // The one exception is that address of an object cannot compare equal
13082       // to a null pointer constant.
13083       // TODO: Should we restrict this to actual null pointers, and exclude the
13084       // case of zero cast to pointer type?
13085       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13086           (!RHSValue.Base && !RHSValue.Offset.isZero()))
13087         return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13088                               !RHSValue.Base);
13089       // It's implementation-defined whether distinct literals will have
13090       // distinct addresses. In clang, the result of such a comparison is
13091       // unspecified, so it is not a constant expression. However, we do know
13092       // that the address of a literal will be non-null.
13093       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13094           LHSValue.Base && RHSValue.Base)
13095         return DiagComparison(diag::note_constexpr_literal_comparison);
13096       // We can't tell whether weak symbols will end up pointing to the same
13097       // object.
13098       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13099         return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13100                               !IsWeakLValue(LHSValue));
13101       // We can't compare the address of the start of one object with the
13102       // past-the-end address of another object, per C++ DR1652.
13103       if (LHSValue.Base && LHSValue.Offset.isZero() &&
13104           isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13105         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13106                               true);
13107       if (RHSValue.Base && RHSValue.Offset.isZero() &&
13108            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13109         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13110                               false);
13111       // We can't tell whether an object is at the same address as another
13112       // zero sized object.
13113       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13114           (LHSValue.Base && isZeroSized(RHSValue)))
13115         return DiagComparison(
13116             diag::note_constexpr_pointer_comparison_zero_sized);
13117       return Success(CmpResult::Unequal, E);
13118     }
13119 
13120     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13121     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13122 
13123     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13124     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13125 
13126     // C++11 [expr.rel]p3:
13127     //   Pointers to void (after pointer conversions) can be compared, with a
13128     //   result defined as follows: If both pointers represent the same
13129     //   address or are both the null pointer value, the result is true if the
13130     //   operator is <= or >= and false otherwise; otherwise the result is
13131     //   unspecified.
13132     // We interpret this as applying to pointers to *cv* void.
13133     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13134       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13135 
13136     // C++11 [expr.rel]p2:
13137     // - If two pointers point to non-static data members of the same object,
13138     //   or to subobjects or array elements fo such members, recursively, the
13139     //   pointer to the later declared member compares greater provided the
13140     //   two members have the same access control and provided their class is
13141     //   not a union.
13142     //   [...]
13143     // - Otherwise pointer comparisons are unspecified.
13144     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13145       bool WasArrayIndex;
13146       unsigned Mismatch = FindDesignatorMismatch(
13147           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13148       // At the point where the designators diverge, the comparison has a
13149       // specified value if:
13150       //  - we are comparing array indices
13151       //  - we are comparing fields of a union, or fields with the same access
13152       // Otherwise, the result is unspecified and thus the comparison is not a
13153       // constant expression.
13154       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13155           Mismatch < RHSDesignator.Entries.size()) {
13156         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13157         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13158         if (!LF && !RF)
13159           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13160         else if (!LF)
13161           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13162               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13163               << RF->getParent() << RF;
13164         else if (!RF)
13165           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13166               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13167               << LF->getParent() << LF;
13168         else if (!LF->getParent()->isUnion() &&
13169                  LF->getAccess() != RF->getAccess())
13170           Info.CCEDiag(E,
13171                        diag::note_constexpr_pointer_comparison_differing_access)
13172               << LF << LF->getAccess() << RF << RF->getAccess()
13173               << LF->getParent();
13174       }
13175     }
13176 
13177     // The comparison here must be unsigned, and performed with the same
13178     // width as the pointer.
13179     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13180     uint64_t CompareLHS = LHSOffset.getQuantity();
13181     uint64_t CompareRHS = RHSOffset.getQuantity();
13182     assert(PtrSize <= 64 && "Unexpected pointer width");
13183     uint64_t Mask = ~0ULL >> (64 - PtrSize);
13184     CompareLHS &= Mask;
13185     CompareRHS &= Mask;
13186 
13187     // If there is a base and this is a relational operator, we can only
13188     // compare pointers within the object in question; otherwise, the result
13189     // depends on where the object is located in memory.
13190     if (!LHSValue.Base.isNull() && IsRelational) {
13191       QualType BaseTy = getType(LHSValue.Base);
13192       if (BaseTy->isIncompleteType())
13193         return Error(E);
13194       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13195       uint64_t OffsetLimit = Size.getQuantity();
13196       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13197         return Error(E);
13198     }
13199 
13200     if (CompareLHS < CompareRHS)
13201       return Success(CmpResult::Less, E);
13202     if (CompareLHS > CompareRHS)
13203       return Success(CmpResult::Greater, E);
13204     return Success(CmpResult::Equal, E);
13205   }
13206 
13207   if (LHSTy->isMemberPointerType()) {
13208     assert(IsEquality && "unexpected member pointer operation");
13209     assert(RHSTy->isMemberPointerType() && "invalid comparison");
13210 
13211     MemberPtr LHSValue, RHSValue;
13212 
13213     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13214     if (!LHSOK && !Info.noteFailure())
13215       return false;
13216 
13217     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13218       return false;
13219 
13220     // If either operand is a pointer to a weak function, the comparison is not
13221     // constant.
13222     if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13223       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13224           << LHSValue.getDecl();
13225       return false;
13226     }
13227     if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13228       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13229           << RHSValue.getDecl();
13230       return false;
13231     }
13232 
13233     // C++11 [expr.eq]p2:
13234     //   If both operands are null, they compare equal. Otherwise if only one is
13235     //   null, they compare unequal.
13236     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13237       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13238       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13239     }
13240 
13241     //   Otherwise if either is a pointer to a virtual member function, the
13242     //   result is unspecified.
13243     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13244       if (MD->isVirtual())
13245         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13246     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13247       if (MD->isVirtual())
13248         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13249 
13250     //   Otherwise they compare equal if and only if they would refer to the
13251     //   same member of the same most derived object or the same subobject if
13252     //   they were dereferenced with a hypothetical object of the associated
13253     //   class type.
13254     bool Equal = LHSValue == RHSValue;
13255     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13256   }
13257 
13258   if (LHSTy->isNullPtrType()) {
13259     assert(E->isComparisonOp() && "unexpected nullptr operation");
13260     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13261     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13262     // are compared, the result is true of the operator is <=, >= or ==, and
13263     // false otherwise.
13264     return Success(CmpResult::Equal, E);
13265   }
13266 
13267   return DoAfter();
13268 }
13269 
13270 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13271   if (!CheckLiteralType(Info, E))
13272     return false;
13273 
13274   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13275     ComparisonCategoryResult CCR;
13276     switch (CR) {
13277     case CmpResult::Unequal:
13278       llvm_unreachable("should never produce Unequal for three-way comparison");
13279     case CmpResult::Less:
13280       CCR = ComparisonCategoryResult::Less;
13281       break;
13282     case CmpResult::Equal:
13283       CCR = ComparisonCategoryResult::Equal;
13284       break;
13285     case CmpResult::Greater:
13286       CCR = ComparisonCategoryResult::Greater;
13287       break;
13288     case CmpResult::Unordered:
13289       CCR = ComparisonCategoryResult::Unordered;
13290       break;
13291     }
13292     // Evaluation succeeded. Lookup the information for the comparison category
13293     // type and fetch the VarDecl for the result.
13294     const ComparisonCategoryInfo &CmpInfo =
13295         Info.Ctx.CompCategories.getInfoForType(E->getType());
13296     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13297     // Check and evaluate the result as a constant expression.
13298     LValue LV;
13299     LV.set(VD);
13300     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13301       return false;
13302     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13303                                    ConstantExprKind::Normal);
13304   };
13305   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13306     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13307   });
13308 }
13309 
13310 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13311     const CXXParenListInitExpr *E) {
13312   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13313 }
13314 
13315 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13316   // We don't support assignment in C. C++ assignments don't get here because
13317   // assignment is an lvalue in C++.
13318   if (E->isAssignmentOp()) {
13319     Error(E);
13320     if (!Info.noteFailure())
13321       return false;
13322   }
13323 
13324   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13325     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13326 
13327   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13328           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13329          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13330 
13331   if (E->isComparisonOp()) {
13332     // Evaluate builtin binary comparisons by evaluating them as three-way
13333     // comparisons and then translating the result.
13334     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13335       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13336              "should only produce Unequal for equality comparisons");
13337       bool IsEqual   = CR == CmpResult::Equal,
13338            IsLess    = CR == CmpResult::Less,
13339            IsGreater = CR == CmpResult::Greater;
13340       auto Op = E->getOpcode();
13341       switch (Op) {
13342       default:
13343         llvm_unreachable("unsupported binary operator");
13344       case BO_EQ:
13345       case BO_NE:
13346         return Success(IsEqual == (Op == BO_EQ), E);
13347       case BO_LT:
13348         return Success(IsLess, E);
13349       case BO_GT:
13350         return Success(IsGreater, E);
13351       case BO_LE:
13352         return Success(IsEqual || IsLess, E);
13353       case BO_GE:
13354         return Success(IsEqual || IsGreater, E);
13355       }
13356     };
13357     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13358       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13359     });
13360   }
13361 
13362   QualType LHSTy = E->getLHS()->getType();
13363   QualType RHSTy = E->getRHS()->getType();
13364 
13365   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13366       E->getOpcode() == BO_Sub) {
13367     LValue LHSValue, RHSValue;
13368 
13369     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13370     if (!LHSOK && !Info.noteFailure())
13371       return false;
13372 
13373     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13374       return false;
13375 
13376     // Reject differing bases from the normal codepath; we special-case
13377     // comparisons to null.
13378     if (!HasSameBase(LHSValue, RHSValue)) {
13379       // Handle &&A - &&B.
13380       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13381         return Error(E);
13382       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13383       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13384       if (!LHSExpr || !RHSExpr)
13385         return Error(E);
13386       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13387       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13388       if (!LHSAddrExpr || !RHSAddrExpr)
13389         return Error(E);
13390       // Make sure both labels come from the same function.
13391       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13392           RHSAddrExpr->getLabel()->getDeclContext())
13393         return Error(E);
13394       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13395     }
13396     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13397     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13398 
13399     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13400     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13401 
13402     // C++11 [expr.add]p6:
13403     //   Unless both pointers point to elements of the same array object, or
13404     //   one past the last element of the array object, the behavior is
13405     //   undefined.
13406     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13407         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13408                                 RHSDesignator))
13409       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13410 
13411     QualType Type = E->getLHS()->getType();
13412     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13413 
13414     CharUnits ElementSize;
13415     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13416       return false;
13417 
13418     // As an extension, a type may have zero size (empty struct or union in
13419     // C, array of zero length). Pointer subtraction in such cases has
13420     // undefined behavior, so is not constant.
13421     if (ElementSize.isZero()) {
13422       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13423           << ElementType;
13424       return false;
13425     }
13426 
13427     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13428     // and produce incorrect results when it overflows. Such behavior
13429     // appears to be non-conforming, but is common, so perhaps we should
13430     // assume the standard intended for such cases to be undefined behavior
13431     // and check for them.
13432 
13433     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13434     // overflow in the final conversion to ptrdiff_t.
13435     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13436     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13437     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13438                     false);
13439     APSInt TrueResult = (LHS - RHS) / ElemSize;
13440     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13441 
13442     if (Result.extend(65) != TrueResult &&
13443         !HandleOverflow(Info, E, TrueResult, E->getType()))
13444       return false;
13445     return Success(Result, E);
13446   }
13447 
13448   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13449 }
13450 
13451 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13452 /// a result as the expression's type.
13453 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13454                                     const UnaryExprOrTypeTraitExpr *E) {
13455   switch(E->getKind()) {
13456   case UETT_PreferredAlignOf:
13457   case UETT_AlignOf: {
13458     if (E->isArgumentType())
13459       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13460                      E);
13461     else
13462       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13463                      E);
13464   }
13465 
13466   case UETT_VecStep: {
13467     QualType Ty = E->getTypeOfArgument();
13468 
13469     if (Ty->isVectorType()) {
13470       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13471 
13472       // The vec_step built-in functions that take a 3-component
13473       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13474       if (n == 3)
13475         n = 4;
13476 
13477       return Success(n, E);
13478     } else
13479       return Success(1, E);
13480   }
13481 
13482   case UETT_SizeOf: {
13483     QualType SrcTy = E->getTypeOfArgument();
13484     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13485     //   the result is the size of the referenced type."
13486     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13487       SrcTy = Ref->getPointeeType();
13488 
13489     CharUnits Sizeof;
13490     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13491       return false;
13492     return Success(Sizeof, E);
13493   }
13494   case UETT_OpenMPRequiredSimdAlign:
13495     assert(E->isArgumentType());
13496     return Success(
13497         Info.Ctx.toCharUnitsFromBits(
13498                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13499             .getQuantity(),
13500         E);
13501   }
13502 
13503   llvm_unreachable("unknown expr/type trait");
13504 }
13505 
13506 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13507   CharUnits Result;
13508   unsigned n = OOE->getNumComponents();
13509   if (n == 0)
13510     return Error(OOE);
13511   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13512   for (unsigned i = 0; i != n; ++i) {
13513     OffsetOfNode ON = OOE->getComponent(i);
13514     switch (ON.getKind()) {
13515     case OffsetOfNode::Array: {
13516       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13517       APSInt IdxResult;
13518       if (!EvaluateInteger(Idx, IdxResult, Info))
13519         return false;
13520       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13521       if (!AT)
13522         return Error(OOE);
13523       CurrentType = AT->getElementType();
13524       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13525       Result += IdxResult.getSExtValue() * ElementSize;
13526       break;
13527     }
13528 
13529     case OffsetOfNode::Field: {
13530       FieldDecl *MemberDecl = ON.getField();
13531       const RecordType *RT = CurrentType->getAs<RecordType>();
13532       if (!RT)
13533         return Error(OOE);
13534       RecordDecl *RD = RT->getDecl();
13535       if (RD->isInvalidDecl()) return false;
13536       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13537       unsigned i = MemberDecl->getFieldIndex();
13538       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13539       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13540       CurrentType = MemberDecl->getType().getNonReferenceType();
13541       break;
13542     }
13543 
13544     case OffsetOfNode::Identifier:
13545       llvm_unreachable("dependent __builtin_offsetof");
13546 
13547     case OffsetOfNode::Base: {
13548       CXXBaseSpecifier *BaseSpec = ON.getBase();
13549       if (BaseSpec->isVirtual())
13550         return Error(OOE);
13551 
13552       // Find the layout of the class whose base we are looking into.
13553       const RecordType *RT = CurrentType->getAs<RecordType>();
13554       if (!RT)
13555         return Error(OOE);
13556       RecordDecl *RD = RT->getDecl();
13557       if (RD->isInvalidDecl()) return false;
13558       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13559 
13560       // Find the base class itself.
13561       CurrentType = BaseSpec->getType();
13562       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13563       if (!BaseRT)
13564         return Error(OOE);
13565 
13566       // Add the offset to the base.
13567       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13568       break;
13569     }
13570     }
13571   }
13572   return Success(Result, OOE);
13573 }
13574 
13575 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13576   switch (E->getOpcode()) {
13577   default:
13578     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13579     // See C99 6.6p3.
13580     return Error(E);
13581   case UO_Extension:
13582     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13583     // If so, we could clear the diagnostic ID.
13584     return Visit(E->getSubExpr());
13585   case UO_Plus:
13586     // The result is just the value.
13587     return Visit(E->getSubExpr());
13588   case UO_Minus: {
13589     if (!Visit(E->getSubExpr()))
13590       return false;
13591     if (!Result.isInt()) return Error(E);
13592     const APSInt &Value = Result.getInt();
13593     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
13594       if (Info.checkingForUndefinedBehavior())
13595         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13596                                          diag::warn_integer_constant_overflow)
13597             << toString(Value, 10) << E->getType();
13598 
13599       if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13600                           E->getType()))
13601         return false;
13602     }
13603     return Success(-Value, E);
13604   }
13605   case UO_Not: {
13606     if (!Visit(E->getSubExpr()))
13607       return false;
13608     if (!Result.isInt()) return Error(E);
13609     return Success(~Result.getInt(), E);
13610   }
13611   case UO_LNot: {
13612     bool bres;
13613     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13614       return false;
13615     return Success(!bres, E);
13616   }
13617   }
13618 }
13619 
13620 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13621 /// result type is integer.
13622 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13623   const Expr *SubExpr = E->getSubExpr();
13624   QualType DestType = E->getType();
13625   QualType SrcType = SubExpr->getType();
13626 
13627   switch (E->getCastKind()) {
13628   case CK_BaseToDerived:
13629   case CK_DerivedToBase:
13630   case CK_UncheckedDerivedToBase:
13631   case CK_Dynamic:
13632   case CK_ToUnion:
13633   case CK_ArrayToPointerDecay:
13634   case CK_FunctionToPointerDecay:
13635   case CK_NullToPointer:
13636   case CK_NullToMemberPointer:
13637   case CK_BaseToDerivedMemberPointer:
13638   case CK_DerivedToBaseMemberPointer:
13639   case CK_ReinterpretMemberPointer:
13640   case CK_ConstructorConversion:
13641   case CK_IntegralToPointer:
13642   case CK_ToVoid:
13643   case CK_VectorSplat:
13644   case CK_IntegralToFloating:
13645   case CK_FloatingCast:
13646   case CK_CPointerToObjCPointerCast:
13647   case CK_BlockPointerToObjCPointerCast:
13648   case CK_AnyPointerToBlockPointerCast:
13649   case CK_ObjCObjectLValueCast:
13650   case CK_FloatingRealToComplex:
13651   case CK_FloatingComplexToReal:
13652   case CK_FloatingComplexCast:
13653   case CK_FloatingComplexToIntegralComplex:
13654   case CK_IntegralRealToComplex:
13655   case CK_IntegralComplexCast:
13656   case CK_IntegralComplexToFloatingComplex:
13657   case CK_BuiltinFnToFnPtr:
13658   case CK_ZeroToOCLOpaqueType:
13659   case CK_NonAtomicToAtomic:
13660   case CK_AddressSpaceConversion:
13661   case CK_IntToOCLSampler:
13662   case CK_FloatingToFixedPoint:
13663   case CK_FixedPointToFloating:
13664   case CK_FixedPointCast:
13665   case CK_IntegralToFixedPoint:
13666   case CK_MatrixCast:
13667     llvm_unreachable("invalid cast kind for integral value");
13668 
13669   case CK_BitCast:
13670   case CK_Dependent:
13671   case CK_LValueBitCast:
13672   case CK_ARCProduceObject:
13673   case CK_ARCConsumeObject:
13674   case CK_ARCReclaimReturnedObject:
13675   case CK_ARCExtendBlockObject:
13676   case CK_CopyAndAutoreleaseBlockObject:
13677     return Error(E);
13678 
13679   case CK_UserDefinedConversion:
13680   case CK_LValueToRValue:
13681   case CK_AtomicToNonAtomic:
13682   case CK_NoOp:
13683   case CK_LValueToRValueBitCast:
13684     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13685 
13686   case CK_MemberPointerToBoolean:
13687   case CK_PointerToBoolean:
13688   case CK_IntegralToBoolean:
13689   case CK_FloatingToBoolean:
13690   case CK_BooleanToSignedIntegral:
13691   case CK_FloatingComplexToBoolean:
13692   case CK_IntegralComplexToBoolean: {
13693     bool BoolResult;
13694     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13695       return false;
13696     uint64_t IntResult = BoolResult;
13697     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13698       IntResult = (uint64_t)-1;
13699     return Success(IntResult, E);
13700   }
13701 
13702   case CK_FixedPointToIntegral: {
13703     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13704     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13705       return false;
13706     bool Overflowed;
13707     llvm::APSInt Result = Src.convertToInt(
13708         Info.Ctx.getIntWidth(DestType),
13709         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13710     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13711       return false;
13712     return Success(Result, E);
13713   }
13714 
13715   case CK_FixedPointToBoolean: {
13716     // Unsigned padding does not affect this.
13717     APValue Val;
13718     if (!Evaluate(Val, Info, SubExpr))
13719       return false;
13720     return Success(Val.getFixedPoint().getBoolValue(), E);
13721   }
13722 
13723   case CK_IntegralCast: {
13724     if (!Visit(SubExpr))
13725       return false;
13726 
13727     if (!Result.isInt()) {
13728       // Allow casts of address-of-label differences if they are no-ops
13729       // or narrowing.  (The narrowing case isn't actually guaranteed to
13730       // be constant-evaluatable except in some narrow cases which are hard
13731       // to detect here.  We let it through on the assumption the user knows
13732       // what they are doing.)
13733       if (Result.isAddrLabelDiff())
13734         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13735       // Only allow casts of lvalues if they are lossless.
13736       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13737     }
13738 
13739     if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13740         Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13741         DestType->isEnumeralType()) {
13742 
13743       bool ConstexprVar = true;
13744 
13745       // We know if we are here that we are in a context that we might require
13746       // a constant expression or a context that requires a constant
13747       // value. But if we are initializing a value we don't know if it is a
13748       // constexpr variable or not. We can check the EvaluatingDecl to determine
13749       // if it constexpr or not. If not then we don't want to emit a diagnostic.
13750       if (const auto *VD = dyn_cast_or_null<VarDecl>(
13751               Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13752         ConstexprVar = VD->isConstexpr();
13753 
13754       const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
13755       const EnumDecl *ED = ET->getDecl();
13756       // Check that the value is within the range of the enumeration values.
13757       //
13758       // This corressponds to [expr.static.cast]p10 which says:
13759       // A value of integral or enumeration type can be explicitly converted
13760       // to a complete enumeration type ... If the enumeration type does not
13761       // have a fixed underlying type, the value is unchanged if the original
13762       // value is within the range of the enumeration values ([dcl.enum]), and
13763       // otherwise, the behavior is undefined.
13764       //
13765       // This was resolved as part of DR2338 which has CD5 status.
13766       if (!ED->isFixed()) {
13767         llvm::APInt Min;
13768         llvm::APInt Max;
13769 
13770         ED->getValueRange(Max, Min);
13771         --Max;
13772 
13773         if (ED->getNumNegativeBits() && ConstexprVar &&
13774             (Max.slt(Result.getInt().getSExtValue()) ||
13775              Min.sgt(Result.getInt().getSExtValue())))
13776           Info.Ctx.getDiagnostics().Report(
13777               E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13778               << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
13779               << Max.getSExtValue() << ED;
13780         else if (!ED->getNumNegativeBits() && ConstexprVar &&
13781                  Max.ult(Result.getInt().getZExtValue()))
13782           Info.Ctx.getDiagnostics().Report(
13783               E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13784               << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
13785               << Max.getZExtValue() << ED;
13786       }
13787     }
13788 
13789     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13790                                       Result.getInt()), E);
13791   }
13792 
13793   case CK_PointerToIntegral: {
13794     CCEDiag(E, diag::note_constexpr_invalid_cast)
13795         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
13796 
13797     LValue LV;
13798     if (!EvaluatePointer(SubExpr, LV, Info))
13799       return false;
13800 
13801     if (LV.getLValueBase()) {
13802       // Only allow based lvalue casts if they are lossless.
13803       // FIXME: Allow a larger integer size than the pointer size, and allow
13804       // narrowing back down to pointer width in subsequent integral casts.
13805       // FIXME: Check integer type's active bits, not its type size.
13806       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13807         return Error(E);
13808 
13809       LV.Designator.setInvalid();
13810       LV.moveInto(Result);
13811       return true;
13812     }
13813 
13814     APSInt AsInt;
13815     APValue V;
13816     LV.moveInto(V);
13817     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13818       llvm_unreachable("Can't cast this!");
13819 
13820     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13821   }
13822 
13823   case CK_IntegralComplexToReal: {
13824     ComplexValue C;
13825     if (!EvaluateComplex(SubExpr, C, Info))
13826       return false;
13827     return Success(C.getComplexIntReal(), E);
13828   }
13829 
13830   case CK_FloatingToIntegral: {
13831     APFloat F(0.0);
13832     if (!EvaluateFloat(SubExpr, F, Info))
13833       return false;
13834 
13835     APSInt Value;
13836     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13837       return false;
13838     return Success(Value, E);
13839   }
13840   }
13841 
13842   llvm_unreachable("unknown cast resulting in integral value");
13843 }
13844 
13845 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13846   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13847     ComplexValue LV;
13848     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13849       return false;
13850     if (!LV.isComplexInt())
13851       return Error(E);
13852     return Success(LV.getComplexIntReal(), E);
13853   }
13854 
13855   return Visit(E->getSubExpr());
13856 }
13857 
13858 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13859   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13860     ComplexValue LV;
13861     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13862       return false;
13863     if (!LV.isComplexInt())
13864       return Error(E);
13865     return Success(LV.getComplexIntImag(), E);
13866   }
13867 
13868   VisitIgnoredValue(E->getSubExpr());
13869   return Success(0, E);
13870 }
13871 
13872 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13873   return Success(E->getPackLength(), E);
13874 }
13875 
13876 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13877   return Success(E->getValue(), E);
13878 }
13879 
13880 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13881        const ConceptSpecializationExpr *E) {
13882   return Success(E->isSatisfied(), E);
13883 }
13884 
13885 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13886   return Success(E->isSatisfied(), E);
13887 }
13888 
13889 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13890   switch (E->getOpcode()) {
13891     default:
13892       // Invalid unary operators
13893       return Error(E);
13894     case UO_Plus:
13895       // The result is just the value.
13896       return Visit(E->getSubExpr());
13897     case UO_Minus: {
13898       if (!Visit(E->getSubExpr())) return false;
13899       if (!Result.isFixedPoint())
13900         return Error(E);
13901       bool Overflowed;
13902       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13903       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13904         return false;
13905       return Success(Negated, E);
13906     }
13907     case UO_LNot: {
13908       bool bres;
13909       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13910         return false;
13911       return Success(!bres, E);
13912     }
13913   }
13914 }
13915 
13916 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13917   const Expr *SubExpr = E->getSubExpr();
13918   QualType DestType = E->getType();
13919   assert(DestType->isFixedPointType() &&
13920          "Expected destination type to be a fixed point type");
13921   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13922 
13923   switch (E->getCastKind()) {
13924   case CK_FixedPointCast: {
13925     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13926     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13927       return false;
13928     bool Overflowed;
13929     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13930     if (Overflowed) {
13931       if (Info.checkingForUndefinedBehavior())
13932         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13933                                          diag::warn_fixedpoint_constant_overflow)
13934           << Result.toString() << E->getType();
13935       if (!HandleOverflow(Info, E, Result, E->getType()))
13936         return false;
13937     }
13938     return Success(Result, E);
13939   }
13940   case CK_IntegralToFixedPoint: {
13941     APSInt Src;
13942     if (!EvaluateInteger(SubExpr, Src, Info))
13943       return false;
13944 
13945     bool Overflowed;
13946     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13947         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13948 
13949     if (Overflowed) {
13950       if (Info.checkingForUndefinedBehavior())
13951         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13952                                          diag::warn_fixedpoint_constant_overflow)
13953           << IntResult.toString() << E->getType();
13954       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13955         return false;
13956     }
13957 
13958     return Success(IntResult, E);
13959   }
13960   case CK_FloatingToFixedPoint: {
13961     APFloat Src(0.0);
13962     if (!EvaluateFloat(SubExpr, Src, Info))
13963       return false;
13964 
13965     bool Overflowed;
13966     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13967         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13968 
13969     if (Overflowed) {
13970       if (Info.checkingForUndefinedBehavior())
13971         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13972                                          diag::warn_fixedpoint_constant_overflow)
13973           << Result.toString() << E->getType();
13974       if (!HandleOverflow(Info, E, Result, E->getType()))
13975         return false;
13976     }
13977 
13978     return Success(Result, E);
13979   }
13980   case CK_NoOp:
13981   case CK_LValueToRValue:
13982     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13983   default:
13984     return Error(E);
13985   }
13986 }
13987 
13988 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13989   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13990     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13991 
13992   const Expr *LHS = E->getLHS();
13993   const Expr *RHS = E->getRHS();
13994   FixedPointSemantics ResultFXSema =
13995       Info.Ctx.getFixedPointSemantics(E->getType());
13996 
13997   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13998   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13999     return false;
14000   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
14001   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
14002     return false;
14003 
14004   bool OpOverflow = false, ConversionOverflow = false;
14005   APFixedPoint Result(LHSFX.getSemantics());
14006   switch (E->getOpcode()) {
14007   case BO_Add: {
14008     Result = LHSFX.add(RHSFX, &OpOverflow)
14009                   .convert(ResultFXSema, &ConversionOverflow);
14010     break;
14011   }
14012   case BO_Sub: {
14013     Result = LHSFX.sub(RHSFX, &OpOverflow)
14014                   .convert(ResultFXSema, &ConversionOverflow);
14015     break;
14016   }
14017   case BO_Mul: {
14018     Result = LHSFX.mul(RHSFX, &OpOverflow)
14019                   .convert(ResultFXSema, &ConversionOverflow);
14020     break;
14021   }
14022   case BO_Div: {
14023     if (RHSFX.getValue() == 0) {
14024       Info.FFDiag(E, diag::note_expr_divide_by_zero);
14025       return false;
14026     }
14027     Result = LHSFX.div(RHSFX, &OpOverflow)
14028                   .convert(ResultFXSema, &ConversionOverflow);
14029     break;
14030   }
14031   case BO_Shl:
14032   case BO_Shr: {
14033     FixedPointSemantics LHSSema = LHSFX.getSemantics();
14034     llvm::APSInt RHSVal = RHSFX.getValue();
14035 
14036     unsigned ShiftBW =
14037         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14038     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
14039     // Embedded-C 4.1.6.2.2:
14040     //   The right operand must be nonnegative and less than the total number
14041     //   of (nonpadding) bits of the fixed-point operand ...
14042     if (RHSVal.isNegative())
14043       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
14044     else if (Amt != RHSVal)
14045       Info.CCEDiag(E, diag::note_constexpr_large_shift)
14046           << RHSVal << E->getType() << ShiftBW;
14047 
14048     if (E->getOpcode() == BO_Shl)
14049       Result = LHSFX.shl(Amt, &OpOverflow);
14050     else
14051       Result = LHSFX.shr(Amt, &OpOverflow);
14052     break;
14053   }
14054   default:
14055     return false;
14056   }
14057   if (OpOverflow || ConversionOverflow) {
14058     if (Info.checkingForUndefinedBehavior())
14059       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14060                                        diag::warn_fixedpoint_constant_overflow)
14061         << Result.toString() << E->getType();
14062     if (!HandleOverflow(Info, E, Result, E->getType()))
14063       return false;
14064   }
14065   return Success(Result, E);
14066 }
14067 
14068 //===----------------------------------------------------------------------===//
14069 // Float Evaluation
14070 //===----------------------------------------------------------------------===//
14071 
14072 namespace {
14073 class FloatExprEvaluator
14074   : public ExprEvaluatorBase<FloatExprEvaluator> {
14075   APFloat &Result;
14076 public:
14077   FloatExprEvaluator(EvalInfo &info, APFloat &result)
14078     : ExprEvaluatorBaseTy(info), Result(result) {}
14079 
14080   bool Success(const APValue &V, const Expr *e) {
14081     Result = V.getFloat();
14082     return true;
14083   }
14084 
14085   bool ZeroInitialization(const Expr *E) {
14086     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14087     return true;
14088   }
14089 
14090   bool VisitCallExpr(const CallExpr *E);
14091 
14092   bool VisitUnaryOperator(const UnaryOperator *E);
14093   bool VisitBinaryOperator(const BinaryOperator *E);
14094   bool VisitFloatingLiteral(const FloatingLiteral *E);
14095   bool VisitCastExpr(const CastExpr *E);
14096 
14097   bool VisitUnaryReal(const UnaryOperator *E);
14098   bool VisitUnaryImag(const UnaryOperator *E);
14099 
14100   // FIXME: Missing: array subscript of vector, member of vector
14101 };
14102 } // end anonymous namespace
14103 
14104 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14105   assert(!E->isValueDependent());
14106   assert(E->isPRValue() && E->getType()->isRealFloatingType());
14107   return FloatExprEvaluator(Info, Result).Visit(E);
14108 }
14109 
14110 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14111                                   QualType ResultTy,
14112                                   const Expr *Arg,
14113                                   bool SNaN,
14114                                   llvm::APFloat &Result) {
14115   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14116   if (!S) return false;
14117 
14118   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14119 
14120   llvm::APInt fill;
14121 
14122   // Treat empty strings as if they were zero.
14123   if (S->getString().empty())
14124     fill = llvm::APInt(32, 0);
14125   else if (S->getString().getAsInteger(0, fill))
14126     return false;
14127 
14128   if (Context.getTargetInfo().isNan2008()) {
14129     if (SNaN)
14130       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14131     else
14132       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14133   } else {
14134     // Prior to IEEE 754-2008, architectures were allowed to choose whether
14135     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14136     // a different encoding to what became a standard in 2008, and for pre-
14137     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14138     // sNaN. This is now known as "legacy NaN" encoding.
14139     if (SNaN)
14140       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14141     else
14142       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14143   }
14144 
14145   return true;
14146 }
14147 
14148 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14149   if (!IsConstantEvaluatedBuiltinCall(E))
14150     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14151 
14152   switch (E->getBuiltinCallee()) {
14153   default:
14154     return false;
14155 
14156   case Builtin::BI__builtin_huge_val:
14157   case Builtin::BI__builtin_huge_valf:
14158   case Builtin::BI__builtin_huge_vall:
14159   case Builtin::BI__builtin_huge_valf16:
14160   case Builtin::BI__builtin_huge_valf128:
14161   case Builtin::BI__builtin_inf:
14162   case Builtin::BI__builtin_inff:
14163   case Builtin::BI__builtin_infl:
14164   case Builtin::BI__builtin_inff16:
14165   case Builtin::BI__builtin_inff128: {
14166     const llvm::fltSemantics &Sem =
14167       Info.Ctx.getFloatTypeSemantics(E->getType());
14168     Result = llvm::APFloat::getInf(Sem);
14169     return true;
14170   }
14171 
14172   case Builtin::BI__builtin_nans:
14173   case Builtin::BI__builtin_nansf:
14174   case Builtin::BI__builtin_nansl:
14175   case Builtin::BI__builtin_nansf16:
14176   case Builtin::BI__builtin_nansf128:
14177     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14178                                true, Result))
14179       return Error(E);
14180     return true;
14181 
14182   case Builtin::BI__builtin_nan:
14183   case Builtin::BI__builtin_nanf:
14184   case Builtin::BI__builtin_nanl:
14185   case Builtin::BI__builtin_nanf16:
14186   case Builtin::BI__builtin_nanf128:
14187     // If this is __builtin_nan() turn this into a nan, otherwise we
14188     // can't constant fold it.
14189     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14190                                false, Result))
14191       return Error(E);
14192     return true;
14193 
14194   case Builtin::BI__builtin_fabs:
14195   case Builtin::BI__builtin_fabsf:
14196   case Builtin::BI__builtin_fabsl:
14197   case Builtin::BI__builtin_fabsf128:
14198     // The C standard says "fabs raises no floating-point exceptions,
14199     // even if x is a signaling NaN. The returned value is independent of
14200     // the current rounding direction mode."  Therefore constant folding can
14201     // proceed without regard to the floating point settings.
14202     // Reference, WG14 N2478 F.10.4.3
14203     if (!EvaluateFloat(E->getArg(0), Result, Info))
14204       return false;
14205 
14206     if (Result.isNegative())
14207       Result.changeSign();
14208     return true;
14209 
14210   case Builtin::BI__arithmetic_fence:
14211     return EvaluateFloat(E->getArg(0), Result, Info);
14212 
14213   // FIXME: Builtin::BI__builtin_powi
14214   // FIXME: Builtin::BI__builtin_powif
14215   // FIXME: Builtin::BI__builtin_powil
14216 
14217   case Builtin::BI__builtin_copysign:
14218   case Builtin::BI__builtin_copysignf:
14219   case Builtin::BI__builtin_copysignl:
14220   case Builtin::BI__builtin_copysignf128: {
14221     APFloat RHS(0.);
14222     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14223         !EvaluateFloat(E->getArg(1), RHS, Info))
14224       return false;
14225     Result.copySign(RHS);
14226     return true;
14227   }
14228 
14229   case Builtin::BI__builtin_fmax:
14230   case Builtin::BI__builtin_fmaxf:
14231   case Builtin::BI__builtin_fmaxl:
14232   case Builtin::BI__builtin_fmaxf16:
14233   case Builtin::BI__builtin_fmaxf128: {
14234     // TODO: Handle sNaN.
14235     APFloat RHS(0.);
14236     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14237         !EvaluateFloat(E->getArg(1), RHS, Info))
14238       return false;
14239     // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14240     if (Result.isZero() && RHS.isZero() && Result.isNegative())
14241       Result = RHS;
14242     else if (Result.isNaN() || RHS > Result)
14243       Result = RHS;
14244     return true;
14245   }
14246 
14247   case Builtin::BI__builtin_fmin:
14248   case Builtin::BI__builtin_fminf:
14249   case Builtin::BI__builtin_fminl:
14250   case Builtin::BI__builtin_fminf16:
14251   case Builtin::BI__builtin_fminf128: {
14252     // TODO: Handle sNaN.
14253     APFloat RHS(0.);
14254     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14255         !EvaluateFloat(E->getArg(1), RHS, Info))
14256       return false;
14257     // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14258     if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14259       Result = RHS;
14260     else if (Result.isNaN() || RHS < Result)
14261       Result = RHS;
14262     return true;
14263   }
14264   }
14265 }
14266 
14267 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14268   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14269     ComplexValue CV;
14270     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14271       return false;
14272     Result = CV.FloatReal;
14273     return true;
14274   }
14275 
14276   return Visit(E->getSubExpr());
14277 }
14278 
14279 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14280   if (E->getSubExpr()->getType()->isAnyComplexType()) {
14281     ComplexValue CV;
14282     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14283       return false;
14284     Result = CV.FloatImag;
14285     return true;
14286   }
14287 
14288   VisitIgnoredValue(E->getSubExpr());
14289   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14290   Result = llvm::APFloat::getZero(Sem);
14291   return true;
14292 }
14293 
14294 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14295   switch (E->getOpcode()) {
14296   default: return Error(E);
14297   case UO_Plus:
14298     return EvaluateFloat(E->getSubExpr(), Result, Info);
14299   case UO_Minus:
14300     // In C standard, WG14 N2478 F.3 p4
14301     // "the unary - raises no floating point exceptions,
14302     // even if the operand is signalling."
14303     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14304       return false;
14305     Result.changeSign();
14306     return true;
14307   }
14308 }
14309 
14310 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14311   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14312     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14313 
14314   APFloat RHS(0.0);
14315   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14316   if (!LHSOK && !Info.noteFailure())
14317     return false;
14318   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14319          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14320 }
14321 
14322 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14323   Result = E->getValue();
14324   return true;
14325 }
14326 
14327 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14328   const Expr* SubExpr = E->getSubExpr();
14329 
14330   switch (E->getCastKind()) {
14331   default:
14332     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14333 
14334   case CK_IntegralToFloating: {
14335     APSInt IntResult;
14336     const FPOptions FPO = E->getFPFeaturesInEffect(
14337                                   Info.Ctx.getLangOpts());
14338     return EvaluateInteger(SubExpr, IntResult, Info) &&
14339            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14340                                 IntResult, E->getType(), Result);
14341   }
14342 
14343   case CK_FixedPointToFloating: {
14344     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14345     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14346       return false;
14347     Result =
14348         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14349     return true;
14350   }
14351 
14352   case CK_FloatingCast: {
14353     if (!Visit(SubExpr))
14354       return false;
14355     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14356                                   Result);
14357   }
14358 
14359   case CK_FloatingComplexToReal: {
14360     ComplexValue V;
14361     if (!EvaluateComplex(SubExpr, V, Info))
14362       return false;
14363     Result = V.getComplexFloatReal();
14364     return true;
14365   }
14366   }
14367 }
14368 
14369 //===----------------------------------------------------------------------===//
14370 // Complex Evaluation (for float and integer)
14371 //===----------------------------------------------------------------------===//
14372 
14373 namespace {
14374 class ComplexExprEvaluator
14375   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14376   ComplexValue &Result;
14377 
14378 public:
14379   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14380     : ExprEvaluatorBaseTy(info), Result(Result) {}
14381 
14382   bool Success(const APValue &V, const Expr *e) {
14383     Result.setFrom(V);
14384     return true;
14385   }
14386 
14387   bool ZeroInitialization(const Expr *E);
14388 
14389   //===--------------------------------------------------------------------===//
14390   //                            Visitor Methods
14391   //===--------------------------------------------------------------------===//
14392 
14393   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14394   bool VisitCastExpr(const CastExpr *E);
14395   bool VisitBinaryOperator(const BinaryOperator *E);
14396   bool VisitUnaryOperator(const UnaryOperator *E);
14397   bool VisitInitListExpr(const InitListExpr *E);
14398   bool VisitCallExpr(const CallExpr *E);
14399 };
14400 } // end anonymous namespace
14401 
14402 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14403                             EvalInfo &Info) {
14404   assert(!E->isValueDependent());
14405   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14406   return ComplexExprEvaluator(Info, Result).Visit(E);
14407 }
14408 
14409 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14410   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14411   if (ElemTy->isRealFloatingType()) {
14412     Result.makeComplexFloat();
14413     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14414     Result.FloatReal = Zero;
14415     Result.FloatImag = Zero;
14416   } else {
14417     Result.makeComplexInt();
14418     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14419     Result.IntReal = Zero;
14420     Result.IntImag = Zero;
14421   }
14422   return true;
14423 }
14424 
14425 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14426   const Expr* SubExpr = E->getSubExpr();
14427 
14428   if (SubExpr->getType()->isRealFloatingType()) {
14429     Result.makeComplexFloat();
14430     APFloat &Imag = Result.FloatImag;
14431     if (!EvaluateFloat(SubExpr, Imag, Info))
14432       return false;
14433 
14434     Result.FloatReal = APFloat(Imag.getSemantics());
14435     return true;
14436   } else {
14437     assert(SubExpr->getType()->isIntegerType() &&
14438            "Unexpected imaginary literal.");
14439 
14440     Result.makeComplexInt();
14441     APSInt &Imag = Result.IntImag;
14442     if (!EvaluateInteger(SubExpr, Imag, Info))
14443       return false;
14444 
14445     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14446     return true;
14447   }
14448 }
14449 
14450 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14451 
14452   switch (E->getCastKind()) {
14453   case CK_BitCast:
14454   case CK_BaseToDerived:
14455   case CK_DerivedToBase:
14456   case CK_UncheckedDerivedToBase:
14457   case CK_Dynamic:
14458   case CK_ToUnion:
14459   case CK_ArrayToPointerDecay:
14460   case CK_FunctionToPointerDecay:
14461   case CK_NullToPointer:
14462   case CK_NullToMemberPointer:
14463   case CK_BaseToDerivedMemberPointer:
14464   case CK_DerivedToBaseMemberPointer:
14465   case CK_MemberPointerToBoolean:
14466   case CK_ReinterpretMemberPointer:
14467   case CK_ConstructorConversion:
14468   case CK_IntegralToPointer:
14469   case CK_PointerToIntegral:
14470   case CK_PointerToBoolean:
14471   case CK_ToVoid:
14472   case CK_VectorSplat:
14473   case CK_IntegralCast:
14474   case CK_BooleanToSignedIntegral:
14475   case CK_IntegralToBoolean:
14476   case CK_IntegralToFloating:
14477   case CK_FloatingToIntegral:
14478   case CK_FloatingToBoolean:
14479   case CK_FloatingCast:
14480   case CK_CPointerToObjCPointerCast:
14481   case CK_BlockPointerToObjCPointerCast:
14482   case CK_AnyPointerToBlockPointerCast:
14483   case CK_ObjCObjectLValueCast:
14484   case CK_FloatingComplexToReal:
14485   case CK_FloatingComplexToBoolean:
14486   case CK_IntegralComplexToReal:
14487   case CK_IntegralComplexToBoolean:
14488   case CK_ARCProduceObject:
14489   case CK_ARCConsumeObject:
14490   case CK_ARCReclaimReturnedObject:
14491   case CK_ARCExtendBlockObject:
14492   case CK_CopyAndAutoreleaseBlockObject:
14493   case CK_BuiltinFnToFnPtr:
14494   case CK_ZeroToOCLOpaqueType:
14495   case CK_NonAtomicToAtomic:
14496   case CK_AddressSpaceConversion:
14497   case CK_IntToOCLSampler:
14498   case CK_FloatingToFixedPoint:
14499   case CK_FixedPointToFloating:
14500   case CK_FixedPointCast:
14501   case CK_FixedPointToBoolean:
14502   case CK_FixedPointToIntegral:
14503   case CK_IntegralToFixedPoint:
14504   case CK_MatrixCast:
14505     llvm_unreachable("invalid cast kind for complex value");
14506 
14507   case CK_LValueToRValue:
14508   case CK_AtomicToNonAtomic:
14509   case CK_NoOp:
14510   case CK_LValueToRValueBitCast:
14511     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14512 
14513   case CK_Dependent:
14514   case CK_LValueBitCast:
14515   case CK_UserDefinedConversion:
14516     return Error(E);
14517 
14518   case CK_FloatingRealToComplex: {
14519     APFloat &Real = Result.FloatReal;
14520     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14521       return false;
14522 
14523     Result.makeComplexFloat();
14524     Result.FloatImag = APFloat(Real.getSemantics());
14525     return true;
14526   }
14527 
14528   case CK_FloatingComplexCast: {
14529     if (!Visit(E->getSubExpr()))
14530       return false;
14531 
14532     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14533     QualType From
14534       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14535 
14536     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14537            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14538   }
14539 
14540   case CK_FloatingComplexToIntegralComplex: {
14541     if (!Visit(E->getSubExpr()))
14542       return false;
14543 
14544     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14545     QualType From
14546       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14547     Result.makeComplexInt();
14548     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14549                                 To, Result.IntReal) &&
14550            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14551                                 To, Result.IntImag);
14552   }
14553 
14554   case CK_IntegralRealToComplex: {
14555     APSInt &Real = Result.IntReal;
14556     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14557       return false;
14558 
14559     Result.makeComplexInt();
14560     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14561     return true;
14562   }
14563 
14564   case CK_IntegralComplexCast: {
14565     if (!Visit(E->getSubExpr()))
14566       return false;
14567 
14568     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14569     QualType From
14570       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14571 
14572     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14573     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14574     return true;
14575   }
14576 
14577   case CK_IntegralComplexToFloatingComplex: {
14578     if (!Visit(E->getSubExpr()))
14579       return false;
14580 
14581     const FPOptions FPO = E->getFPFeaturesInEffect(
14582                                   Info.Ctx.getLangOpts());
14583     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14584     QualType From
14585       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14586     Result.makeComplexFloat();
14587     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14588                                 To, Result.FloatReal) &&
14589            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14590                                 To, Result.FloatImag);
14591   }
14592   }
14593 
14594   llvm_unreachable("unknown cast resulting in complex value");
14595 }
14596 
14597 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14598   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14599     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14600 
14601   // Track whether the LHS or RHS is real at the type system level. When this is
14602   // the case we can simplify our evaluation strategy.
14603   bool LHSReal = false, RHSReal = false;
14604 
14605   bool LHSOK;
14606   if (E->getLHS()->getType()->isRealFloatingType()) {
14607     LHSReal = true;
14608     APFloat &Real = Result.FloatReal;
14609     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14610     if (LHSOK) {
14611       Result.makeComplexFloat();
14612       Result.FloatImag = APFloat(Real.getSemantics());
14613     }
14614   } else {
14615     LHSOK = Visit(E->getLHS());
14616   }
14617   if (!LHSOK && !Info.noteFailure())
14618     return false;
14619 
14620   ComplexValue RHS;
14621   if (E->getRHS()->getType()->isRealFloatingType()) {
14622     RHSReal = true;
14623     APFloat &Real = RHS.FloatReal;
14624     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14625       return false;
14626     RHS.makeComplexFloat();
14627     RHS.FloatImag = APFloat(Real.getSemantics());
14628   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14629     return false;
14630 
14631   assert(!(LHSReal && RHSReal) &&
14632          "Cannot have both operands of a complex operation be real.");
14633   switch (E->getOpcode()) {
14634   default: return Error(E);
14635   case BO_Add:
14636     if (Result.isComplexFloat()) {
14637       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14638                                        APFloat::rmNearestTiesToEven);
14639       if (LHSReal)
14640         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14641       else if (!RHSReal)
14642         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14643                                          APFloat::rmNearestTiesToEven);
14644     } else {
14645       Result.getComplexIntReal() += RHS.getComplexIntReal();
14646       Result.getComplexIntImag() += RHS.getComplexIntImag();
14647     }
14648     break;
14649   case BO_Sub:
14650     if (Result.isComplexFloat()) {
14651       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14652                                             APFloat::rmNearestTiesToEven);
14653       if (LHSReal) {
14654         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14655         Result.getComplexFloatImag().changeSign();
14656       } else if (!RHSReal) {
14657         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14658                                               APFloat::rmNearestTiesToEven);
14659       }
14660     } else {
14661       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14662       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14663     }
14664     break;
14665   case BO_Mul:
14666     if (Result.isComplexFloat()) {
14667       // This is an implementation of complex multiplication according to the
14668       // constraints laid out in C11 Annex G. The implementation uses the
14669       // following naming scheme:
14670       //   (a + ib) * (c + id)
14671       ComplexValue LHS = Result;
14672       APFloat &A = LHS.getComplexFloatReal();
14673       APFloat &B = LHS.getComplexFloatImag();
14674       APFloat &C = RHS.getComplexFloatReal();
14675       APFloat &D = RHS.getComplexFloatImag();
14676       APFloat &ResR = Result.getComplexFloatReal();
14677       APFloat &ResI = Result.getComplexFloatImag();
14678       if (LHSReal) {
14679         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14680         ResR = A * C;
14681         ResI = A * D;
14682       } else if (RHSReal) {
14683         ResR = C * A;
14684         ResI = C * B;
14685       } else {
14686         // In the fully general case, we need to handle NaNs and infinities
14687         // robustly.
14688         APFloat AC = A * C;
14689         APFloat BD = B * D;
14690         APFloat AD = A * D;
14691         APFloat BC = B * C;
14692         ResR = AC - BD;
14693         ResI = AD + BC;
14694         if (ResR.isNaN() && ResI.isNaN()) {
14695           bool Recalc = false;
14696           if (A.isInfinity() || B.isInfinity()) {
14697             A = APFloat::copySign(
14698                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14699             B = APFloat::copySign(
14700                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14701             if (C.isNaN())
14702               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14703             if (D.isNaN())
14704               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14705             Recalc = true;
14706           }
14707           if (C.isInfinity() || D.isInfinity()) {
14708             C = APFloat::copySign(
14709                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14710             D = APFloat::copySign(
14711                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14712             if (A.isNaN())
14713               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14714             if (B.isNaN())
14715               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14716             Recalc = true;
14717           }
14718           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14719                           AD.isInfinity() || BC.isInfinity())) {
14720             if (A.isNaN())
14721               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14722             if (B.isNaN())
14723               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14724             if (C.isNaN())
14725               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14726             if (D.isNaN())
14727               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14728             Recalc = true;
14729           }
14730           if (Recalc) {
14731             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14732             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14733           }
14734         }
14735       }
14736     } else {
14737       ComplexValue LHS = Result;
14738       Result.getComplexIntReal() =
14739         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14740          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14741       Result.getComplexIntImag() =
14742         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14743          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14744     }
14745     break;
14746   case BO_Div:
14747     if (Result.isComplexFloat()) {
14748       // This is an implementation of complex division according to the
14749       // constraints laid out in C11 Annex G. The implementation uses the
14750       // following naming scheme:
14751       //   (a + ib) / (c + id)
14752       ComplexValue LHS = Result;
14753       APFloat &A = LHS.getComplexFloatReal();
14754       APFloat &B = LHS.getComplexFloatImag();
14755       APFloat &C = RHS.getComplexFloatReal();
14756       APFloat &D = RHS.getComplexFloatImag();
14757       APFloat &ResR = Result.getComplexFloatReal();
14758       APFloat &ResI = Result.getComplexFloatImag();
14759       if (RHSReal) {
14760         ResR = A / C;
14761         ResI = B / C;
14762       } else {
14763         if (LHSReal) {
14764           // No real optimizations we can do here, stub out with zero.
14765           B = APFloat::getZero(A.getSemantics());
14766         }
14767         int DenomLogB = 0;
14768         APFloat MaxCD = maxnum(abs(C), abs(D));
14769         if (MaxCD.isFinite()) {
14770           DenomLogB = ilogb(MaxCD);
14771           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14772           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14773         }
14774         APFloat Denom = C * C + D * D;
14775         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14776                       APFloat::rmNearestTiesToEven);
14777         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14778                       APFloat::rmNearestTiesToEven);
14779         if (ResR.isNaN() && ResI.isNaN()) {
14780           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14781             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14782             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14783           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14784                      D.isFinite()) {
14785             A = APFloat::copySign(
14786                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14787             B = APFloat::copySign(
14788                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14789             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14790             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14791           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14792             C = APFloat::copySign(
14793                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14794             D = APFloat::copySign(
14795                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14796             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14797             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14798           }
14799         }
14800       }
14801     } else {
14802       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14803         return Error(E, diag::note_expr_divide_by_zero);
14804 
14805       ComplexValue LHS = Result;
14806       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14807         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14808       Result.getComplexIntReal() =
14809         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14810          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14811       Result.getComplexIntImag() =
14812         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14813          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14814     }
14815     break;
14816   }
14817 
14818   return true;
14819 }
14820 
14821 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14822   // Get the operand value into 'Result'.
14823   if (!Visit(E->getSubExpr()))
14824     return false;
14825 
14826   switch (E->getOpcode()) {
14827   default:
14828     return Error(E);
14829   case UO_Extension:
14830     return true;
14831   case UO_Plus:
14832     // The result is always just the subexpr.
14833     return true;
14834   case UO_Minus:
14835     if (Result.isComplexFloat()) {
14836       Result.getComplexFloatReal().changeSign();
14837       Result.getComplexFloatImag().changeSign();
14838     }
14839     else {
14840       Result.getComplexIntReal() = -Result.getComplexIntReal();
14841       Result.getComplexIntImag() = -Result.getComplexIntImag();
14842     }
14843     return true;
14844   case UO_Not:
14845     if (Result.isComplexFloat())
14846       Result.getComplexFloatImag().changeSign();
14847     else
14848       Result.getComplexIntImag() = -Result.getComplexIntImag();
14849     return true;
14850   }
14851 }
14852 
14853 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14854   if (E->getNumInits() == 2) {
14855     if (E->getType()->isComplexType()) {
14856       Result.makeComplexFloat();
14857       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14858         return false;
14859       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14860         return false;
14861     } else {
14862       Result.makeComplexInt();
14863       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14864         return false;
14865       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14866         return false;
14867     }
14868     return true;
14869   }
14870   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14871 }
14872 
14873 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14874   if (!IsConstantEvaluatedBuiltinCall(E))
14875     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14876 
14877   switch (E->getBuiltinCallee()) {
14878   case Builtin::BI__builtin_complex:
14879     Result.makeComplexFloat();
14880     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14881       return false;
14882     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14883       return false;
14884     return true;
14885 
14886   default:
14887     return false;
14888   }
14889 }
14890 
14891 //===----------------------------------------------------------------------===//
14892 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14893 // implicit conversion.
14894 //===----------------------------------------------------------------------===//
14895 
14896 namespace {
14897 class AtomicExprEvaluator :
14898     public ExprEvaluatorBase<AtomicExprEvaluator> {
14899   const LValue *This;
14900   APValue &Result;
14901 public:
14902   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14903       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14904 
14905   bool Success(const APValue &V, const Expr *E) {
14906     Result = V;
14907     return true;
14908   }
14909 
14910   bool ZeroInitialization(const Expr *E) {
14911     ImplicitValueInitExpr VIE(
14912         E->getType()->castAs<AtomicType>()->getValueType());
14913     // For atomic-qualified class (and array) types in C++, initialize the
14914     // _Atomic-wrapped subobject directly, in-place.
14915     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14916                 : Evaluate(Result, Info, &VIE);
14917   }
14918 
14919   bool VisitCastExpr(const CastExpr *E) {
14920     switch (E->getCastKind()) {
14921     default:
14922       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14923     case CK_NullToPointer:
14924       VisitIgnoredValue(E->getSubExpr());
14925       return ZeroInitialization(E);
14926     case CK_NonAtomicToAtomic:
14927       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14928                   : Evaluate(Result, Info, E->getSubExpr());
14929     }
14930   }
14931 };
14932 } // end anonymous namespace
14933 
14934 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14935                            EvalInfo &Info) {
14936   assert(!E->isValueDependent());
14937   assert(E->isPRValue() && E->getType()->isAtomicType());
14938   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14939 }
14940 
14941 //===----------------------------------------------------------------------===//
14942 // Void expression evaluation, primarily for a cast to void on the LHS of a
14943 // comma operator
14944 //===----------------------------------------------------------------------===//
14945 
14946 namespace {
14947 class VoidExprEvaluator
14948   : public ExprEvaluatorBase<VoidExprEvaluator> {
14949 public:
14950   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14951 
14952   bool Success(const APValue &V, const Expr *e) { return true; }
14953 
14954   bool ZeroInitialization(const Expr *E) { return true; }
14955 
14956   bool VisitCastExpr(const CastExpr *E) {
14957     switch (E->getCastKind()) {
14958     default:
14959       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14960     case CK_ToVoid:
14961       VisitIgnoredValue(E->getSubExpr());
14962       return true;
14963     }
14964   }
14965 
14966   bool VisitCallExpr(const CallExpr *E) {
14967     if (!IsConstantEvaluatedBuiltinCall(E))
14968       return ExprEvaluatorBaseTy::VisitCallExpr(E);
14969 
14970     switch (E->getBuiltinCallee()) {
14971     case Builtin::BI__assume:
14972     case Builtin::BI__builtin_assume:
14973       // The argument is not evaluated!
14974       return true;
14975 
14976     case Builtin::BI__builtin_operator_delete:
14977       return HandleOperatorDeleteCall(Info, E);
14978 
14979     default:
14980       return false;
14981     }
14982   }
14983 
14984   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14985 };
14986 } // end anonymous namespace
14987 
14988 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14989   // We cannot speculatively evaluate a delete expression.
14990   if (Info.SpeculativeEvaluationDepth)
14991     return false;
14992 
14993   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14994   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14995     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14996         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14997     return false;
14998   }
14999 
15000   const Expr *Arg = E->getArgument();
15001 
15002   LValue Pointer;
15003   if (!EvaluatePointer(Arg, Pointer, Info))
15004     return false;
15005   if (Pointer.Designator.Invalid)
15006     return false;
15007 
15008   // Deleting a null pointer has no effect.
15009   if (Pointer.isNullPointer()) {
15010     // This is the only case where we need to produce an extension warning:
15011     // the only other way we can succeed is if we find a dynamic allocation,
15012     // and we will have warned when we allocated it in that case.
15013     if (!Info.getLangOpts().CPlusPlus20)
15014       Info.CCEDiag(E, diag::note_constexpr_new);
15015     return true;
15016   }
15017 
15018   std::optional<DynAlloc *> Alloc = CheckDeleteKind(
15019       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
15020   if (!Alloc)
15021     return false;
15022   QualType AllocType = Pointer.Base.getDynamicAllocType();
15023 
15024   // For the non-array case, the designator must be empty if the static type
15025   // does not have a virtual destructor.
15026   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
15027       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
15028     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
15029         << Arg->getType()->getPointeeType() << AllocType;
15030     return false;
15031   }
15032 
15033   // For a class type with a virtual destructor, the selected operator delete
15034   // is the one looked up when building the destructor.
15035   if (!E->isArrayForm() && !E->isGlobalDelete()) {
15036     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
15037     if (VirtualDelete &&
15038         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
15039       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15040           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
15041       return false;
15042     }
15043   }
15044 
15045   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
15046                          (*Alloc)->Value, AllocType))
15047     return false;
15048 
15049   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
15050     // The element was already erased. This means the destructor call also
15051     // deleted the object.
15052     // FIXME: This probably results in undefined behavior before we get this
15053     // far, and should be diagnosed elsewhere first.
15054     Info.FFDiag(E, diag::note_constexpr_double_delete);
15055     return false;
15056   }
15057 
15058   return true;
15059 }
15060 
15061 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
15062   assert(!E->isValueDependent());
15063   assert(E->isPRValue() && E->getType()->isVoidType());
15064   return VoidExprEvaluator(Info).Visit(E);
15065 }
15066 
15067 //===----------------------------------------------------------------------===//
15068 // Top level Expr::EvaluateAsRValue method.
15069 //===----------------------------------------------------------------------===//
15070 
15071 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
15072   assert(!E->isValueDependent());
15073   // In C, function designators are not lvalues, but we evaluate them as if they
15074   // are.
15075   QualType T = E->getType();
15076   if (E->isGLValue() || T->isFunctionType()) {
15077     LValue LV;
15078     if (!EvaluateLValue(E, LV, Info))
15079       return false;
15080     LV.moveInto(Result);
15081   } else if (T->isVectorType()) {
15082     if (!EvaluateVector(E, Result, Info))
15083       return false;
15084   } else if (T->isIntegralOrEnumerationType()) {
15085     if (!IntExprEvaluator(Info, Result).Visit(E))
15086       return false;
15087   } else if (T->hasPointerRepresentation()) {
15088     LValue LV;
15089     if (!EvaluatePointer(E, LV, Info))
15090       return false;
15091     LV.moveInto(Result);
15092   } else if (T->isRealFloatingType()) {
15093     llvm::APFloat F(0.0);
15094     if (!EvaluateFloat(E, F, Info))
15095       return false;
15096     Result = APValue(F);
15097   } else if (T->isAnyComplexType()) {
15098     ComplexValue C;
15099     if (!EvaluateComplex(E, C, Info))
15100       return false;
15101     C.moveInto(Result);
15102   } else if (T->isFixedPointType()) {
15103     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15104   } else if (T->isMemberPointerType()) {
15105     MemberPtr P;
15106     if (!EvaluateMemberPointer(E, P, Info))
15107       return false;
15108     P.moveInto(Result);
15109     return true;
15110   } else if (T->isArrayType()) {
15111     LValue LV;
15112     APValue &Value =
15113         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15114     if (!EvaluateArray(E, LV, Value, Info))
15115       return false;
15116     Result = Value;
15117   } else if (T->isRecordType()) {
15118     LValue LV;
15119     APValue &Value =
15120         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15121     if (!EvaluateRecord(E, LV, Value, Info))
15122       return false;
15123     Result = Value;
15124   } else if (T->isVoidType()) {
15125     if (!Info.getLangOpts().CPlusPlus11)
15126       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15127         << E->getType();
15128     if (!EvaluateVoid(E, Info))
15129       return false;
15130   } else if (T->isAtomicType()) {
15131     QualType Unqual = T.getAtomicUnqualifiedType();
15132     if (Unqual->isArrayType() || Unqual->isRecordType()) {
15133       LValue LV;
15134       APValue &Value = Info.CurrentCall->createTemporary(
15135           E, Unqual, ScopeKind::FullExpression, LV);
15136       if (!EvaluateAtomic(E, &LV, Value, Info))
15137         return false;
15138       Result = Value;
15139     } else {
15140       if (!EvaluateAtomic(E, nullptr, Result, Info))
15141         return false;
15142     }
15143   } else if (Info.getLangOpts().CPlusPlus11) {
15144     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15145     return false;
15146   } else {
15147     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15148     return false;
15149   }
15150 
15151   return true;
15152 }
15153 
15154 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15155 /// cases, the in-place evaluation is essential, since later initializers for
15156 /// an object can indirectly refer to subobjects which were initialized earlier.
15157 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15158                             const Expr *E, bool AllowNonLiteralTypes) {
15159   assert(!E->isValueDependent());
15160 
15161   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15162     return false;
15163 
15164   if (E->isPRValue()) {
15165     // Evaluate arrays and record types in-place, so that later initializers can
15166     // refer to earlier-initialized members of the object.
15167     QualType T = E->getType();
15168     if (T->isArrayType())
15169       return EvaluateArray(E, This, Result, Info);
15170     else if (T->isRecordType())
15171       return EvaluateRecord(E, This, Result, Info);
15172     else if (T->isAtomicType()) {
15173       QualType Unqual = T.getAtomicUnqualifiedType();
15174       if (Unqual->isArrayType() || Unqual->isRecordType())
15175         return EvaluateAtomic(E, &This, Result, Info);
15176     }
15177   }
15178 
15179   // For any other type, in-place evaluation is unimportant.
15180   return Evaluate(Result, Info, E);
15181 }
15182 
15183 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15184 /// lvalue-to-rvalue cast if it is an lvalue.
15185 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15186   assert(!E->isValueDependent());
15187 
15188   if (E->getType().isNull())
15189     return false;
15190 
15191   if (!CheckLiteralType(Info, E))
15192     return false;
15193 
15194   if (Info.EnableNewConstInterp) {
15195     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15196       return false;
15197   } else {
15198     if (!::Evaluate(Result, Info, E))
15199       return false;
15200   }
15201 
15202   // Implicit lvalue-to-rvalue cast.
15203   if (E->isGLValue()) {
15204     LValue LV;
15205     LV.setFrom(Info.Ctx, Result);
15206     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15207       return false;
15208   }
15209 
15210   // Check this core constant expression is a constant expression.
15211   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15212                                  ConstantExprKind::Normal) &&
15213          CheckMemoryLeaks(Info);
15214 }
15215 
15216 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15217                                  const ASTContext &Ctx, bool &IsConst) {
15218   // Fast-path evaluations of integer literals, since we sometimes see files
15219   // containing vast quantities of these.
15220   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15221     Result.Val = APValue(APSInt(L->getValue(),
15222                                 L->getType()->isUnsignedIntegerType()));
15223     IsConst = true;
15224     return true;
15225   }
15226 
15227   if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15228     Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15229     IsConst = true;
15230     return true;
15231   }
15232 
15233   // This case should be rare, but we need to check it before we check on
15234   // the type below.
15235   if (Exp->getType().isNull()) {
15236     IsConst = false;
15237     return true;
15238   }
15239 
15240   return false;
15241 }
15242 
15243 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15244                                       Expr::SideEffectsKind SEK) {
15245   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15246          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15247 }
15248 
15249 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15250                              const ASTContext &Ctx, EvalInfo &Info) {
15251   assert(!E->isValueDependent());
15252   bool IsConst;
15253   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15254     return IsConst;
15255 
15256   return EvaluateAsRValue(Info, E, Result.Val);
15257 }
15258 
15259 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15260                           const ASTContext &Ctx,
15261                           Expr::SideEffectsKind AllowSideEffects,
15262                           EvalInfo &Info) {
15263   assert(!E->isValueDependent());
15264   if (!E->getType()->isIntegralOrEnumerationType())
15265     return false;
15266 
15267   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15268       !ExprResult.Val.isInt() ||
15269       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15270     return false;
15271 
15272   return true;
15273 }
15274 
15275 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15276                                  const ASTContext &Ctx,
15277                                  Expr::SideEffectsKind AllowSideEffects,
15278                                  EvalInfo &Info) {
15279   assert(!E->isValueDependent());
15280   if (!E->getType()->isFixedPointType())
15281     return false;
15282 
15283   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15284     return false;
15285 
15286   if (!ExprResult.Val.isFixedPoint() ||
15287       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15288     return false;
15289 
15290   return true;
15291 }
15292 
15293 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
15294 /// any crazy technique (that has nothing to do with language standards) that
15295 /// we want to.  If this function returns true, it returns the folded constant
15296 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15297 /// will be applied to the result.
15298 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15299                             bool InConstantContext) const {
15300   assert(!isValueDependent() &&
15301          "Expression evaluator can't be called on a dependent expression.");
15302   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15303   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15304   Info.InConstantContext = InConstantContext;
15305   return ::EvaluateAsRValue(this, Result, Ctx, Info);
15306 }
15307 
15308 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15309                                       bool InConstantContext) const {
15310   assert(!isValueDependent() &&
15311          "Expression evaluator can't be called on a dependent expression.");
15312   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15313   EvalResult Scratch;
15314   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15315          HandleConversionToBool(Scratch.Val, Result);
15316 }
15317 
15318 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15319                          SideEffectsKind AllowSideEffects,
15320                          bool InConstantContext) const {
15321   assert(!isValueDependent() &&
15322          "Expression evaluator can't be called on a dependent expression.");
15323   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15324   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15325   Info.InConstantContext = InConstantContext;
15326   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15327 }
15328 
15329 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15330                                 SideEffectsKind AllowSideEffects,
15331                                 bool InConstantContext) const {
15332   assert(!isValueDependent() &&
15333          "Expression evaluator can't be called on a dependent expression.");
15334   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15335   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15336   Info.InConstantContext = InConstantContext;
15337   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15338 }
15339 
15340 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15341                            SideEffectsKind AllowSideEffects,
15342                            bool InConstantContext) const {
15343   assert(!isValueDependent() &&
15344          "Expression evaluator can't be called on a dependent expression.");
15345 
15346   if (!getType()->isRealFloatingType())
15347     return false;
15348 
15349   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15350   EvalResult ExprResult;
15351   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15352       !ExprResult.Val.isFloat() ||
15353       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15354     return false;
15355 
15356   Result = ExprResult.Val.getFloat();
15357   return true;
15358 }
15359 
15360 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15361                             bool InConstantContext) const {
15362   assert(!isValueDependent() &&
15363          "Expression evaluator can't be called on a dependent expression.");
15364 
15365   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15366   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15367   Info.InConstantContext = InConstantContext;
15368   LValue LV;
15369   CheckedTemporaries CheckedTemps;
15370   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15371       Result.HasSideEffects ||
15372       !CheckLValueConstantExpression(Info, getExprLoc(),
15373                                      Ctx.getLValueReferenceType(getType()), LV,
15374                                      ConstantExprKind::Normal, CheckedTemps))
15375     return false;
15376 
15377   LV.moveInto(Result.Val);
15378   return true;
15379 }
15380 
15381 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15382                                 APValue DestroyedValue, QualType Type,
15383                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15384                                 bool IsConstantDestruction) {
15385   EvalInfo Info(Ctx, EStatus,
15386                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15387                                       : EvalInfo::EM_ConstantFold);
15388   Info.setEvaluatingDecl(Base, DestroyedValue,
15389                          EvalInfo::EvaluatingDeclKind::Dtor);
15390   Info.InConstantContext = IsConstantDestruction;
15391 
15392   LValue LVal;
15393   LVal.set(Base);
15394 
15395   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15396       EStatus.HasSideEffects)
15397     return false;
15398 
15399   if (!Info.discardCleanups())
15400     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15401 
15402   return true;
15403 }
15404 
15405 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15406                                   ConstantExprKind Kind) const {
15407   assert(!isValueDependent() &&
15408          "Expression evaluator can't be called on a dependent expression.");
15409   bool IsConst;
15410   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
15411     return true;
15412 
15413   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15414   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15415   EvalInfo Info(Ctx, Result, EM);
15416   Info.InConstantContext = true;
15417 
15418   // The type of the object we're initializing is 'const T' for a class NTTP.
15419   QualType T = getType();
15420   if (Kind == ConstantExprKind::ClassTemplateArgument)
15421     T.addConst();
15422 
15423   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15424   // represent the result of the evaluation. CheckConstantExpression ensures
15425   // this doesn't escape.
15426   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15427   APValue::LValueBase Base(&BaseMTE);
15428 
15429   Info.setEvaluatingDecl(Base, Result.Val);
15430   LValue LVal;
15431   LVal.set(Base);
15432 
15433   {
15434     // C++23 [intro.execution]/p5
15435     // A full-expression is [...] a constant-expression
15436     // So we need to make sure temporary objects are destroyed after having
15437     // evaluating the expression (per C++23 [class.temporary]/p4).
15438     FullExpressionRAII Scope(Info);
15439     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
15440         Result.HasSideEffects || !Scope.destroy())
15441       return false;
15442   }
15443 
15444   if (!Info.discardCleanups())
15445     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15446 
15447   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15448                                Result.Val, Kind))
15449     return false;
15450   if (!CheckMemoryLeaks(Info))
15451     return false;
15452 
15453   // If this is a class template argument, it's required to have constant
15454   // destruction too.
15455   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15456       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15457                             true) ||
15458        Result.HasSideEffects)) {
15459     // FIXME: Prefix a note to indicate that the problem is lack of constant
15460     // destruction.
15461     return false;
15462   }
15463 
15464   return true;
15465 }
15466 
15467 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15468                                  const VarDecl *VD,
15469                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15470                                  bool IsConstantInitialization) const {
15471   assert(!isValueDependent() &&
15472          "Expression evaluator can't be called on a dependent expression.");
15473 
15474   llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15475     std::string Name;
15476     llvm::raw_string_ostream OS(Name);
15477     VD->printQualifiedName(OS);
15478     return Name;
15479   });
15480 
15481   Expr::EvalStatus EStatus;
15482   EStatus.Diag = &Notes;
15483 
15484   EvalInfo Info(Ctx, EStatus,
15485                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus)
15486                     ? EvalInfo::EM_ConstantExpression
15487                     : EvalInfo::EM_ConstantFold);
15488   Info.setEvaluatingDecl(VD, Value);
15489   Info.InConstantContext = IsConstantInitialization;
15490 
15491   if (Info.EnableNewConstInterp) {
15492     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15493     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15494       return false;
15495   } else {
15496     LValue LVal;
15497     LVal.set(VD);
15498 
15499     if (!EvaluateInPlace(Value, Info, LVal, this,
15500                          /*AllowNonLiteralTypes=*/true) ||
15501         EStatus.HasSideEffects)
15502       return false;
15503 
15504     // At this point, any lifetime-extended temporaries are completely
15505     // initialized.
15506     Info.performLifetimeExtension();
15507 
15508     if (!Info.discardCleanups())
15509       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15510   }
15511 
15512   SourceLocation DeclLoc = VD->getLocation();
15513   QualType DeclTy = VD->getType();
15514   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15515                                  ConstantExprKind::Normal) &&
15516          CheckMemoryLeaks(Info);
15517 }
15518 
15519 bool VarDecl::evaluateDestruction(
15520     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15521   Expr::EvalStatus EStatus;
15522   EStatus.Diag = &Notes;
15523 
15524   // Only treat the destruction as constant destruction if we formally have
15525   // constant initialization (or are usable in a constant expression).
15526   bool IsConstantDestruction = hasConstantInitialization();
15527 
15528   // Make a copy of the value for the destructor to mutate, if we know it.
15529   // Otherwise, treat the value as default-initialized; if the destructor works
15530   // anyway, then the destruction is constant (and must be essentially empty).
15531   APValue DestroyedValue;
15532   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15533     DestroyedValue = *getEvaluatedValue();
15534   else if (!getDefaultInitValue(getType(), DestroyedValue))
15535     return false;
15536 
15537   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15538                            getType(), getLocation(), EStatus,
15539                            IsConstantDestruction) ||
15540       EStatus.HasSideEffects)
15541     return false;
15542 
15543   ensureEvaluatedStmt()->HasConstantDestruction = true;
15544   return true;
15545 }
15546 
15547 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15548 /// constant folded, but discard the result.
15549 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15550   assert(!isValueDependent() &&
15551          "Expression evaluator can't be called on a dependent expression.");
15552 
15553   EvalResult Result;
15554   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15555          !hasUnacceptableSideEffect(Result, SEK);
15556 }
15557 
15558 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15559                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15560   assert(!isValueDependent() &&
15561          "Expression evaluator can't be called on a dependent expression.");
15562 
15563   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15564   EvalResult EVResult;
15565   EVResult.Diag = Diag;
15566   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15567   Info.InConstantContext = true;
15568 
15569   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15570   (void)Result;
15571   assert(Result && "Could not evaluate expression");
15572   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15573 
15574   return EVResult.Val.getInt();
15575 }
15576 
15577 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15578     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15579   assert(!isValueDependent() &&
15580          "Expression evaluator can't be called on a dependent expression.");
15581 
15582   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15583   EvalResult EVResult;
15584   EVResult.Diag = Diag;
15585   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15586   Info.InConstantContext = true;
15587   Info.CheckingForUndefinedBehavior = true;
15588 
15589   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15590   (void)Result;
15591   assert(Result && "Could not evaluate expression");
15592   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15593 
15594   return EVResult.Val.getInt();
15595 }
15596 
15597 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15598   assert(!isValueDependent() &&
15599          "Expression evaluator can't be called on a dependent expression.");
15600 
15601   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15602   bool IsConst;
15603   EvalResult EVResult;
15604   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15605     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15606     Info.CheckingForUndefinedBehavior = true;
15607     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15608   }
15609 }
15610 
15611 bool Expr::EvalResult::isGlobalLValue() const {
15612   assert(Val.isLValue());
15613   return IsGlobalLValue(Val.getLValueBase());
15614 }
15615 
15616 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15617 /// an integer constant expression.
15618 
15619 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15620 /// comma, etc
15621 
15622 // CheckICE - This function does the fundamental ICE checking: the returned
15623 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15624 // and a (possibly null) SourceLocation indicating the location of the problem.
15625 //
15626 // Note that to reduce code duplication, this helper does no evaluation
15627 // itself; the caller checks whether the expression is evaluatable, and
15628 // in the rare cases where CheckICE actually cares about the evaluated
15629 // value, it calls into Evaluate.
15630 
15631 namespace {
15632 
15633 enum ICEKind {
15634   /// This expression is an ICE.
15635   IK_ICE,
15636   /// This expression is not an ICE, but if it isn't evaluated, it's
15637   /// a legal subexpression for an ICE. This return value is used to handle
15638   /// the comma operator in C99 mode, and non-constant subexpressions.
15639   IK_ICEIfUnevaluated,
15640   /// This expression is not an ICE, and is not a legal subexpression for one.
15641   IK_NotICE
15642 };
15643 
15644 struct ICEDiag {
15645   ICEKind Kind;
15646   SourceLocation Loc;
15647 
15648   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15649 };
15650 
15651 }
15652 
15653 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15654 
15655 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15656 
15657 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15658   Expr::EvalResult EVResult;
15659   Expr::EvalStatus Status;
15660   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15661 
15662   Info.InConstantContext = true;
15663   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15664       !EVResult.Val.isInt())
15665     return ICEDiag(IK_NotICE, E->getBeginLoc());
15666 
15667   return NoDiag();
15668 }
15669 
15670 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15671   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15672   if (!E->getType()->isIntegralOrEnumerationType())
15673     return ICEDiag(IK_NotICE, E->getBeginLoc());
15674 
15675   switch (E->getStmtClass()) {
15676 #define ABSTRACT_STMT(Node)
15677 #define STMT(Node, Base) case Expr::Node##Class:
15678 #define EXPR(Node, Base)
15679 #include "clang/AST/StmtNodes.inc"
15680   case Expr::PredefinedExprClass:
15681   case Expr::FloatingLiteralClass:
15682   case Expr::ImaginaryLiteralClass:
15683   case Expr::StringLiteralClass:
15684   case Expr::ArraySubscriptExprClass:
15685   case Expr::MatrixSubscriptExprClass:
15686   case Expr::OMPArraySectionExprClass:
15687   case Expr::OMPArrayShapingExprClass:
15688   case Expr::OMPIteratorExprClass:
15689   case Expr::MemberExprClass:
15690   case Expr::CompoundAssignOperatorClass:
15691   case Expr::CompoundLiteralExprClass:
15692   case Expr::ExtVectorElementExprClass:
15693   case Expr::DesignatedInitExprClass:
15694   case Expr::ArrayInitLoopExprClass:
15695   case Expr::ArrayInitIndexExprClass:
15696   case Expr::NoInitExprClass:
15697   case Expr::DesignatedInitUpdateExprClass:
15698   case Expr::ImplicitValueInitExprClass:
15699   case Expr::ParenListExprClass:
15700   case Expr::VAArgExprClass:
15701   case Expr::AddrLabelExprClass:
15702   case Expr::StmtExprClass:
15703   case Expr::CXXMemberCallExprClass:
15704   case Expr::CUDAKernelCallExprClass:
15705   case Expr::CXXAddrspaceCastExprClass:
15706   case Expr::CXXDynamicCastExprClass:
15707   case Expr::CXXTypeidExprClass:
15708   case Expr::CXXUuidofExprClass:
15709   case Expr::MSPropertyRefExprClass:
15710   case Expr::MSPropertySubscriptExprClass:
15711   case Expr::CXXNullPtrLiteralExprClass:
15712   case Expr::UserDefinedLiteralClass:
15713   case Expr::CXXThisExprClass:
15714   case Expr::CXXThrowExprClass:
15715   case Expr::CXXNewExprClass:
15716   case Expr::CXXDeleteExprClass:
15717   case Expr::CXXPseudoDestructorExprClass:
15718   case Expr::UnresolvedLookupExprClass:
15719   case Expr::TypoExprClass:
15720   case Expr::RecoveryExprClass:
15721   case Expr::DependentScopeDeclRefExprClass:
15722   case Expr::CXXConstructExprClass:
15723   case Expr::CXXInheritedCtorInitExprClass:
15724   case Expr::CXXStdInitializerListExprClass:
15725   case Expr::CXXBindTemporaryExprClass:
15726   case Expr::ExprWithCleanupsClass:
15727   case Expr::CXXTemporaryObjectExprClass:
15728   case Expr::CXXUnresolvedConstructExprClass:
15729   case Expr::CXXDependentScopeMemberExprClass:
15730   case Expr::UnresolvedMemberExprClass:
15731   case Expr::ObjCStringLiteralClass:
15732   case Expr::ObjCBoxedExprClass:
15733   case Expr::ObjCArrayLiteralClass:
15734   case Expr::ObjCDictionaryLiteralClass:
15735   case Expr::ObjCEncodeExprClass:
15736   case Expr::ObjCMessageExprClass:
15737   case Expr::ObjCSelectorExprClass:
15738   case Expr::ObjCProtocolExprClass:
15739   case Expr::ObjCIvarRefExprClass:
15740   case Expr::ObjCPropertyRefExprClass:
15741   case Expr::ObjCSubscriptRefExprClass:
15742   case Expr::ObjCIsaExprClass:
15743   case Expr::ObjCAvailabilityCheckExprClass:
15744   case Expr::ShuffleVectorExprClass:
15745   case Expr::ConvertVectorExprClass:
15746   case Expr::BlockExprClass:
15747   case Expr::NoStmtClass:
15748   case Expr::OpaqueValueExprClass:
15749   case Expr::PackExpansionExprClass:
15750   case Expr::SubstNonTypeTemplateParmPackExprClass:
15751   case Expr::FunctionParmPackExprClass:
15752   case Expr::AsTypeExprClass:
15753   case Expr::ObjCIndirectCopyRestoreExprClass:
15754   case Expr::MaterializeTemporaryExprClass:
15755   case Expr::PseudoObjectExprClass:
15756   case Expr::AtomicExprClass:
15757   case Expr::LambdaExprClass:
15758   case Expr::CXXFoldExprClass:
15759   case Expr::CoawaitExprClass:
15760   case Expr::DependentCoawaitExprClass:
15761   case Expr::CoyieldExprClass:
15762   case Expr::SYCLUniqueStableNameExprClass:
15763   case Expr::CXXParenListInitExprClass:
15764     return ICEDiag(IK_NotICE, E->getBeginLoc());
15765 
15766   case Expr::InitListExprClass: {
15767     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15768     // form "T x = { a };" is equivalent to "T x = a;".
15769     // Unless we're initializing a reference, T is a scalar as it is known to be
15770     // of integral or enumeration type.
15771     if (E->isPRValue())
15772       if (cast<InitListExpr>(E)->getNumInits() == 1)
15773         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15774     return ICEDiag(IK_NotICE, E->getBeginLoc());
15775   }
15776 
15777   case Expr::SizeOfPackExprClass:
15778   case Expr::GNUNullExprClass:
15779   case Expr::SourceLocExprClass:
15780     return NoDiag();
15781 
15782   case Expr::SubstNonTypeTemplateParmExprClass:
15783     return
15784       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15785 
15786   case Expr::ConstantExprClass:
15787     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15788 
15789   case Expr::ParenExprClass:
15790     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15791   case Expr::GenericSelectionExprClass:
15792     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15793   case Expr::IntegerLiteralClass:
15794   case Expr::FixedPointLiteralClass:
15795   case Expr::CharacterLiteralClass:
15796   case Expr::ObjCBoolLiteralExprClass:
15797   case Expr::CXXBoolLiteralExprClass:
15798   case Expr::CXXScalarValueInitExprClass:
15799   case Expr::TypeTraitExprClass:
15800   case Expr::ConceptSpecializationExprClass:
15801   case Expr::RequiresExprClass:
15802   case Expr::ArrayTypeTraitExprClass:
15803   case Expr::ExpressionTraitExprClass:
15804   case Expr::CXXNoexceptExprClass:
15805     return NoDiag();
15806   case Expr::CallExprClass:
15807   case Expr::CXXOperatorCallExprClass: {
15808     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15809     // constant expressions, but they can never be ICEs because an ICE cannot
15810     // contain an operand of (pointer to) function type.
15811     const CallExpr *CE = cast<CallExpr>(E);
15812     if (CE->getBuiltinCallee())
15813       return CheckEvalInICE(E, Ctx);
15814     return ICEDiag(IK_NotICE, E->getBeginLoc());
15815   }
15816   case Expr::CXXRewrittenBinaryOperatorClass:
15817     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15818                     Ctx);
15819   case Expr::DeclRefExprClass: {
15820     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15821     if (isa<EnumConstantDecl>(D))
15822       return NoDiag();
15823 
15824     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15825     // integer variables in constant expressions:
15826     //
15827     // C++ 7.1.5.1p2
15828     //   A variable of non-volatile const-qualified integral or enumeration
15829     //   type initialized by an ICE can be used in ICEs.
15830     //
15831     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15832     // that mode, use of reference variables should not be allowed.
15833     const VarDecl *VD = dyn_cast<VarDecl>(D);
15834     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15835         !VD->getType()->isReferenceType())
15836       return NoDiag();
15837 
15838     return ICEDiag(IK_NotICE, E->getBeginLoc());
15839   }
15840   case Expr::UnaryOperatorClass: {
15841     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15842     switch (Exp->getOpcode()) {
15843     case UO_PostInc:
15844     case UO_PostDec:
15845     case UO_PreInc:
15846     case UO_PreDec:
15847     case UO_AddrOf:
15848     case UO_Deref:
15849     case UO_Coawait:
15850       // C99 6.6/3 allows increment and decrement within unevaluated
15851       // subexpressions of constant expressions, but they can never be ICEs
15852       // because an ICE cannot contain an lvalue operand.
15853       return ICEDiag(IK_NotICE, E->getBeginLoc());
15854     case UO_Extension:
15855     case UO_LNot:
15856     case UO_Plus:
15857     case UO_Minus:
15858     case UO_Not:
15859     case UO_Real:
15860     case UO_Imag:
15861       return CheckICE(Exp->getSubExpr(), Ctx);
15862     }
15863     llvm_unreachable("invalid unary operator class");
15864   }
15865   case Expr::OffsetOfExprClass: {
15866     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15867     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15868     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15869     // compliance: we should warn earlier for offsetof expressions with
15870     // array subscripts that aren't ICEs, and if the array subscripts
15871     // are ICEs, the value of the offsetof must be an integer constant.
15872     return CheckEvalInICE(E, Ctx);
15873   }
15874   case Expr::UnaryExprOrTypeTraitExprClass: {
15875     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15876     if ((Exp->getKind() ==  UETT_SizeOf) &&
15877         Exp->getTypeOfArgument()->isVariableArrayType())
15878       return ICEDiag(IK_NotICE, E->getBeginLoc());
15879     return NoDiag();
15880   }
15881   case Expr::BinaryOperatorClass: {
15882     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15883     switch (Exp->getOpcode()) {
15884     case BO_PtrMemD:
15885     case BO_PtrMemI:
15886     case BO_Assign:
15887     case BO_MulAssign:
15888     case BO_DivAssign:
15889     case BO_RemAssign:
15890     case BO_AddAssign:
15891     case BO_SubAssign:
15892     case BO_ShlAssign:
15893     case BO_ShrAssign:
15894     case BO_AndAssign:
15895     case BO_XorAssign:
15896     case BO_OrAssign:
15897       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15898       // constant expressions, but they can never be ICEs because an ICE cannot
15899       // contain an lvalue operand.
15900       return ICEDiag(IK_NotICE, E->getBeginLoc());
15901 
15902     case BO_Mul:
15903     case BO_Div:
15904     case BO_Rem:
15905     case BO_Add:
15906     case BO_Sub:
15907     case BO_Shl:
15908     case BO_Shr:
15909     case BO_LT:
15910     case BO_GT:
15911     case BO_LE:
15912     case BO_GE:
15913     case BO_EQ:
15914     case BO_NE:
15915     case BO_And:
15916     case BO_Xor:
15917     case BO_Or:
15918     case BO_Comma:
15919     case BO_Cmp: {
15920       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15921       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15922       if (Exp->getOpcode() == BO_Div ||
15923           Exp->getOpcode() == BO_Rem) {
15924         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15925         // we don't evaluate one.
15926         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15927           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15928           if (REval == 0)
15929             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15930           if (REval.isSigned() && REval.isAllOnes()) {
15931             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15932             if (LEval.isMinSignedValue())
15933               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15934           }
15935         }
15936       }
15937       if (Exp->getOpcode() == BO_Comma) {
15938         if (Ctx.getLangOpts().C99) {
15939           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15940           // if it isn't evaluated.
15941           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15942             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15943         } else {
15944           // In both C89 and C++, commas in ICEs are illegal.
15945           return ICEDiag(IK_NotICE, E->getBeginLoc());
15946         }
15947       }
15948       return Worst(LHSResult, RHSResult);
15949     }
15950     case BO_LAnd:
15951     case BO_LOr: {
15952       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15953       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15954       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15955         // Rare case where the RHS has a comma "side-effect"; we need
15956         // to actually check the condition to see whether the side
15957         // with the comma is evaluated.
15958         if ((Exp->getOpcode() == BO_LAnd) !=
15959             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15960           return RHSResult;
15961         return NoDiag();
15962       }
15963 
15964       return Worst(LHSResult, RHSResult);
15965     }
15966     }
15967     llvm_unreachable("invalid binary operator kind");
15968   }
15969   case Expr::ImplicitCastExprClass:
15970   case Expr::CStyleCastExprClass:
15971   case Expr::CXXFunctionalCastExprClass:
15972   case Expr::CXXStaticCastExprClass:
15973   case Expr::CXXReinterpretCastExprClass:
15974   case Expr::CXXConstCastExprClass:
15975   case Expr::ObjCBridgedCastExprClass: {
15976     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15977     if (isa<ExplicitCastExpr>(E)) {
15978       if (const FloatingLiteral *FL
15979             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15980         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15981         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15982         APSInt IgnoredVal(DestWidth, !DestSigned);
15983         bool Ignored;
15984         // If the value does not fit in the destination type, the behavior is
15985         // undefined, so we are not required to treat it as a constant
15986         // expression.
15987         if (FL->getValue().convertToInteger(IgnoredVal,
15988                                             llvm::APFloat::rmTowardZero,
15989                                             &Ignored) & APFloat::opInvalidOp)
15990           return ICEDiag(IK_NotICE, E->getBeginLoc());
15991         return NoDiag();
15992       }
15993     }
15994     switch (cast<CastExpr>(E)->getCastKind()) {
15995     case CK_LValueToRValue:
15996     case CK_AtomicToNonAtomic:
15997     case CK_NonAtomicToAtomic:
15998     case CK_NoOp:
15999     case CK_IntegralToBoolean:
16000     case CK_IntegralCast:
16001       return CheckICE(SubExpr, Ctx);
16002     default:
16003       return ICEDiag(IK_NotICE, E->getBeginLoc());
16004     }
16005   }
16006   case Expr::BinaryConditionalOperatorClass: {
16007     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
16008     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
16009     if (CommonResult.Kind == IK_NotICE) return CommonResult;
16010     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16011     if (FalseResult.Kind == IK_NotICE) return FalseResult;
16012     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
16013     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
16014         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
16015     return FalseResult;
16016   }
16017   case Expr::ConditionalOperatorClass: {
16018     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
16019     // If the condition (ignoring parens) is a __builtin_constant_p call,
16020     // then only the true side is actually considered in an integer constant
16021     // expression, and it is fully evaluated.  This is an important GNU
16022     // extension.  See GCC PR38377 for discussion.
16023     if (const CallExpr *CallCE
16024         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
16025       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16026         return CheckEvalInICE(E, Ctx);
16027     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
16028     if (CondResult.Kind == IK_NotICE)
16029       return CondResult;
16030 
16031     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
16032     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16033 
16034     if (TrueResult.Kind == IK_NotICE)
16035       return TrueResult;
16036     if (FalseResult.Kind == IK_NotICE)
16037       return FalseResult;
16038     if (CondResult.Kind == IK_ICEIfUnevaluated)
16039       return CondResult;
16040     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
16041       return NoDiag();
16042     // Rare case where the diagnostics depend on which side is evaluated
16043     // Note that if we get here, CondResult is 0, and at least one of
16044     // TrueResult and FalseResult is non-zero.
16045     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16046       return FalseResult;
16047     return TrueResult;
16048   }
16049   case Expr::CXXDefaultArgExprClass:
16050     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
16051   case Expr::CXXDefaultInitExprClass:
16052     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
16053   case Expr::ChooseExprClass: {
16054     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
16055   }
16056   case Expr::BuiltinBitCastExprClass: {
16057     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
16058       return ICEDiag(IK_NotICE, E->getBeginLoc());
16059     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
16060   }
16061   }
16062 
16063   llvm_unreachable("Invalid StmtClass!");
16064 }
16065 
16066 /// Evaluate an expression as a C++11 integral constant expression.
16067 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
16068                                                     const Expr *E,
16069                                                     llvm::APSInt *Value,
16070                                                     SourceLocation *Loc) {
16071   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16072     if (Loc) *Loc = E->getExprLoc();
16073     return false;
16074   }
16075 
16076   APValue Result;
16077   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16078     return false;
16079 
16080   if (!Result.isInt()) {
16081     if (Loc) *Loc = E->getExprLoc();
16082     return false;
16083   }
16084 
16085   if (Value) *Value = Result.getInt();
16086   return true;
16087 }
16088 
16089 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
16090                                  SourceLocation *Loc) const {
16091   assert(!isValueDependent() &&
16092          "Expression evaluator can't be called on a dependent expression.");
16093 
16094   ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16095 
16096   if (Ctx.getLangOpts().CPlusPlus11)
16097     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16098 
16099   ICEDiag D = CheckICE(this, Ctx);
16100   if (D.Kind != IK_ICE) {
16101     if (Loc) *Loc = D.Loc;
16102     return false;
16103   }
16104   return true;
16105 }
16106 
16107 std::optional<llvm::APSInt>
16108 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc,
16109                              bool isEvaluated) const {
16110   if (isValueDependent()) {
16111     // Expression evaluator can't succeed on a dependent expression.
16112     return std::nullopt;
16113   }
16114 
16115   APSInt Value;
16116 
16117   if (Ctx.getLangOpts().CPlusPlus11) {
16118     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
16119       return Value;
16120     return std::nullopt;
16121   }
16122 
16123   if (!isIntegerConstantExpr(Ctx, Loc))
16124     return std::nullopt;
16125 
16126   // The only possible side-effects here are due to UB discovered in the
16127   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16128   // required to treat the expression as an ICE, so we produce the folded
16129   // value.
16130   EvalResult ExprResult;
16131   Expr::EvalStatus Status;
16132   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16133   Info.InConstantContext = true;
16134 
16135   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16136     llvm_unreachable("ICE cannot be evaluated!");
16137 
16138   return ExprResult.Val.getInt();
16139 }
16140 
16141 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16142   assert(!isValueDependent() &&
16143          "Expression evaluator can't be called on a dependent expression.");
16144 
16145   return CheckICE(this, Ctx).Kind == IK_ICE;
16146 }
16147 
16148 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16149                                SourceLocation *Loc) const {
16150   assert(!isValueDependent() &&
16151          "Expression evaluator can't be called on a dependent expression.");
16152 
16153   // We support this checking in C++98 mode in order to diagnose compatibility
16154   // issues.
16155   assert(Ctx.getLangOpts().CPlusPlus);
16156 
16157   // Build evaluation settings.
16158   Expr::EvalStatus Status;
16159   SmallVector<PartialDiagnosticAt, 8> Diags;
16160   Status.Diag = &Diags;
16161   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16162 
16163   APValue Scratch;
16164   bool IsConstExpr =
16165       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16166       // FIXME: We don't produce a diagnostic for this, but the callers that
16167       // call us on arbitrary full-expressions should generally not care.
16168       Info.discardCleanups() && !Status.HasSideEffects;
16169 
16170   if (!Diags.empty()) {
16171     IsConstExpr = false;
16172     if (Loc) *Loc = Diags[0].first;
16173   } else if (!IsConstExpr) {
16174     // FIXME: This shouldn't happen.
16175     if (Loc) *Loc = getExprLoc();
16176   }
16177 
16178   return IsConstExpr;
16179 }
16180 
16181 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16182                                     const FunctionDecl *Callee,
16183                                     ArrayRef<const Expr*> Args,
16184                                     const Expr *This) const {
16185   assert(!isValueDependent() &&
16186          "Expression evaluator can't be called on a dependent expression.");
16187 
16188   llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16189     std::string Name;
16190     llvm::raw_string_ostream OS(Name);
16191     Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16192                                  /*Qualified=*/true);
16193     return Name;
16194   });
16195 
16196   Expr::EvalStatus Status;
16197   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16198   Info.InConstantContext = true;
16199 
16200   LValue ThisVal;
16201   const LValue *ThisPtr = nullptr;
16202   if (This) {
16203 #ifndef NDEBUG
16204     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16205     assert(MD && "Don't provide `this` for non-methods.");
16206     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
16207 #endif
16208     if (!This->isValueDependent() &&
16209         EvaluateObjectArgument(Info, This, ThisVal) &&
16210         !Info.EvalStatus.HasSideEffects)
16211       ThisPtr = &ThisVal;
16212 
16213     // Ignore any side-effects from a failed evaluation. This is safe because
16214     // they can't interfere with any other argument evaluation.
16215     Info.EvalStatus.HasSideEffects = false;
16216   }
16217 
16218   CallRef Call = Info.CurrentCall->createCall(Callee);
16219   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16220        I != E; ++I) {
16221     unsigned Idx = I - Args.begin();
16222     if (Idx >= Callee->getNumParams())
16223       break;
16224     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16225     if ((*I)->isValueDependent() ||
16226         !EvaluateCallArg(PVD, *I, Call, Info) ||
16227         Info.EvalStatus.HasSideEffects) {
16228       // If evaluation fails, throw away the argument entirely.
16229       if (APValue *Slot = Info.getParamSlot(Call, PVD))
16230         *Slot = APValue();
16231     }
16232 
16233     // Ignore any side-effects from a failed evaluation. This is safe because
16234     // they can't interfere with any other argument evaluation.
16235     Info.EvalStatus.HasSideEffects = false;
16236   }
16237 
16238   // Parameter cleanups happen in the caller and are not part of this
16239   // evaluation.
16240   Info.discardCleanups();
16241   Info.EvalStatus.HasSideEffects = false;
16242 
16243   // Build fake call to Callee.
16244   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
16245                        Call);
16246   // FIXME: Missing ExprWithCleanups in enable_if conditions?
16247   FullExpressionRAII Scope(Info);
16248   return Evaluate(Value, Info, this) && Scope.destroy() &&
16249          !Info.EvalStatus.HasSideEffects;
16250 }
16251 
16252 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16253                                    SmallVectorImpl<
16254                                      PartialDiagnosticAt> &Diags) {
16255   // FIXME: It would be useful to check constexpr function templates, but at the
16256   // moment the constant expression evaluator cannot cope with the non-rigorous
16257   // ASTs which we build for dependent expressions.
16258   if (FD->isDependentContext())
16259     return true;
16260 
16261   llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16262     std::string Name;
16263     llvm::raw_string_ostream OS(Name);
16264     FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16265                              /*Qualified=*/true);
16266     return Name;
16267   });
16268 
16269   Expr::EvalStatus Status;
16270   Status.Diag = &Diags;
16271 
16272   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16273   Info.InConstantContext = true;
16274   Info.CheckingPotentialConstantExpression = true;
16275 
16276   // The constexpr VM attempts to compile all methods to bytecode here.
16277   if (Info.EnableNewConstInterp) {
16278     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16279     return Diags.empty();
16280   }
16281 
16282   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16283   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16284 
16285   // Fabricate an arbitrary expression on the stack and pretend that it
16286   // is a temporary being used as the 'this' pointer.
16287   LValue This;
16288   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16289   This.set({&VIE, Info.CurrentCall->Index});
16290 
16291   ArrayRef<const Expr*> Args;
16292 
16293   APValue Scratch;
16294   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16295     // Evaluate the call as a constant initializer, to allow the construction
16296     // of objects of non-literal types.
16297     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16298     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16299   } else {
16300     SourceLocation Loc = FD->getLocation();
16301     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
16302                        &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
16303                        /*ResultSlot=*/nullptr);
16304   }
16305 
16306   return Diags.empty();
16307 }
16308 
16309 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16310                                               const FunctionDecl *FD,
16311                                               SmallVectorImpl<
16312                                                 PartialDiagnosticAt> &Diags) {
16313   assert(!E->isValueDependent() &&
16314          "Expression evaluator can't be called on a dependent expression.");
16315 
16316   Expr::EvalStatus Status;
16317   Status.Diag = &Diags;
16318 
16319   EvalInfo Info(FD->getASTContext(), Status,
16320                 EvalInfo::EM_ConstantExpressionUnevaluated);
16321   Info.InConstantContext = true;
16322   Info.CheckingPotentialConstantExpression = true;
16323 
16324   // Fabricate a call stack frame to give the arguments a plausible cover story.
16325   CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
16326                        /*CallExpr=*/nullptr, CallRef());
16327 
16328   APValue ResultScratch;
16329   Evaluate(ResultScratch, Info, E);
16330   return Diags.empty();
16331 }
16332 
16333 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16334                                  unsigned Type) const {
16335   if (!getType()->isPointerType())
16336     return false;
16337 
16338   Expr::EvalStatus Status;
16339   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16340   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16341 }
16342 
16343 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16344                                   EvalInfo &Info) {
16345   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16346     return false;
16347 
16348   LValue String;
16349 
16350   if (!EvaluatePointer(E, String, Info))
16351     return false;
16352 
16353   QualType CharTy = E->getType()->getPointeeType();
16354 
16355   // Fast path: if it's a string literal, search the string value.
16356   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16357           String.getLValueBase().dyn_cast<const Expr *>())) {
16358     StringRef Str = S->getBytes();
16359     int64_t Off = String.Offset.getQuantity();
16360     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16361         S->getCharByteWidth() == 1 &&
16362         // FIXME: Add fast-path for wchar_t too.
16363         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16364       Str = Str.substr(Off);
16365 
16366       StringRef::size_type Pos = Str.find(0);
16367       if (Pos != StringRef::npos)
16368         Str = Str.substr(0, Pos);
16369 
16370       Result = Str.size();
16371       return true;
16372     }
16373 
16374     // Fall through to slow path.
16375   }
16376 
16377   // Slow path: scan the bytes of the string looking for the terminating 0.
16378   for (uint64_t Strlen = 0; /**/; ++Strlen) {
16379     APValue Char;
16380     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16381         !Char.isInt())
16382       return false;
16383     if (!Char.getInt()) {
16384       Result = Strlen;
16385       return true;
16386     }
16387     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16388       return false;
16389   }
16390 }
16391 
16392 bool Expr::EvaluateCharRangeAsString(std::string &Result,
16393                                      const Expr *SizeExpression,
16394                                      const Expr *PtrExpression, ASTContext &Ctx,
16395                                      EvalResult &Status) const {
16396   LValue String;
16397   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16398   Info.InConstantContext = true;
16399 
16400   FullExpressionRAII Scope(Info);
16401   APSInt SizeValue;
16402   if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
16403     return false;
16404 
16405   int64_t Size = SizeValue.getExtValue();
16406 
16407   if (!::EvaluatePointer(PtrExpression, String, Info))
16408     return false;
16409 
16410   QualType CharTy = PtrExpression->getType()->getPointeeType();
16411   for (int64_t I = 0; I < Size; ++I) {
16412     APValue Char;
16413     if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
16414                                         Char))
16415       return false;
16416 
16417     APSInt C = Char.getInt();
16418     Result.push_back(static_cast<char>(C.getExtValue()));
16419     if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
16420       return false;
16421   }
16422   if (!Scope.destroy())
16423     return false;
16424 
16425   if (!CheckMemoryLeaks(Info))
16426     return false;
16427 
16428   return true;
16429 }
16430 
16431 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16432   Expr::EvalStatus Status;
16433   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16434   return EvaluateBuiltinStrLen(this, Result, Info);
16435 }
16436