xref: /llvm-project/clang/lib/AST/ExprConstant.cpp (revision abc8812df02599fc413d9ed77b992f8236ed2af9)
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 "ByteCode/Context.h"
36 #include "ByteCode/Frame.h"
37 #include "ByteCode/State.h"
38 #include "ExprConstShared.h"
39 #include "clang/AST/APValue.h"
40 #include "clang/AST/ASTContext.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/TargetBuiltins.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "llvm/ADT/APFixedPoint.h"
57 #include "llvm/ADT/Sequence.h"
58 #include "llvm/ADT/SmallBitVector.h"
59 #include "llvm/ADT/StringExtras.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/SaveAndRestore.h"
63 #include "llvm/Support/SipHash.h"
64 #include "llvm/Support/TimeProfiler.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include <cstring>
67 #include <functional>
68 #include <optional>
69 
70 #define DEBUG_TYPE "exprconstant"
71 
72 using namespace clang;
73 using llvm::APFixedPoint;
74 using llvm::APInt;
75 using llvm::APSInt;
76 using llvm::APFloat;
77 using llvm::FixedPointSemantics;
78 
79 namespace {
80   struct LValue;
81   class CallStackFrame;
82   class EvalInfo;
83 
84   using SourceLocExprScopeGuard =
85       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
86 
87   static QualType getType(APValue::LValueBase B) {
88     return B.getType();
89   }
90 
91   /// Get an LValue path entry, which is known to not be an array index, as a
92   /// field declaration.
93   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
94     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
95   }
96   /// Get an LValue path entry, which is known to not be an array index, as a
97   /// base class declaration.
98   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
99     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
100   }
101   /// Determine whether this LValue path entry for a base class names a virtual
102   /// base class.
103   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
104     return E.getAsBaseOrMember().getInt();
105   }
106 
107   /// Given an expression, determine the type used to store the result of
108   /// evaluating that expression.
109   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
110     if (E->isPRValue())
111       return E->getType();
112     return Ctx.getLValueReferenceType(E->getType());
113   }
114 
115   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
116   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
117     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
118       return DirectCallee->getAttr<AllocSizeAttr>();
119     if (const Decl *IndirectCallee = CE->getCalleeDecl())
120       return IndirectCallee->getAttr<AllocSizeAttr>();
121     return nullptr;
122   }
123 
124   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125   /// This will look through a single cast.
126   ///
127   /// Returns null if we couldn't unwrap a function with alloc_size.
128   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129     if (!E->getType()->isPointerType())
130       return nullptr;
131 
132     E = E->IgnoreParens();
133     // If we're doing a variable assignment from e.g. malloc(N), there will
134     // probably be a cast of some kind. In exotic cases, we might also see a
135     // top-level ExprWithCleanups. Ignore them either way.
136     if (const auto *FE = dyn_cast<FullExpr>(E))
137       E = FE->getSubExpr()->IgnoreParens();
138 
139     if (const auto *Cast = dyn_cast<CastExpr>(E))
140       E = Cast->getSubExpr()->IgnoreParens();
141 
142     if (const auto *CE = dyn_cast<CallExpr>(E))
143       return getAllocSizeAttr(CE) ? CE : nullptr;
144     return nullptr;
145   }
146 
147   /// Determines whether or not the given Base contains a call to a function
148   /// with the alloc_size attribute.
149   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
150     const auto *E = Base.dyn_cast<const Expr *>();
151     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
152   }
153 
154   /// Determines whether the given kind of constant expression is only ever
155   /// used for name mangling. If so, it's permitted to reference things that we
156   /// can't generate code for (in particular, dllimported functions).
157   static bool isForManglingOnly(ConstantExprKind Kind) {
158     switch (Kind) {
159     case ConstantExprKind::Normal:
160     case ConstantExprKind::ClassTemplateArgument:
161     case ConstantExprKind::ImmediateInvocation:
162       // Note that non-type template arguments of class type are emitted as
163       // template parameter objects.
164       return false;
165 
166     case ConstantExprKind::NonClassTemplateArgument:
167       return true;
168     }
169     llvm_unreachable("unknown ConstantExprKind");
170   }
171 
172   static bool isTemplateArgument(ConstantExprKind Kind) {
173     switch (Kind) {
174     case ConstantExprKind::Normal:
175     case ConstantExprKind::ImmediateInvocation:
176       return false;
177 
178     case ConstantExprKind::ClassTemplateArgument:
179     case ConstantExprKind::NonClassTemplateArgument:
180       return true;
181     }
182     llvm_unreachable("unknown ConstantExprKind");
183   }
184 
185   /// The bound to claim that an array of unknown bound has.
186   /// The value in MostDerivedArraySize is undefined in this case. So, set it
187   /// to an arbitrary value that's likely to loudly break things if it's used.
188   static const uint64_t AssumedSizeForUnsizedArray =
189       std::numeric_limits<uint64_t>::max() / 2;
190 
191   /// Determines if an LValue with the given LValueBase will have an unsized
192   /// array in its designator.
193   /// Find the path length and type of the most-derived subobject in the given
194   /// path, and find the size of the containing array, if any.
195   static unsigned
196   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
197                            ArrayRef<APValue::LValuePathEntry> Path,
198                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
199                            bool &FirstEntryIsUnsizedArray) {
200     // This only accepts LValueBases from APValues, and APValues don't support
201     // arrays that lack size info.
202     assert(!isBaseAnAllocSizeCall(Base) &&
203            "Unsized arrays shouldn't appear here");
204     unsigned MostDerivedLength = 0;
205     Type = getType(Base);
206 
207     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
208       if (Type->isArrayType()) {
209         const ArrayType *AT = Ctx.getAsArrayType(Type);
210         Type = AT->getElementType();
211         MostDerivedLength = I + 1;
212         IsArray = true;
213 
214         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
215           ArraySize = CAT->getZExtSize();
216         } else {
217           assert(I == 0 && "unexpected unsized array designator");
218           FirstEntryIsUnsizedArray = true;
219           ArraySize = AssumedSizeForUnsizedArray;
220         }
221       } else if (Type->isAnyComplexType()) {
222         const ComplexType *CT = Type->castAs<ComplexType>();
223         Type = CT->getElementType();
224         ArraySize = 2;
225         MostDerivedLength = I + 1;
226         IsArray = true;
227       } else if (const auto *VT = Type->getAs<VectorType>()) {
228         Type = VT->getElementType();
229         ArraySize = VT->getNumElements();
230         MostDerivedLength = I + 1;
231         IsArray = true;
232       } else if (const FieldDecl *FD = getAsField(Path[I])) {
233         Type = FD->getType();
234         ArraySize = 0;
235         MostDerivedLength = I + 1;
236         IsArray = false;
237       } else {
238         // Path[I] describes a base class.
239         ArraySize = 0;
240         IsArray = false;
241       }
242     }
243     return MostDerivedLength;
244   }
245 
246   /// A path from a glvalue to a subobject of that glvalue.
247   struct SubobjectDesignator {
248     /// True if the subobject was named in a manner not supported by C++11. Such
249     /// lvalues can still be folded, but they are not core constant expressions
250     /// and we cannot perform lvalue-to-rvalue conversions on them.
251     LLVM_PREFERRED_TYPE(bool)
252     unsigned Invalid : 1;
253 
254     /// Is this a pointer one past the end of an object?
255     LLVM_PREFERRED_TYPE(bool)
256     unsigned IsOnePastTheEnd : 1;
257 
258     /// Indicator of whether the first entry is an unsized array.
259     LLVM_PREFERRED_TYPE(bool)
260     unsigned FirstEntryIsAnUnsizedArray : 1;
261 
262     /// Indicator of whether the most-derived object is an array element.
263     LLVM_PREFERRED_TYPE(bool)
264     unsigned MostDerivedIsArrayElement : 1;
265 
266     /// The length of the path to the most-derived object of which this is a
267     /// subobject.
268     unsigned MostDerivedPathLength : 28;
269 
270     /// The size of the array of which the most-derived object is an element.
271     /// This will always be 0 if the most-derived object is not an array
272     /// element. 0 is not an indicator of whether or not the most-derived object
273     /// is an array, however, because 0-length arrays are allowed.
274     ///
275     /// If the current array is an unsized array, the value of this is
276     /// undefined.
277     uint64_t MostDerivedArraySize;
278     /// The type of the most derived object referred to by this address.
279     QualType MostDerivedType;
280 
281     typedef APValue::LValuePathEntry PathEntry;
282 
283     /// The entries on the path from the glvalue to the designated subobject.
284     SmallVector<PathEntry, 8> Entries;
285 
286     SubobjectDesignator() : Invalid(true) {}
287 
288     explicit SubobjectDesignator(QualType T)
289         : Invalid(false), IsOnePastTheEnd(false),
290           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
291           MostDerivedPathLength(0), MostDerivedArraySize(0),
292           MostDerivedType(T) {}
293 
294     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
295         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
296           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
297           MostDerivedPathLength(0), MostDerivedArraySize(0) {
298       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
299       if (!Invalid) {
300         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
301         ArrayRef<PathEntry> VEntries = V.getLValuePath();
302         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
303         if (V.getLValueBase()) {
304           bool IsArray = false;
305           bool FirstIsUnsizedArray = false;
306           MostDerivedPathLength = findMostDerivedSubobject(
307               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
308               MostDerivedType, IsArray, FirstIsUnsizedArray);
309           MostDerivedIsArrayElement = IsArray;
310           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
311         }
312       }
313     }
314 
315     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
316                   unsigned NewLength) {
317       if (Invalid)
318         return;
319 
320       assert(Base && "cannot truncate path for null pointer");
321       assert(NewLength <= Entries.size() && "not a truncation");
322 
323       if (NewLength == Entries.size())
324         return;
325       Entries.resize(NewLength);
326 
327       bool IsArray = false;
328       bool FirstIsUnsizedArray = false;
329       MostDerivedPathLength = findMostDerivedSubobject(
330           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
331           FirstIsUnsizedArray);
332       MostDerivedIsArrayElement = IsArray;
333       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
334     }
335 
336     void setInvalid() {
337       Invalid = true;
338       Entries.clear();
339     }
340 
341     /// Determine whether the most derived subobject is an array without a
342     /// known bound.
343     bool isMostDerivedAnUnsizedArray() const {
344       assert(!Invalid && "Calling this makes no sense on invalid designators");
345       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
346     }
347 
348     /// Determine what the most derived array's size is. Results in an assertion
349     /// failure if the most derived array lacks a size.
350     uint64_t getMostDerivedArraySize() const {
351       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
352       return MostDerivedArraySize;
353     }
354 
355     /// Determine whether this is a one-past-the-end pointer.
356     bool isOnePastTheEnd() const {
357       assert(!Invalid);
358       if (IsOnePastTheEnd)
359         return true;
360       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
361           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
362               MostDerivedArraySize)
363         return true;
364       return false;
365     }
366 
367     /// Get the range of valid index adjustments in the form
368     ///   {maximum value that can be subtracted from this pointer,
369     ///    maximum value that can be added to this pointer}
370     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
371       if (Invalid || isMostDerivedAnUnsizedArray())
372         return {0, 0};
373 
374       // [expr.add]p4: For the purposes of these operators, a pointer to a
375       // nonarray object behaves the same as a pointer to the first element of
376       // an array of length one with the type of the object as its element type.
377       bool IsArray = MostDerivedPathLength == Entries.size() &&
378                      MostDerivedIsArrayElement;
379       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
380                                     : (uint64_t)IsOnePastTheEnd;
381       uint64_t ArraySize =
382           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
383       return {ArrayIndex, ArraySize - ArrayIndex};
384     }
385 
386     /// Check that this refers to a valid subobject.
387     bool isValidSubobject() const {
388       if (Invalid)
389         return false;
390       return !isOnePastTheEnd();
391     }
392     /// Check that this refers to a valid subobject, and if not, produce a
393     /// relevant diagnostic and set the designator as invalid.
394     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
395 
396     /// Get the type of the designated object.
397     QualType getType(ASTContext &Ctx) const {
398       assert(!Invalid && "invalid designator has no subobject type");
399       return MostDerivedPathLength == Entries.size()
400                  ? MostDerivedType
401                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
402     }
403 
404     /// Update this designator to refer to the first element within this array.
405     void addArrayUnchecked(const ConstantArrayType *CAT) {
406       Entries.push_back(PathEntry::ArrayIndex(0));
407 
408       // This is a most-derived object.
409       MostDerivedType = CAT->getElementType();
410       MostDerivedIsArrayElement = true;
411       MostDerivedArraySize = CAT->getZExtSize();
412       MostDerivedPathLength = Entries.size();
413     }
414     /// Update this designator to refer to the first element within the array of
415     /// elements of type T. This is an array of unknown size.
416     void addUnsizedArrayUnchecked(QualType ElemTy) {
417       Entries.push_back(PathEntry::ArrayIndex(0));
418 
419       MostDerivedType = ElemTy;
420       MostDerivedIsArrayElement = true;
421       // The value in MostDerivedArraySize is undefined in this case. So, set it
422       // to an arbitrary value that's likely to loudly break things if it's
423       // used.
424       MostDerivedArraySize = AssumedSizeForUnsizedArray;
425       MostDerivedPathLength = Entries.size();
426     }
427     /// Update this designator to refer to the given base or member of this
428     /// object.
429     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
430       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
431 
432       // If this isn't a base class, it's a new most-derived object.
433       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
434         MostDerivedType = FD->getType();
435         MostDerivedIsArrayElement = false;
436         MostDerivedArraySize = 0;
437         MostDerivedPathLength = Entries.size();
438       }
439     }
440     /// Update this designator to refer to the given complex component.
441     void addComplexUnchecked(QualType EltTy, bool Imag) {
442       Entries.push_back(PathEntry::ArrayIndex(Imag));
443 
444       // This is technically a most-derived object, though in practice this
445       // is unlikely to matter.
446       MostDerivedType = EltTy;
447       MostDerivedIsArrayElement = true;
448       MostDerivedArraySize = 2;
449       MostDerivedPathLength = Entries.size();
450     }
451 
452     void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
453                                    uint64_t Idx) {
454       Entries.push_back(PathEntry::ArrayIndex(Idx));
455       MostDerivedType = EltTy;
456       MostDerivedPathLength = Entries.size();
457       MostDerivedArraySize = 0;
458       MostDerivedIsArrayElement = false;
459     }
460 
461     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
462     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
463                                    const APSInt &N);
464     /// Add N to the address of this subobject.
465     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
466       if (Invalid || !N) return;
467       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
468       if (isMostDerivedAnUnsizedArray()) {
469         diagnoseUnsizedArrayPointerArithmetic(Info, E);
470         // Can't verify -- trust that the user is doing the right thing (or if
471         // not, trust that the caller will catch the bad behavior).
472         // FIXME: Should we reject if this overflows, at least?
473         Entries.back() = PathEntry::ArrayIndex(
474             Entries.back().getAsArrayIndex() + TruncatedN);
475         return;
476       }
477 
478       // [expr.add]p4: For the purposes of these operators, a pointer to a
479       // nonarray object behaves the same as a pointer to the first element of
480       // an array of length one with the type of the object as its element type.
481       bool IsArray = MostDerivedPathLength == Entries.size() &&
482                      MostDerivedIsArrayElement;
483       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
484                                     : (uint64_t)IsOnePastTheEnd;
485       uint64_t ArraySize =
486           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
487 
488       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
489         // Calculate the actual index in a wide enough type, so we can include
490         // it in the note.
491         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
492         (llvm::APInt&)N += ArrayIndex;
493         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
494         diagnosePointerArithmetic(Info, E, N);
495         setInvalid();
496         return;
497       }
498 
499       ArrayIndex += TruncatedN;
500       assert(ArrayIndex <= ArraySize &&
501              "bounds check succeeded for out-of-bounds index");
502 
503       if (IsArray)
504         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
505       else
506         IsOnePastTheEnd = (ArrayIndex != 0);
507     }
508   };
509 
510   /// A scope at the end of which an object can need to be destroyed.
511   enum class ScopeKind {
512     Block,
513     FullExpression,
514     Call
515   };
516 
517   /// A reference to a particular call and its arguments.
518   struct CallRef {
519     CallRef() : OrigCallee(), CallIndex(0), Version() {}
520     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
521         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
522 
523     explicit operator bool() const { return OrigCallee; }
524 
525     /// Get the parameter that the caller initialized, corresponding to the
526     /// given parameter in the callee.
527     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
528       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
529                         : PVD;
530     }
531 
532     /// The callee at the point where the arguments were evaluated. This might
533     /// be different from the actual callee (a different redeclaration, or a
534     /// virtual override), but this function's parameters are the ones that
535     /// appear in the parameter map.
536     const FunctionDecl *OrigCallee;
537     /// The call index of the frame that holds the argument values.
538     unsigned CallIndex;
539     /// The version of the parameters corresponding to this call.
540     unsigned Version;
541   };
542 
543   /// A stack frame in the constexpr call stack.
544   class CallStackFrame : public interp::Frame {
545   public:
546     EvalInfo &Info;
547 
548     /// Parent - The caller of this stack frame.
549     CallStackFrame *Caller;
550 
551     /// Callee - The function which was called.
552     const FunctionDecl *Callee;
553 
554     /// This - The binding for the this pointer in this call, if any.
555     const LValue *This;
556 
557     /// CallExpr - The syntactical structure of member function calls
558     const Expr *CallExpr;
559 
560     /// Information on how to find the arguments to this call. Our arguments
561     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
562     /// key and this value as the version.
563     CallRef Arguments;
564 
565     /// Source location information about the default argument or default
566     /// initializer expression we're evaluating, if any.
567     CurrentSourceLocExprScope CurSourceLocExprScope;
568 
569     // Note that we intentionally use std::map here so that references to
570     // values are stable.
571     typedef std::pair<const void *, unsigned> MapKeyTy;
572     typedef std::map<MapKeyTy, APValue> MapTy;
573     /// Temporaries - Temporary lvalues materialized within this stack frame.
574     MapTy Temporaries;
575     MapTy ConstexprUnknownAPValues;
576 
577     /// CallRange - The source range of the call expression for this call.
578     SourceRange CallRange;
579 
580     /// Index - The call index of this call.
581     unsigned Index;
582 
583     /// The stack of integers for tracking version numbers for temporaries.
584     SmallVector<unsigned, 2> TempVersionStack = {1};
585     unsigned CurTempVersion = TempVersionStack.back();
586 
587     unsigned getTempVersion() const { return TempVersionStack.back(); }
588 
589     void pushTempVersion() {
590       TempVersionStack.push_back(++CurTempVersion);
591     }
592 
593     void popTempVersion() {
594       TempVersionStack.pop_back();
595     }
596 
597     CallRef createCall(const FunctionDecl *Callee) {
598       return {Callee, Index, ++CurTempVersion};
599     }
600 
601     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
602     // on the overall stack usage of deeply-recursing constexpr evaluations.
603     // (We should cache this map rather than recomputing it repeatedly.)
604     // But let's try this and see how it goes; we can look into caching the map
605     // as a later change.
606 
607     /// LambdaCaptureFields - Mapping from captured variables/this to
608     /// corresponding data members in the closure class.
609     llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
610     FieldDecl *LambdaThisCaptureField = nullptr;
611 
612     CallStackFrame(EvalInfo &Info, SourceRange CallRange,
613                    const FunctionDecl *Callee, const LValue *This,
614                    const Expr *CallExpr, CallRef Arguments);
615     ~CallStackFrame();
616 
617     // Return the temporary for Key whose version number is Version.
618     APValue *getTemporary(const void *Key, unsigned Version) {
619       MapKeyTy KV(Key, Version);
620       auto LB = Temporaries.lower_bound(KV);
621       if (LB != Temporaries.end() && LB->first == KV)
622         return &LB->second;
623       return nullptr;
624     }
625 
626     // Return the current temporary for Key in the map.
627     APValue *getCurrentTemporary(const void *Key) {
628       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
629       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
630         return &std::prev(UB)->second;
631       return nullptr;
632     }
633 
634     // Return the version number of the current temporary for Key.
635     unsigned getCurrentTemporaryVersion(const void *Key) const {
636       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
637       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
638         return std::prev(UB)->first.second;
639       return 0;
640     }
641 
642     /// Allocate storage for an object of type T in this stack frame.
643     /// Populates LV with a handle to the created object. Key identifies
644     /// the temporary within the stack frame, and must not be reused without
645     /// bumping the temporary version number.
646     template<typename KeyT>
647     APValue &createTemporary(const KeyT *Key, QualType T,
648                              ScopeKind Scope, LValue &LV);
649 
650     APValue &createConstexprUnknownAPValues(const VarDecl *Key,
651                                             APValue::LValueBase Base);
652 
653     /// Allocate storage for a parameter of a function call made in this frame.
654     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
655 
656     void describe(llvm::raw_ostream &OS) const override;
657 
658     Frame *getCaller() const override { return Caller; }
659     SourceRange getCallRange() const override { return CallRange; }
660     const FunctionDecl *getCallee() const override { return Callee; }
661 
662     bool isStdFunction() const {
663       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
664         if (DC->isStdNamespace())
665           return true;
666       return false;
667     }
668 
669     /// Whether we're in a context where [[msvc::constexpr]] evaluation is
670     /// permitted. See MSConstexprDocs for description of permitted contexts.
671     bool CanEvalMSConstexpr = false;
672 
673   private:
674     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
675                          ScopeKind Scope);
676   };
677 
678   /// Temporarily override 'this'.
679   class ThisOverrideRAII {
680   public:
681     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
682         : Frame(Frame), OldThis(Frame.This) {
683       if (Enable)
684         Frame.This = NewThis;
685     }
686     ~ThisOverrideRAII() {
687       Frame.This = OldThis;
688     }
689   private:
690     CallStackFrame &Frame;
691     const LValue *OldThis;
692   };
693 
694   // A shorthand time trace scope struct, prints source range, for example
695   // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
696   class ExprTimeTraceScope {
697   public:
698     ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
699         : TimeScope(Name, [E, &Ctx] {
700             return E->getSourceRange().printToString(Ctx.getSourceManager());
701           }) {}
702 
703   private:
704     llvm::TimeTraceScope TimeScope;
705   };
706 
707   /// RAII object used to change the current ability of
708   /// [[msvc::constexpr]] evaulation.
709   struct MSConstexprContextRAII {
710     CallStackFrame &Frame;
711     bool OldValue;
712     explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
713         : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
714       Frame.CanEvalMSConstexpr = Value;
715     }
716 
717     ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
718   };
719 }
720 
721 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
722                               const LValue &This, QualType ThisType);
723 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
724                               APValue::LValueBase LVBase, APValue &Value,
725                               QualType T);
726 
727 namespace {
728   /// A cleanup, and a flag indicating whether it is lifetime-extended.
729   class Cleanup {
730     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
731     APValue::LValueBase Base;
732     QualType T;
733 
734   public:
735     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
736             ScopeKind Scope)
737         : Value(Val, Scope), Base(Base), T(T) {}
738 
739     /// Determine whether this cleanup should be performed at the end of the
740     /// given kind of scope.
741     bool isDestroyedAtEndOf(ScopeKind K) const {
742       return (int)Value.getInt() >= (int)K;
743     }
744     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
745       if (RunDestructors) {
746         SourceLocation Loc;
747         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
748           Loc = VD->getLocation();
749         else if (const Expr *E = Base.dyn_cast<const Expr*>())
750           Loc = E->getExprLoc();
751         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
752       }
753       *Value.getPointer() = APValue();
754       return true;
755     }
756 
757     bool hasSideEffect() {
758       return T.isDestructedType();
759     }
760   };
761 
762   /// A reference to an object whose construction we are currently evaluating.
763   struct ObjectUnderConstruction {
764     APValue::LValueBase Base;
765     ArrayRef<APValue::LValuePathEntry> Path;
766     friend bool operator==(const ObjectUnderConstruction &LHS,
767                            const ObjectUnderConstruction &RHS) {
768       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
769     }
770     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
771       return llvm::hash_combine(Obj.Base, Obj.Path);
772     }
773   };
774   enum class ConstructionPhase {
775     None,
776     Bases,
777     AfterBases,
778     AfterFields,
779     Destroying,
780     DestroyingBases
781   };
782 }
783 
784 namespace llvm {
785 template<> struct DenseMapInfo<ObjectUnderConstruction> {
786   using Base = DenseMapInfo<APValue::LValueBase>;
787   static ObjectUnderConstruction getEmptyKey() {
788     return {Base::getEmptyKey(), {}}; }
789   static ObjectUnderConstruction getTombstoneKey() {
790     return {Base::getTombstoneKey(), {}};
791   }
792   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
793     return hash_value(Object);
794   }
795   static bool isEqual(const ObjectUnderConstruction &LHS,
796                       const ObjectUnderConstruction &RHS) {
797     return LHS == RHS;
798   }
799 };
800 }
801 
802 namespace {
803   /// A dynamically-allocated heap object.
804   struct DynAlloc {
805     /// The value of this heap-allocated object.
806     APValue Value;
807     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
808     /// or a CallExpr (the latter is for direct calls to operator new inside
809     /// std::allocator<T>::allocate).
810     const Expr *AllocExpr = nullptr;
811 
812     enum Kind {
813       New,
814       ArrayNew,
815       StdAllocator
816     };
817 
818     /// Get the kind of the allocation. This must match between allocation
819     /// and deallocation.
820     Kind getKind() const {
821       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
822         return NE->isArray() ? ArrayNew : New;
823       assert(isa<CallExpr>(AllocExpr));
824       return StdAllocator;
825     }
826   };
827 
828   struct DynAllocOrder {
829     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
830       return L.getIndex() < R.getIndex();
831     }
832   };
833 
834   /// EvalInfo - This is a private struct used by the evaluator to capture
835   /// information about a subexpression as it is folded.  It retains information
836   /// about the AST context, but also maintains information about the folded
837   /// expression.
838   ///
839   /// If an expression could be evaluated, it is still possible it is not a C
840   /// "integer constant expression" or constant expression.  If not, this struct
841   /// captures information about how and why not.
842   ///
843   /// One bit of information passed *into* the request for constant folding
844   /// indicates whether the subexpression is "evaluated" or not according to C
845   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
846   /// evaluate the expression regardless of what the RHS is, but C only allows
847   /// certain things in certain situations.
848   class EvalInfo : public interp::State {
849   public:
850     ASTContext &Ctx;
851 
852     /// EvalStatus - Contains information about the evaluation.
853     Expr::EvalStatus &EvalStatus;
854 
855     /// CurrentCall - The top of the constexpr call stack.
856     CallStackFrame *CurrentCall;
857 
858     /// CallStackDepth - The number of calls in the call stack right now.
859     unsigned CallStackDepth;
860 
861     /// NextCallIndex - The next call index to assign.
862     unsigned NextCallIndex;
863 
864     /// StepsLeft - The remaining number of evaluation steps we're permitted
865     /// to perform. This is essentially a limit for the number of statements
866     /// we will evaluate.
867     unsigned StepsLeft;
868 
869     /// Enable the experimental new constant interpreter. If an expression is
870     /// not supported by the interpreter, an error is triggered.
871     bool EnableNewConstInterp;
872 
873     /// BottomFrame - The frame in which evaluation started. This must be
874     /// initialized after CurrentCall and CallStackDepth.
875     CallStackFrame BottomFrame;
876 
877     /// A stack of values whose lifetimes end at the end of some surrounding
878     /// evaluation frame.
879     llvm::SmallVector<Cleanup, 16> CleanupStack;
880 
881     /// EvaluatingDecl - This is the declaration whose initializer is being
882     /// evaluated, if any.
883     APValue::LValueBase EvaluatingDecl;
884 
885     enum class EvaluatingDeclKind {
886       None,
887       /// We're evaluating the construction of EvaluatingDecl.
888       Ctor,
889       /// We're evaluating the destruction of EvaluatingDecl.
890       Dtor,
891     };
892     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
893 
894     /// EvaluatingDeclValue - This is the value being constructed for the
895     /// declaration whose initializer is being evaluated, if any.
896     APValue *EvaluatingDeclValue;
897 
898     /// Set of objects that are currently being constructed.
899     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
900         ObjectsUnderConstruction;
901 
902     /// Current heap allocations, along with the location where each was
903     /// allocated. We use std::map here because we need stable addresses
904     /// for the stored APValues.
905     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
906 
907     /// The number of heap allocations performed so far in this evaluation.
908     unsigned NumHeapAllocs = 0;
909 
910     struct EvaluatingConstructorRAII {
911       EvalInfo &EI;
912       ObjectUnderConstruction Object;
913       bool DidInsert;
914       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
915                                 bool HasBases)
916           : EI(EI), Object(Object) {
917         DidInsert =
918             EI.ObjectsUnderConstruction
919                 .insert({Object, HasBases ? ConstructionPhase::Bases
920                                           : ConstructionPhase::AfterBases})
921                 .second;
922       }
923       void finishedConstructingBases() {
924         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
925       }
926       void finishedConstructingFields() {
927         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
928       }
929       ~EvaluatingConstructorRAII() {
930         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
931       }
932     };
933 
934     struct EvaluatingDestructorRAII {
935       EvalInfo &EI;
936       ObjectUnderConstruction Object;
937       bool DidInsert;
938       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
939           : EI(EI), Object(Object) {
940         DidInsert = EI.ObjectsUnderConstruction
941                         .insert({Object, ConstructionPhase::Destroying})
942                         .second;
943       }
944       void startedDestroyingBases() {
945         EI.ObjectsUnderConstruction[Object] =
946             ConstructionPhase::DestroyingBases;
947       }
948       ~EvaluatingDestructorRAII() {
949         if (DidInsert)
950           EI.ObjectsUnderConstruction.erase(Object);
951       }
952     };
953 
954     ConstructionPhase
955     isEvaluatingCtorDtor(APValue::LValueBase Base,
956                          ArrayRef<APValue::LValuePathEntry> Path) {
957       return ObjectsUnderConstruction.lookup({Base, Path});
958     }
959 
960     /// If we're currently speculatively evaluating, the outermost call stack
961     /// depth at which we can mutate state, otherwise 0.
962     unsigned SpeculativeEvaluationDepth = 0;
963 
964     /// The current array initialization index, if we're performing array
965     /// initialization.
966     uint64_t ArrayInitIndex = -1;
967 
968     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
969     /// notes attached to it will also be stored, otherwise they will not be.
970     bool HasActiveDiagnostic;
971 
972     /// Have we emitted a diagnostic explaining why we couldn't constant
973     /// fold (not just why it's not strictly a constant expression)?
974     bool HasFoldFailureDiagnostic;
975 
976     /// Whether we're checking that an expression is a potential constant
977     /// expression. If so, do not fail on constructs that could become constant
978     /// later on (such as a use of an undefined global).
979     bool CheckingPotentialConstantExpression = false;
980 
981     /// Whether we're checking for an expression that has undefined behavior.
982     /// If so, we will produce warnings if we encounter an operation that is
983     /// always undefined.
984     ///
985     /// Note that we still need to evaluate the expression normally when this
986     /// is set; this is used when evaluating ICEs in C.
987     bool CheckingForUndefinedBehavior = false;
988 
989     enum EvaluationMode {
990       /// Evaluate as a constant expression. Stop if we find that the expression
991       /// is not a constant expression.
992       EM_ConstantExpression,
993 
994       /// Evaluate as a constant expression. Stop if we find that the expression
995       /// is not a constant expression. Some expressions can be retried in the
996       /// optimizer if we don't constant fold them here, but in an unevaluated
997       /// context we try to fold them immediately since the optimizer never
998       /// gets a chance to look at it.
999       EM_ConstantExpressionUnevaluated,
1000 
1001       /// Fold the expression to a constant. Stop if we hit a side-effect that
1002       /// we can't model.
1003       EM_ConstantFold,
1004 
1005       /// Evaluate in any way we know how. Don't worry about side-effects that
1006       /// can't be modeled.
1007       EM_IgnoreSideEffects,
1008     } EvalMode;
1009 
1010     /// Are we checking whether the expression is a potential constant
1011     /// expression?
1012     bool checkingPotentialConstantExpression() const override  {
1013       return CheckingPotentialConstantExpression;
1014     }
1015 
1016     /// Are we checking an expression for overflow?
1017     // FIXME: We should check for any kind of undefined or suspicious behavior
1018     // in such constructs, not just overflow.
1019     bool checkingForUndefinedBehavior() const override {
1020       return CheckingForUndefinedBehavior;
1021     }
1022 
1023     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1024         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1025           CallStackDepth(0), NextCallIndex(1),
1026           StepsLeft(C.getLangOpts().ConstexprStepLimit),
1027           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1028           BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1029                       /*This=*/nullptr,
1030                       /*CallExpr=*/nullptr, CallRef()),
1031           EvaluatingDecl((const ValueDecl *)nullptr),
1032           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1033           HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1034 
1035     ~EvalInfo() {
1036       discardCleanups();
1037     }
1038 
1039     ASTContext &getASTContext() const override { return Ctx; }
1040 
1041     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1042                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1043       EvaluatingDecl = Base;
1044       IsEvaluatingDecl = EDK;
1045       EvaluatingDeclValue = &Value;
1046     }
1047 
1048     bool CheckCallLimit(SourceLocation Loc) {
1049       // Don't perform any constexpr calls (other than the call we're checking)
1050       // when checking a potential constant expression.
1051       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1052         return false;
1053       if (NextCallIndex == 0) {
1054         // NextCallIndex has wrapped around.
1055         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1056         return false;
1057       }
1058       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1059         return true;
1060       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1061         << getLangOpts().ConstexprCallDepth;
1062       return false;
1063     }
1064 
1065     bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1066                         uint64_t ElemCount, bool Diag) {
1067       // FIXME: GH63562
1068       // APValue stores array extents as unsigned,
1069       // so anything that is greater that unsigned would overflow when
1070       // constructing the array, we catch this here.
1071       if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1072           ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1073         if (Diag)
1074           FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1075         return false;
1076       }
1077 
1078       // FIXME: GH63562
1079       // Arrays allocate an APValue per element.
1080       // We use the number of constexpr steps as a proxy for the maximum size
1081       // of arrays to avoid exhausting the system resources, as initialization
1082       // of each element is likely to take some number of steps anyway.
1083       uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1084       if (ElemCount > Limit) {
1085         if (Diag)
1086           FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1087               << ElemCount << Limit;
1088         return false;
1089       }
1090       return true;
1091     }
1092 
1093     std::pair<CallStackFrame *, unsigned>
1094     getCallFrameAndDepth(unsigned CallIndex) {
1095       assert(CallIndex && "no call index in getCallFrameAndDepth");
1096       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1097       // be null in this loop.
1098       unsigned Depth = CallStackDepth;
1099       CallStackFrame *Frame = CurrentCall;
1100       while (Frame->Index > CallIndex) {
1101         Frame = Frame->Caller;
1102         --Depth;
1103       }
1104       if (Frame->Index == CallIndex)
1105         return {Frame, Depth};
1106       return {nullptr, 0};
1107     }
1108 
1109     bool nextStep(const Stmt *S) {
1110       if (!StepsLeft) {
1111         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1112         return false;
1113       }
1114       --StepsLeft;
1115       return true;
1116     }
1117 
1118     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1119 
1120     std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1121       std::optional<DynAlloc *> Result;
1122       auto It = HeapAllocs.find(DA);
1123       if (It != HeapAllocs.end())
1124         Result = &It->second;
1125       return Result;
1126     }
1127 
1128     /// Get the allocated storage for the given parameter of the given call.
1129     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1130       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1131       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1132                    : nullptr;
1133     }
1134 
1135     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1136     struct StdAllocatorCaller {
1137       unsigned FrameIndex;
1138       QualType ElemType;
1139       const Expr *Call;
1140       explicit operator bool() const { return FrameIndex != 0; };
1141     };
1142 
1143     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1144       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1145            Call = Call->Caller) {
1146         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1147         if (!MD)
1148           continue;
1149         const IdentifierInfo *FnII = MD->getIdentifier();
1150         if (!FnII || !FnII->isStr(FnName))
1151           continue;
1152 
1153         const auto *CTSD =
1154             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1155         if (!CTSD)
1156           continue;
1157 
1158         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1159         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1160         if (CTSD->isInStdNamespace() && ClassII &&
1161             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1162             TAL[0].getKind() == TemplateArgument::Type)
1163           return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1164       }
1165 
1166       return {};
1167     }
1168 
1169     void performLifetimeExtension() {
1170       // Disable the cleanups for lifetime-extended temporaries.
1171       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1172         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1173       });
1174     }
1175 
1176     /// Throw away any remaining cleanups at the end of evaluation. If any
1177     /// cleanups would have had a side-effect, note that as an unmodeled
1178     /// side-effect and return false. Otherwise, return true.
1179     bool discardCleanups() {
1180       for (Cleanup &C : CleanupStack) {
1181         if (C.hasSideEffect() && !noteSideEffect()) {
1182           CleanupStack.clear();
1183           return false;
1184         }
1185       }
1186       CleanupStack.clear();
1187       return true;
1188     }
1189 
1190   private:
1191     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1192     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1193 
1194     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1195     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1196 
1197     void setFoldFailureDiagnostic(bool Flag) override {
1198       HasFoldFailureDiagnostic = Flag;
1199     }
1200 
1201     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1202 
1203     // If we have a prior diagnostic, it will be noting that the expression
1204     // isn't a constant expression. This diagnostic is more important,
1205     // unless we require this evaluation to produce a constant expression.
1206     //
1207     // FIXME: We might want to show both diagnostics to the user in
1208     // EM_ConstantFold mode.
1209     bool hasPriorDiagnostic() override {
1210       if (!EvalStatus.Diag->empty()) {
1211         switch (EvalMode) {
1212         case EM_ConstantFold:
1213         case EM_IgnoreSideEffects:
1214           if (!HasFoldFailureDiagnostic)
1215             break;
1216           // We've already failed to fold something. Keep that diagnostic.
1217           [[fallthrough]];
1218         case EM_ConstantExpression:
1219         case EM_ConstantExpressionUnevaluated:
1220           setActiveDiagnostic(false);
1221           return true;
1222         }
1223       }
1224       return false;
1225     }
1226 
1227     unsigned getCallStackDepth() override { return CallStackDepth; }
1228 
1229   public:
1230     /// Should we continue evaluation after encountering a side-effect that we
1231     /// couldn't model?
1232     bool keepEvaluatingAfterSideEffect() const override {
1233       switch (EvalMode) {
1234       case EM_IgnoreSideEffects:
1235         return true;
1236 
1237       case EM_ConstantExpression:
1238       case EM_ConstantExpressionUnevaluated:
1239       case EM_ConstantFold:
1240         // By default, assume any side effect might be valid in some other
1241         // evaluation of this expression from a different context.
1242         return checkingPotentialConstantExpression() ||
1243                checkingForUndefinedBehavior();
1244       }
1245       llvm_unreachable("Missed EvalMode case");
1246     }
1247 
1248     /// Note that we have had a side-effect, and determine whether we should
1249     /// keep evaluating.
1250     bool noteSideEffect() override {
1251       EvalStatus.HasSideEffects = true;
1252       return keepEvaluatingAfterSideEffect();
1253     }
1254 
1255     /// Should we continue evaluation after encountering undefined behavior?
1256     bool keepEvaluatingAfterUndefinedBehavior() {
1257       switch (EvalMode) {
1258       case EM_IgnoreSideEffects:
1259       case EM_ConstantFold:
1260         return true;
1261 
1262       case EM_ConstantExpression:
1263       case EM_ConstantExpressionUnevaluated:
1264         return checkingForUndefinedBehavior();
1265       }
1266       llvm_unreachable("Missed EvalMode case");
1267     }
1268 
1269     /// Note that we hit something that was technically undefined behavior, but
1270     /// that we can evaluate past it (such as signed overflow or floating-point
1271     /// division by zero.)
1272     bool noteUndefinedBehavior() override {
1273       EvalStatus.HasUndefinedBehavior = true;
1274       return keepEvaluatingAfterUndefinedBehavior();
1275     }
1276 
1277     /// Should we continue evaluation as much as possible after encountering a
1278     /// construct which can't be reduced to a value?
1279     bool keepEvaluatingAfterFailure() const override {
1280       if (!StepsLeft)
1281         return false;
1282 
1283       switch (EvalMode) {
1284       case EM_ConstantExpression:
1285       case EM_ConstantExpressionUnevaluated:
1286       case EM_ConstantFold:
1287       case EM_IgnoreSideEffects:
1288         return checkingPotentialConstantExpression() ||
1289                checkingForUndefinedBehavior();
1290       }
1291       llvm_unreachable("Missed EvalMode case");
1292     }
1293 
1294     /// Notes that we failed to evaluate an expression that other expressions
1295     /// directly depend on, and determine if we should keep evaluating. This
1296     /// should only be called if we actually intend to keep evaluating.
1297     ///
1298     /// Call noteSideEffect() instead if we may be able to ignore the value that
1299     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1300     ///
1301     /// (Foo(), 1)      // use noteSideEffect
1302     /// (Foo() || true) // use noteSideEffect
1303     /// Foo() + 1       // use noteFailure
1304     [[nodiscard]] bool noteFailure() {
1305       // Failure when evaluating some expression often means there is some
1306       // subexpression whose evaluation was skipped. Therefore, (because we
1307       // don't track whether we skipped an expression when unwinding after an
1308       // evaluation failure) every evaluation failure that bubbles up from a
1309       // subexpression implies that a side-effect has potentially happened. We
1310       // skip setting the HasSideEffects flag to true until we decide to
1311       // continue evaluating after that point, which happens here.
1312       bool KeepGoing = keepEvaluatingAfterFailure();
1313       EvalStatus.HasSideEffects |= KeepGoing;
1314       return KeepGoing;
1315     }
1316 
1317     class ArrayInitLoopIndex {
1318       EvalInfo &Info;
1319       uint64_t OuterIndex;
1320 
1321     public:
1322       ArrayInitLoopIndex(EvalInfo &Info)
1323           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1324         Info.ArrayInitIndex = 0;
1325       }
1326       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1327 
1328       operator uint64_t&() { return Info.ArrayInitIndex; }
1329     };
1330   };
1331 
1332   /// Object used to treat all foldable expressions as constant expressions.
1333   struct FoldConstant {
1334     EvalInfo &Info;
1335     bool Enabled;
1336     bool HadNoPriorDiags;
1337     EvalInfo::EvaluationMode OldMode;
1338 
1339     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1340       : Info(Info),
1341         Enabled(Enabled),
1342         HadNoPriorDiags(Info.EvalStatus.Diag &&
1343                         Info.EvalStatus.Diag->empty() &&
1344                         !Info.EvalStatus.HasSideEffects),
1345         OldMode(Info.EvalMode) {
1346       if (Enabled)
1347         Info.EvalMode = EvalInfo::EM_ConstantFold;
1348     }
1349     void keepDiagnostics() { Enabled = false; }
1350     ~FoldConstant() {
1351       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1352           !Info.EvalStatus.HasSideEffects)
1353         Info.EvalStatus.Diag->clear();
1354       Info.EvalMode = OldMode;
1355     }
1356   };
1357 
1358   /// RAII object used to set the current evaluation mode to ignore
1359   /// side-effects.
1360   struct IgnoreSideEffectsRAII {
1361     EvalInfo &Info;
1362     EvalInfo::EvaluationMode OldMode;
1363     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1364         : Info(Info), OldMode(Info.EvalMode) {
1365       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1366     }
1367 
1368     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1369   };
1370 
1371   /// RAII object used to optionally suppress diagnostics and side-effects from
1372   /// a speculative evaluation.
1373   class SpeculativeEvaluationRAII {
1374     EvalInfo *Info = nullptr;
1375     Expr::EvalStatus OldStatus;
1376     unsigned OldSpeculativeEvaluationDepth = 0;
1377 
1378     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1379       Info = Other.Info;
1380       OldStatus = Other.OldStatus;
1381       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1382       Other.Info = nullptr;
1383     }
1384 
1385     void maybeRestoreState() {
1386       if (!Info)
1387         return;
1388 
1389       Info->EvalStatus = OldStatus;
1390       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1391     }
1392 
1393   public:
1394     SpeculativeEvaluationRAII() = default;
1395 
1396     SpeculativeEvaluationRAII(
1397         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1398         : Info(&Info), OldStatus(Info.EvalStatus),
1399           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1400       Info.EvalStatus.Diag = NewDiag;
1401       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1402     }
1403 
1404     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1405     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1406       moveFromAndCancel(std::move(Other));
1407     }
1408 
1409     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1410       maybeRestoreState();
1411       moveFromAndCancel(std::move(Other));
1412       return *this;
1413     }
1414 
1415     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1416   };
1417 
1418   /// RAII object wrapping a full-expression or block scope, and handling
1419   /// the ending of the lifetime of temporaries created within it.
1420   template<ScopeKind Kind>
1421   class ScopeRAII {
1422     EvalInfo &Info;
1423     unsigned OldStackSize;
1424   public:
1425     ScopeRAII(EvalInfo &Info)
1426         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1427       // Push a new temporary version. This is needed to distinguish between
1428       // temporaries created in different iterations of a loop.
1429       Info.CurrentCall->pushTempVersion();
1430     }
1431     bool destroy(bool RunDestructors = true) {
1432       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1433       OldStackSize = -1U;
1434       return OK;
1435     }
1436     ~ScopeRAII() {
1437       if (OldStackSize != -1U)
1438         destroy(false);
1439       // Body moved to a static method to encourage the compiler to inline away
1440       // instances of this class.
1441       Info.CurrentCall->popTempVersion();
1442     }
1443   private:
1444     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1445                         unsigned OldStackSize) {
1446       assert(OldStackSize <= Info.CleanupStack.size() &&
1447              "running cleanups out of order?");
1448 
1449       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1450       // for a full-expression scope.
1451       bool Success = true;
1452       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1453         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1454           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1455             Success = false;
1456             break;
1457           }
1458         }
1459       }
1460 
1461       // Compact any retained cleanups.
1462       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1463       if (Kind != ScopeKind::Block)
1464         NewEnd =
1465             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1466               return C.isDestroyedAtEndOf(Kind);
1467             });
1468       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1469       return Success;
1470     }
1471   };
1472   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1473   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1474   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1475 }
1476 
1477 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1478                                          CheckSubobjectKind CSK) {
1479   if (Invalid)
1480     return false;
1481   if (isOnePastTheEnd()) {
1482     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1483       << CSK;
1484     setInvalid();
1485     return false;
1486   }
1487   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1488   // must actually be at least one array element; even a VLA cannot have a
1489   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1490   return true;
1491 }
1492 
1493 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1494                                                                 const Expr *E) {
1495   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1496   // Do not set the designator as invalid: we can represent this situation,
1497   // and correct handling of __builtin_object_size requires us to do so.
1498 }
1499 
1500 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1501                                                     const Expr *E,
1502                                                     const APSInt &N) {
1503   // If we're complaining, we must be able to statically determine the size of
1504   // the most derived array.
1505   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1506     Info.CCEDiag(E, diag::note_constexpr_array_index)
1507       << N << /*array*/ 0
1508       << static_cast<unsigned>(getMostDerivedArraySize());
1509   else
1510     Info.CCEDiag(E, diag::note_constexpr_array_index)
1511       << N << /*non-array*/ 1;
1512   setInvalid();
1513 }
1514 
1515 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1516                                const FunctionDecl *Callee, const LValue *This,
1517                                const Expr *CallExpr, CallRef Call)
1518     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1519       CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1520       Index(Info.NextCallIndex++) {
1521   Info.CurrentCall = this;
1522   ++Info.CallStackDepth;
1523 }
1524 
1525 CallStackFrame::~CallStackFrame() {
1526   assert(Info.CurrentCall == this && "calls retired out of order");
1527   --Info.CallStackDepth;
1528   Info.CurrentCall = Caller;
1529 }
1530 
1531 static bool isRead(AccessKinds AK) {
1532   return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1533          AK == AK_IsWithinLifetime;
1534 }
1535 
1536 static bool isModification(AccessKinds AK) {
1537   switch (AK) {
1538   case AK_Read:
1539   case AK_ReadObjectRepresentation:
1540   case AK_MemberCall:
1541   case AK_DynamicCast:
1542   case AK_TypeId:
1543   case AK_IsWithinLifetime:
1544     return false;
1545   case AK_Assign:
1546   case AK_Increment:
1547   case AK_Decrement:
1548   case AK_Construct:
1549   case AK_Destroy:
1550     return true;
1551   }
1552   llvm_unreachable("unknown access kind");
1553 }
1554 
1555 static bool isAnyAccess(AccessKinds AK) {
1556   return isRead(AK) || isModification(AK);
1557 }
1558 
1559 /// Is this an access per the C++ definition?
1560 static bool isFormalAccess(AccessKinds AK) {
1561   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1562          AK != AK_IsWithinLifetime;
1563 }
1564 
1565 /// Is this kind of axcess valid on an indeterminate object value?
1566 static bool isValidIndeterminateAccess(AccessKinds AK) {
1567   switch (AK) {
1568   case AK_Read:
1569   case AK_Increment:
1570   case AK_Decrement:
1571     // These need the object's value.
1572     return false;
1573 
1574   case AK_IsWithinLifetime:
1575   case AK_ReadObjectRepresentation:
1576   case AK_Assign:
1577   case AK_Construct:
1578   case AK_Destroy:
1579     // Construction and destruction don't need the value.
1580     return true;
1581 
1582   case AK_MemberCall:
1583   case AK_DynamicCast:
1584   case AK_TypeId:
1585     // These aren't really meaningful on scalars.
1586     return true;
1587   }
1588   llvm_unreachable("unknown access kind");
1589 }
1590 
1591 namespace {
1592   struct ComplexValue {
1593   private:
1594     bool IsInt;
1595 
1596   public:
1597     APSInt IntReal, IntImag;
1598     APFloat FloatReal, FloatImag;
1599 
1600     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1601 
1602     void makeComplexFloat() { IsInt = false; }
1603     bool isComplexFloat() const { return !IsInt; }
1604     APFloat &getComplexFloatReal() { return FloatReal; }
1605     APFloat &getComplexFloatImag() { return FloatImag; }
1606 
1607     void makeComplexInt() { IsInt = true; }
1608     bool isComplexInt() const { return IsInt; }
1609     APSInt &getComplexIntReal() { return IntReal; }
1610     APSInt &getComplexIntImag() { return IntImag; }
1611 
1612     void moveInto(APValue &v) const {
1613       if (isComplexFloat())
1614         v = APValue(FloatReal, FloatImag);
1615       else
1616         v = APValue(IntReal, IntImag);
1617     }
1618     void setFrom(const APValue &v) {
1619       assert(v.isComplexFloat() || v.isComplexInt());
1620       if (v.isComplexFloat()) {
1621         makeComplexFloat();
1622         FloatReal = v.getComplexFloatReal();
1623         FloatImag = v.getComplexFloatImag();
1624       } else {
1625         makeComplexInt();
1626         IntReal = v.getComplexIntReal();
1627         IntImag = v.getComplexIntImag();
1628       }
1629     }
1630   };
1631 
1632   struct LValue {
1633     APValue::LValueBase Base;
1634     CharUnits Offset;
1635     SubobjectDesignator Designator;
1636     bool IsNullPtr : 1;
1637     bool InvalidBase : 1;
1638     // P2280R4 track if we have an unknown reference or pointer.
1639     bool AllowConstexprUnknown = false;
1640 
1641     const APValue::LValueBase getLValueBase() const { return Base; }
1642     bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1643     CharUnits &getLValueOffset() { return Offset; }
1644     const CharUnits &getLValueOffset() const { return Offset; }
1645     SubobjectDesignator &getLValueDesignator() { return Designator; }
1646     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1647     bool isNullPointer() const { return IsNullPtr;}
1648 
1649     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1650     unsigned getLValueVersion() const { return Base.getVersion(); }
1651 
1652     void moveInto(APValue &V) const {
1653       if (Designator.Invalid)
1654         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1655       else {
1656         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1657         V = APValue(Base, Offset, Designator.Entries,
1658                     Designator.IsOnePastTheEnd, IsNullPtr);
1659       }
1660       if (AllowConstexprUnknown)
1661         V.setConstexprUnknown();
1662     }
1663     void setFrom(ASTContext &Ctx, const APValue &V) {
1664       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1665       Base = V.getLValueBase();
1666       Offset = V.getLValueOffset();
1667       InvalidBase = false;
1668       Designator = SubobjectDesignator(Ctx, V);
1669       IsNullPtr = V.isNullPointer();
1670       AllowConstexprUnknown = V.allowConstexprUnknown();
1671     }
1672 
1673     void set(APValue::LValueBase B, bool BInvalid = false) {
1674 #ifndef NDEBUG
1675       // We only allow a few types of invalid bases. Enforce that here.
1676       if (BInvalid) {
1677         const auto *E = B.get<const Expr *>();
1678         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1679                "Unexpected type of invalid base");
1680       }
1681 #endif
1682 
1683       Base = B;
1684       Offset = CharUnits::fromQuantity(0);
1685       InvalidBase = BInvalid;
1686       Designator = SubobjectDesignator(getType(B));
1687       IsNullPtr = false;
1688       AllowConstexprUnknown = false;
1689     }
1690 
1691     void setNull(ASTContext &Ctx, QualType PointerTy) {
1692       Base = (const ValueDecl *)nullptr;
1693       Offset =
1694           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1695       InvalidBase = false;
1696       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1697       IsNullPtr = true;
1698       AllowConstexprUnknown = false;
1699     }
1700 
1701     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1702       set(B, true);
1703     }
1704 
1705     std::string toString(ASTContext &Ctx, QualType T) const {
1706       APValue Printable;
1707       moveInto(Printable);
1708       return Printable.getAsString(Ctx, T);
1709     }
1710 
1711   private:
1712     // Check that this LValue is not based on a null pointer. If it is, produce
1713     // a diagnostic and mark the designator as invalid.
1714     template <typename GenDiagType>
1715     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1716       if (Designator.Invalid)
1717         return false;
1718       if (IsNullPtr) {
1719         GenDiag();
1720         Designator.setInvalid();
1721         return false;
1722       }
1723       return true;
1724     }
1725 
1726   public:
1727     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1728                           CheckSubobjectKind CSK) {
1729       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1730         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1731       });
1732     }
1733 
1734     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1735                                        AccessKinds AK) {
1736       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1737         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1738       });
1739     }
1740 
1741     // Check this LValue refers to an object. If not, set the designator to be
1742     // invalid and emit a diagnostic.
1743     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1744       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1745              Designator.checkSubobject(Info, E, CSK);
1746     }
1747 
1748     void addDecl(EvalInfo &Info, const Expr *E,
1749                  const Decl *D, bool Virtual = false) {
1750       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1751         Designator.addDeclUnchecked(D, Virtual);
1752     }
1753     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1754       if (!Designator.Entries.empty()) {
1755         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1756         Designator.setInvalid();
1757         return;
1758       }
1759       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1760         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1761         Designator.FirstEntryIsAnUnsizedArray = true;
1762         Designator.addUnsizedArrayUnchecked(ElemTy);
1763       }
1764     }
1765     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1766       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1767         Designator.addArrayUnchecked(CAT);
1768     }
1769     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1770       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1771         Designator.addComplexUnchecked(EltTy, Imag);
1772     }
1773     void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1774                           uint64_t Size, uint64_t Idx) {
1775       if (checkSubobject(Info, E, CSK_VectorElement))
1776         Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1777     }
1778     void clearIsNullPointer() {
1779       IsNullPtr = false;
1780     }
1781     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1782                               const APSInt &Index, CharUnits ElementSize) {
1783       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1784       // but we're not required to diagnose it and it's valid in C++.)
1785       if (!Index)
1786         return;
1787 
1788       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1789       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1790       // offsets.
1791       uint64_t Offset64 = Offset.getQuantity();
1792       uint64_t ElemSize64 = ElementSize.getQuantity();
1793       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1794       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1795 
1796       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1797         Designator.adjustIndex(Info, E, Index);
1798       clearIsNullPointer();
1799     }
1800     void adjustOffset(CharUnits N) {
1801       Offset += N;
1802       if (N.getQuantity())
1803         clearIsNullPointer();
1804     }
1805   };
1806 
1807   struct MemberPtr {
1808     MemberPtr() {}
1809     explicit MemberPtr(const ValueDecl *Decl)
1810         : DeclAndIsDerivedMember(Decl, false) {}
1811 
1812     /// The member or (direct or indirect) field referred to by this member
1813     /// pointer, or 0 if this is a null member pointer.
1814     const ValueDecl *getDecl() const {
1815       return DeclAndIsDerivedMember.getPointer();
1816     }
1817     /// Is this actually a member of some type derived from the relevant class?
1818     bool isDerivedMember() const {
1819       return DeclAndIsDerivedMember.getInt();
1820     }
1821     /// Get the class which the declaration actually lives in.
1822     const CXXRecordDecl *getContainingRecord() const {
1823       return cast<CXXRecordDecl>(
1824           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1825     }
1826 
1827     void moveInto(APValue &V) const {
1828       V = APValue(getDecl(), isDerivedMember(), Path);
1829     }
1830     void setFrom(const APValue &V) {
1831       assert(V.isMemberPointer());
1832       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1833       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1834       Path.clear();
1835       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1836       Path.insert(Path.end(), P.begin(), P.end());
1837     }
1838 
1839     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1840     /// whether the member is a member of some class derived from the class type
1841     /// of the member pointer.
1842     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1843     /// Path - The path of base/derived classes from the member declaration's
1844     /// class (exclusive) to the class type of the member pointer (inclusive).
1845     SmallVector<const CXXRecordDecl*, 4> Path;
1846 
1847     /// Perform a cast towards the class of the Decl (either up or down the
1848     /// hierarchy).
1849     bool castBack(const CXXRecordDecl *Class) {
1850       assert(!Path.empty());
1851       const CXXRecordDecl *Expected;
1852       if (Path.size() >= 2)
1853         Expected = Path[Path.size() - 2];
1854       else
1855         Expected = getContainingRecord();
1856       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1857         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1858         // if B does not contain the original member and is not a base or
1859         // derived class of the class containing the original member, the result
1860         // of the cast is undefined.
1861         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1862         // (D::*). We consider that to be a language defect.
1863         return false;
1864       }
1865       Path.pop_back();
1866       return true;
1867     }
1868     /// Perform a base-to-derived member pointer cast.
1869     bool castToDerived(const CXXRecordDecl *Derived) {
1870       if (!getDecl())
1871         return true;
1872       if (!isDerivedMember()) {
1873         Path.push_back(Derived);
1874         return true;
1875       }
1876       if (!castBack(Derived))
1877         return false;
1878       if (Path.empty())
1879         DeclAndIsDerivedMember.setInt(false);
1880       return true;
1881     }
1882     /// Perform a derived-to-base member pointer cast.
1883     bool castToBase(const CXXRecordDecl *Base) {
1884       if (!getDecl())
1885         return true;
1886       if (Path.empty())
1887         DeclAndIsDerivedMember.setInt(true);
1888       if (isDerivedMember()) {
1889         Path.push_back(Base);
1890         return true;
1891       }
1892       return castBack(Base);
1893     }
1894   };
1895 
1896   /// Compare two member pointers, which are assumed to be of the same type.
1897   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1898     if (!LHS.getDecl() || !RHS.getDecl())
1899       return !LHS.getDecl() && !RHS.getDecl();
1900     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1901       return false;
1902     return LHS.Path == RHS.Path;
1903   }
1904 }
1905 
1906 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1907 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1908                             const LValue &This, const Expr *E,
1909                             bool AllowNonLiteralTypes = false);
1910 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1911                            bool InvalidBaseOK = false);
1912 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1913                             bool InvalidBaseOK = false);
1914 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1915                                   EvalInfo &Info);
1916 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1917 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1918 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1919                                     EvalInfo &Info);
1920 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1921 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1922 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1923                            EvalInfo &Info);
1924 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1925 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1926                                   EvalInfo &Info,
1927                                   std::string *StringResult = nullptr);
1928 
1929 /// Evaluate an integer or fixed point expression into an APResult.
1930 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1931                                         EvalInfo &Info);
1932 
1933 /// Evaluate only a fixed point expression into an APResult.
1934 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1935                                EvalInfo &Info);
1936 
1937 //===----------------------------------------------------------------------===//
1938 // Misc utilities
1939 //===----------------------------------------------------------------------===//
1940 
1941 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1942 /// preserving its value (by extending by up to one bit as needed).
1943 static void negateAsSigned(APSInt &Int) {
1944   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1945     Int = Int.extend(Int.getBitWidth() + 1);
1946     Int.setIsSigned(true);
1947   }
1948   Int = -Int;
1949 }
1950 
1951 template<typename KeyT>
1952 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1953                                          ScopeKind Scope, LValue &LV) {
1954   unsigned Version = getTempVersion();
1955   APValue::LValueBase Base(Key, Index, Version);
1956   LV.set(Base);
1957   return createLocal(Base, Key, T, Scope);
1958 }
1959 
1960 APValue &
1961 CallStackFrame::createConstexprUnknownAPValues(const VarDecl *Key,
1962                                                APValue::LValueBase Base) {
1963   APValue &Result = ConstexprUnknownAPValues[MapKeyTy(Key, Base.getVersion())];
1964   Result = APValue(Base, CharUnits::Zero(), APValue::ConstexprUnknown{});
1965 
1966   return Result;
1967 }
1968 
1969 /// Allocate storage for a parameter of a function call made in this frame.
1970 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1971                                      LValue &LV) {
1972   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1973   APValue::LValueBase Base(PVD, Index, Args.Version);
1974   LV.set(Base);
1975   // We always destroy parameters at the end of the call, even if we'd allow
1976   // them to live to the end of the full-expression at runtime, in order to
1977   // give portable results and match other compilers.
1978   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1979 }
1980 
1981 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1982                                      QualType T, ScopeKind Scope) {
1983   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1984   unsigned Version = Base.getVersion();
1985   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1986   assert(Result.isAbsent() && "local created multiple times");
1987 
1988   // If we're creating a local immediately in the operand of a speculative
1989   // evaluation, don't register a cleanup to be run outside the speculative
1990   // evaluation context, since we won't actually be able to initialize this
1991   // object.
1992   if (Index <= Info.SpeculativeEvaluationDepth) {
1993     if (T.isDestructedType())
1994       Info.noteSideEffect();
1995   } else {
1996     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1997   }
1998   return Result;
1999 }
2000 
2001 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
2002   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
2003     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
2004     return nullptr;
2005   }
2006 
2007   DynamicAllocLValue DA(NumHeapAllocs++);
2008   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
2009   auto Result = HeapAllocs.emplace(std::piecewise_construct,
2010                                    std::forward_as_tuple(DA), std::tuple<>());
2011   assert(Result.second && "reused a heap alloc index?");
2012   Result.first->second.AllocExpr = E;
2013   return &Result.first->second.Value;
2014 }
2015 
2016 /// Produce a string describing the given constexpr call.
2017 void CallStackFrame::describe(raw_ostream &Out) const {
2018   unsigned ArgIndex = 0;
2019   bool IsMemberCall =
2020       isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
2021       cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
2022 
2023   if (!IsMemberCall)
2024     Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2025                                  /*Qualified=*/false);
2026 
2027   if (This && IsMemberCall) {
2028     if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2029       const Expr *Object = MCE->getImplicitObjectArgument();
2030       Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2031                           /*Indentation=*/0);
2032       if (Object->getType()->isPointerType())
2033           Out << "->";
2034       else
2035           Out << ".";
2036     } else if (const auto *OCE =
2037                    dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2038       OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2039                                   Info.Ctx.getPrintingPolicy(),
2040                                   /*Indentation=*/0);
2041       Out << ".";
2042     } else {
2043       APValue Val;
2044       This->moveInto(Val);
2045       Val.printPretty(
2046           Out, Info.Ctx,
2047           Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2048       Out << ".";
2049     }
2050     Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2051                                  /*Qualified=*/false);
2052     IsMemberCall = false;
2053   }
2054 
2055   Out << '(';
2056 
2057   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2058        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2059     if (ArgIndex > (unsigned)IsMemberCall)
2060       Out << ", ";
2061 
2062     const ParmVarDecl *Param = *I;
2063     APValue *V = Info.getParamSlot(Arguments, Param);
2064     if (V)
2065       V->printPretty(Out, Info.Ctx, Param->getType());
2066     else
2067       Out << "<...>";
2068 
2069     if (ArgIndex == 0 && IsMemberCall)
2070       Out << "->" << *Callee << '(';
2071   }
2072 
2073   Out << ')';
2074 }
2075 
2076 /// Evaluate an expression to see if it had side-effects, and discard its
2077 /// result.
2078 /// \return \c true if the caller should keep evaluating.
2079 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2080   assert(!E->isValueDependent());
2081   APValue Scratch;
2082   if (!Evaluate(Scratch, Info, E))
2083     // We don't need the value, but we might have skipped a side effect here.
2084     return Info.noteSideEffect();
2085   return true;
2086 }
2087 
2088 /// Should this call expression be treated as forming an opaque constant?
2089 static bool IsOpaqueConstantCall(const CallExpr *E) {
2090   unsigned Builtin = E->getBuiltinCallee();
2091   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2092           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2093           Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2094           Builtin == Builtin::BI__builtin_function_start);
2095 }
2096 
2097 static bool IsOpaqueConstantCall(const LValue &LVal) {
2098   const auto *BaseExpr =
2099       llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2100   return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2101 }
2102 
2103 static bool IsGlobalLValue(APValue::LValueBase B) {
2104   // C++11 [expr.const]p3 An address constant expression is a prvalue core
2105   // constant expression of pointer type that evaluates to...
2106 
2107   // ... a null pointer value, or a prvalue core constant expression of type
2108   // std::nullptr_t.
2109   if (!B)
2110     return true;
2111 
2112   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2113     // ... the address of an object with static storage duration,
2114     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2115       return VD->hasGlobalStorage();
2116     if (isa<TemplateParamObjectDecl>(D))
2117       return true;
2118     // ... the address of a function,
2119     // ... the address of a GUID [MS extension],
2120     // ... the address of an unnamed global constant
2121     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2122   }
2123 
2124   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2125     return true;
2126 
2127   const Expr *E = B.get<const Expr*>();
2128   switch (E->getStmtClass()) {
2129   default:
2130     return false;
2131   case Expr::CompoundLiteralExprClass: {
2132     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2133     return CLE->isFileScope() && CLE->isLValue();
2134   }
2135   case Expr::MaterializeTemporaryExprClass:
2136     // A materialized temporary might have been lifetime-extended to static
2137     // storage duration.
2138     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2139   // A string literal has static storage duration.
2140   case Expr::StringLiteralClass:
2141   case Expr::PredefinedExprClass:
2142   case Expr::ObjCStringLiteralClass:
2143   case Expr::ObjCEncodeExprClass:
2144     return true;
2145   case Expr::ObjCBoxedExprClass:
2146     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2147   case Expr::CallExprClass:
2148     return IsOpaqueConstantCall(cast<CallExpr>(E));
2149   // For GCC compatibility, &&label has static storage duration.
2150   case Expr::AddrLabelExprClass:
2151     return true;
2152   // A Block literal expression may be used as the initialization value for
2153   // Block variables at global or local static scope.
2154   case Expr::BlockExprClass:
2155     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2156   // The APValue generated from a __builtin_source_location will be emitted as a
2157   // literal.
2158   case Expr::SourceLocExprClass:
2159     return true;
2160   case Expr::ImplicitValueInitExprClass:
2161     // FIXME:
2162     // We can never form an lvalue with an implicit value initialization as its
2163     // base through expression evaluation, so these only appear in one case: the
2164     // implicit variable declaration we invent when checking whether a constexpr
2165     // constructor can produce a constant expression. We must assume that such
2166     // an expression might be a global lvalue.
2167     return true;
2168   }
2169 }
2170 
2171 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2172   return LVal.Base.dyn_cast<const ValueDecl*>();
2173 }
2174 
2175 // Information about an LValueBase that is some kind of string.
2176 struct LValueBaseString {
2177   std::string ObjCEncodeStorage;
2178   StringRef Bytes;
2179   int CharWidth;
2180 };
2181 
2182 // Gets the lvalue base of LVal as a string.
2183 static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2184                                   LValueBaseString &AsString) {
2185   const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2186   if (!BaseExpr)
2187     return false;
2188 
2189   // For ObjCEncodeExpr, we need to compute and store the string.
2190   if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2191     Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2192                                     AsString.ObjCEncodeStorage);
2193     AsString.Bytes = AsString.ObjCEncodeStorage;
2194     AsString.CharWidth = 1;
2195     return true;
2196   }
2197 
2198   // Otherwise, we have a StringLiteral.
2199   const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2200   if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2201     Lit = PE->getFunctionName();
2202 
2203   if (!Lit)
2204     return false;
2205 
2206   AsString.Bytes = Lit->getBytes();
2207   AsString.CharWidth = Lit->getCharByteWidth();
2208   return true;
2209 }
2210 
2211 // Determine whether two string literals potentially overlap. This will be the
2212 // case if they agree on the values of all the bytes on the overlapping region
2213 // between them.
2214 //
2215 // The overlapping region is the portion of the two string literals that must
2216 // overlap in memory if the pointers actually point to the same address at
2217 // runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2218 // the overlapping region is "cdef\0", which in this case does agree, so the
2219 // strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2220 // "bazbar" + 3, the overlapping region contains all of both strings, so they
2221 // are not potentially overlapping, even though they agree from the given
2222 // addresses onwards.
2223 //
2224 // See open core issue CWG2765 which is discussing the desired rule here.
2225 static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2226                                                     const LValue &LHS,
2227                                                     const LValue &RHS) {
2228   LValueBaseString LHSString, RHSString;
2229   if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2230       !GetLValueBaseAsString(Info, RHS, RHSString))
2231     return false;
2232 
2233   // This is the byte offset to the location of the first character of LHS
2234   // within RHS. We don't need to look at the characters of one string that
2235   // would appear before the start of the other string if they were merged.
2236   CharUnits Offset = RHS.Offset - LHS.Offset;
2237   if (Offset.isNegative())
2238     LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2239   else
2240     RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2241 
2242   bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2243   StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2244   StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2245   int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2246 
2247   // The null terminator isn't included in the string data, so check for it
2248   // manually. If the longer string doesn't have a null terminator where the
2249   // shorter string ends, they aren't potentially overlapping.
2250   for (int NullByte : llvm::seq(ShorterCharWidth)) {
2251     if (Shorter.size() + NullByte >= Longer.size())
2252       break;
2253     if (Longer[Shorter.size() + NullByte])
2254       return false;
2255   }
2256 
2257   // Otherwise, they're potentially overlapping if and only if the overlapping
2258   // region is the same.
2259   return Shorter == Longer.take_front(Shorter.size());
2260 }
2261 
2262 static bool IsWeakLValue(const LValue &Value) {
2263   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2264   return Decl && Decl->isWeak();
2265 }
2266 
2267 static bool isZeroSized(const LValue &Value) {
2268   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2269   if (isa_and_nonnull<VarDecl>(Decl)) {
2270     QualType Ty = Decl->getType();
2271     if (Ty->isArrayType())
2272       return Ty->isIncompleteType() ||
2273              Decl->getASTContext().getTypeSize(Ty) == 0;
2274   }
2275   return false;
2276 }
2277 
2278 static bool HasSameBase(const LValue &A, const LValue &B) {
2279   if (!A.getLValueBase())
2280     return !B.getLValueBase();
2281   if (!B.getLValueBase())
2282     return false;
2283 
2284   if (A.getLValueBase().getOpaqueValue() !=
2285       B.getLValueBase().getOpaqueValue())
2286     return false;
2287 
2288   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2289          A.getLValueVersion() == B.getLValueVersion();
2290 }
2291 
2292 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2293   assert(Base && "no location for a null lvalue");
2294   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2295 
2296   // For a parameter, find the corresponding call stack frame (if it still
2297   // exists), and point at the parameter of the function definition we actually
2298   // invoked.
2299   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2300     unsigned Idx = PVD->getFunctionScopeIndex();
2301     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2302       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2303           F->Arguments.Version == Base.getVersion() && F->Callee &&
2304           Idx < F->Callee->getNumParams()) {
2305         VD = F->Callee->getParamDecl(Idx);
2306         break;
2307       }
2308     }
2309   }
2310 
2311   if (VD)
2312     Info.Note(VD->getLocation(), diag::note_declared_at);
2313   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2314     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2315   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2316     // FIXME: Produce a note for dangling pointers too.
2317     if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2318       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2319                 diag::note_constexpr_dynamic_alloc_here);
2320   }
2321 
2322   // We have no information to show for a typeid(T) object.
2323 }
2324 
2325 enum class CheckEvaluationResultKind {
2326   ConstantExpression,
2327   FullyInitialized,
2328 };
2329 
2330 /// Materialized temporaries that we've already checked to determine if they're
2331 /// initializsed by a constant expression.
2332 using CheckedTemporaries =
2333     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2334 
2335 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2336                                   EvalInfo &Info, SourceLocation DiagLoc,
2337                                   QualType Type, const APValue &Value,
2338                                   ConstantExprKind Kind,
2339                                   const FieldDecl *SubobjectDecl,
2340                                   CheckedTemporaries &CheckedTemps);
2341 
2342 /// Check that this reference or pointer core constant expression is a valid
2343 /// value for an address or reference constant expression. Return true if we
2344 /// can fold this expression, whether or not it's a constant expression.
2345 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2346                                           QualType Type, const LValue &LVal,
2347                                           ConstantExprKind Kind,
2348                                           CheckedTemporaries &CheckedTemps) {
2349   bool IsReferenceType = Type->isReferenceType();
2350 
2351   APValue::LValueBase Base = LVal.getLValueBase();
2352   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2353 
2354   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2355   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2356 
2357   // Additional restrictions apply in a template argument. We only enforce the
2358   // C++20 restrictions here; additional syntactic and semantic restrictions
2359   // are applied elsewhere.
2360   if (isTemplateArgument(Kind)) {
2361     int InvalidBaseKind = -1;
2362     StringRef Ident;
2363     if (Base.is<TypeInfoLValue>())
2364       InvalidBaseKind = 0;
2365     else if (isa_and_nonnull<StringLiteral>(BaseE))
2366       InvalidBaseKind = 1;
2367     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2368              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2369       InvalidBaseKind = 2;
2370     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2371       InvalidBaseKind = 3;
2372       Ident = PE->getIdentKindName();
2373     }
2374 
2375     if (InvalidBaseKind != -1) {
2376       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2377           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2378           << Ident;
2379       return false;
2380     }
2381   }
2382 
2383   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2384       FD && FD->isImmediateFunction()) {
2385     Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2386         << !Type->isAnyPointerType();
2387     Info.Note(FD->getLocation(), diag::note_declared_at);
2388     return false;
2389   }
2390 
2391   // Check that the object is a global. Note that the fake 'this' object we
2392   // manufacture when checking potential constant expressions is conservatively
2393   // assumed to be global here.
2394   if (!IsGlobalLValue(Base)) {
2395     if (Info.getLangOpts().CPlusPlus11) {
2396       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2397           << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2398           << BaseVD;
2399       auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2400       if (VarD && VarD->isConstexpr()) {
2401         // Non-static local constexpr variables have unintuitive semantics:
2402         //   constexpr int a = 1;
2403         //   constexpr const int *p = &a;
2404         // ... is invalid because the address of 'a' is not constant. Suggest
2405         // adding a 'static' in this case.
2406         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2407             << VarD
2408             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2409       } else {
2410         NoteLValueLocation(Info, Base);
2411       }
2412     } else {
2413       Info.FFDiag(Loc);
2414     }
2415     // Don't allow references to temporaries to escape.
2416     return false;
2417   }
2418   assert((Info.checkingPotentialConstantExpression() ||
2419           LVal.getLValueCallIndex() == 0) &&
2420          "have call index for global lvalue");
2421 
2422   if (Base.is<DynamicAllocLValue>()) {
2423     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2424         << IsReferenceType << !Designator.Entries.empty();
2425     NoteLValueLocation(Info, Base);
2426     return false;
2427   }
2428 
2429   if (BaseVD) {
2430     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2431       // Check if this is a thread-local variable.
2432       if (Var->getTLSKind())
2433         // FIXME: Diagnostic!
2434         return false;
2435 
2436       // A dllimport variable never acts like a constant, unless we're
2437       // evaluating a value for use only in name mangling.
2438       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2439         // FIXME: Diagnostic!
2440         return false;
2441 
2442       // In CUDA/HIP device compilation, only device side variables have
2443       // constant addresses.
2444       if (Info.getASTContext().getLangOpts().CUDA &&
2445           Info.getASTContext().getLangOpts().CUDAIsDevice &&
2446           Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2447         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2448              !Var->hasAttr<CUDAConstantAttr>() &&
2449              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2450              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2451             Var->hasAttr<HIPManagedAttr>())
2452           return false;
2453       }
2454     }
2455     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2456       // __declspec(dllimport) must be handled very carefully:
2457       // We must never initialize an expression with the thunk in C++.
2458       // Doing otherwise would allow the same id-expression to yield
2459       // different addresses for the same function in different translation
2460       // units.  However, this means that we must dynamically initialize the
2461       // expression with the contents of the import address table at runtime.
2462       //
2463       // The C language has no notion of ODR; furthermore, it has no notion of
2464       // dynamic initialization.  This means that we are permitted to
2465       // perform initialization with the address of the thunk.
2466       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2467           FD->hasAttr<DLLImportAttr>())
2468         // FIXME: Diagnostic!
2469         return false;
2470     }
2471   } else if (const auto *MTE =
2472                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2473     if (CheckedTemps.insert(MTE).second) {
2474       QualType TempType = getType(Base);
2475       if (TempType.isDestructedType()) {
2476         Info.FFDiag(MTE->getExprLoc(),
2477                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2478             << TempType;
2479         return false;
2480       }
2481 
2482       APValue *V = MTE->getOrCreateValue(false);
2483       assert(V && "evasluation result refers to uninitialised temporary");
2484       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2485                                  Info, MTE->getExprLoc(), TempType, *V, Kind,
2486                                  /*SubobjectDecl=*/nullptr, CheckedTemps))
2487         return false;
2488     }
2489   }
2490 
2491   // Allow address constant expressions to be past-the-end pointers. This is
2492   // an extension: the standard requires them to point to an object.
2493   if (!IsReferenceType)
2494     return true;
2495 
2496   // A reference constant expression must refer to an object.
2497   if (!Base) {
2498     // FIXME: diagnostic
2499     Info.CCEDiag(Loc);
2500     return true;
2501   }
2502 
2503   // Does this refer one past the end of some object?
2504   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2505     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2506       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2507     NoteLValueLocation(Info, Base);
2508   }
2509 
2510   return true;
2511 }
2512 
2513 /// Member pointers are constant expressions unless they point to a
2514 /// non-virtual dllimport member function.
2515 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2516                                                  SourceLocation Loc,
2517                                                  QualType Type,
2518                                                  const APValue &Value,
2519                                                  ConstantExprKind Kind) {
2520   const ValueDecl *Member = Value.getMemberPointerDecl();
2521   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2522   if (!FD)
2523     return true;
2524   if (FD->isImmediateFunction()) {
2525     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2526     Info.Note(FD->getLocation(), diag::note_declared_at);
2527     return false;
2528   }
2529   return isForManglingOnly(Kind) || FD->isVirtual() ||
2530          !FD->hasAttr<DLLImportAttr>();
2531 }
2532 
2533 /// Check that this core constant expression is of literal type, and if not,
2534 /// produce an appropriate diagnostic.
2535 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2536                              const LValue *This = nullptr) {
2537   // The restriction to literal types does not exist in C++23 anymore.
2538   if (Info.getLangOpts().CPlusPlus23)
2539     return true;
2540 
2541   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2542     return true;
2543 
2544   // C++1y: A constant initializer for an object o [...] may also invoke
2545   // constexpr constructors for o and its subobjects even if those objects
2546   // are of non-literal class types.
2547   //
2548   // C++11 missed this detail for aggregates, so classes like this:
2549   //   struct foo_t { union { int i; volatile int j; } u; };
2550   // are not (obviously) initializable like so:
2551   //   __attribute__((__require_constant_initialization__))
2552   //   static const foo_t x = {{0}};
2553   // because "i" is a subobject with non-literal initialization (due to the
2554   // volatile member of the union). See:
2555   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2556   // Therefore, we use the C++1y behavior.
2557   if (This && Info.EvaluatingDecl == This->getLValueBase())
2558     return true;
2559 
2560   // Prvalue constant expressions must be of literal types.
2561   if (Info.getLangOpts().CPlusPlus11)
2562     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2563       << E->getType();
2564   else
2565     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2566   return false;
2567 }
2568 
2569 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2570                                   EvalInfo &Info, SourceLocation DiagLoc,
2571                                   QualType Type, const APValue &Value,
2572                                   ConstantExprKind Kind,
2573                                   const FieldDecl *SubobjectDecl,
2574                                   CheckedTemporaries &CheckedTemps) {
2575   if (!Value.hasValue()) {
2576     if (SubobjectDecl) {
2577       Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2578           << /*(name)*/ 1 << SubobjectDecl;
2579       Info.Note(SubobjectDecl->getLocation(),
2580                 diag::note_constexpr_subobject_declared_here);
2581     } else {
2582       Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2583           << /*of type*/ 0 << Type;
2584     }
2585     return false;
2586   }
2587 
2588   // We allow _Atomic(T) to be initialized from anything that T can be
2589   // initialized from.
2590   if (const AtomicType *AT = Type->getAs<AtomicType>())
2591     Type = AT->getValueType();
2592 
2593   // Core issue 1454: For a literal constant expression of array or class type,
2594   // each subobject of its value shall have been initialized by a constant
2595   // expression.
2596   if (Value.isArray()) {
2597     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2598     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2599       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2600                                  Value.getArrayInitializedElt(I), Kind,
2601                                  SubobjectDecl, CheckedTemps))
2602         return false;
2603     }
2604     if (!Value.hasArrayFiller())
2605       return true;
2606     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2607                                  Value.getArrayFiller(), Kind, SubobjectDecl,
2608                                  CheckedTemps);
2609   }
2610   if (Value.isUnion() && Value.getUnionField()) {
2611     return CheckEvaluationResult(
2612         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2613         Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2614   }
2615   if (Value.isStruct()) {
2616     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2617     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2618       unsigned BaseIndex = 0;
2619       for (const CXXBaseSpecifier &BS : CD->bases()) {
2620         const APValue &BaseValue = Value.getStructBase(BaseIndex);
2621         if (!BaseValue.hasValue()) {
2622           SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2623           Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2624               << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2625           return false;
2626         }
2627         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2628                                    Kind, /*SubobjectDecl=*/nullptr,
2629                                    CheckedTemps))
2630           return false;
2631         ++BaseIndex;
2632       }
2633     }
2634     for (const auto *I : RD->fields()) {
2635       if (I->isUnnamedBitField())
2636         continue;
2637 
2638       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2639                                  Value.getStructField(I->getFieldIndex()), Kind,
2640                                  I, CheckedTemps))
2641         return false;
2642     }
2643   }
2644 
2645   if (Value.isLValue() &&
2646       CERK == CheckEvaluationResultKind::ConstantExpression) {
2647     LValue LVal;
2648     LVal.setFrom(Info.Ctx, Value);
2649     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2650                                          CheckedTemps);
2651   }
2652 
2653   if (Value.isMemberPointer() &&
2654       CERK == CheckEvaluationResultKind::ConstantExpression)
2655     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2656 
2657   // Everything else is fine.
2658   return true;
2659 }
2660 
2661 /// Check that this core constant expression value is a valid value for a
2662 /// constant expression. If not, report an appropriate diagnostic. Does not
2663 /// check that the expression is of literal type.
2664 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2665                                     QualType Type, const APValue &Value,
2666                                     ConstantExprKind Kind) {
2667   // Nothing to check for a constant expression of type 'cv void'.
2668   if (Type->isVoidType())
2669     return true;
2670 
2671   CheckedTemporaries CheckedTemps;
2672   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2673                                Info, DiagLoc, Type, Value, Kind,
2674                                /*SubobjectDecl=*/nullptr, CheckedTemps);
2675 }
2676 
2677 /// Check that this evaluated value is fully-initialized and can be loaded by
2678 /// an lvalue-to-rvalue conversion.
2679 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2680                                   QualType Type, const APValue &Value) {
2681   CheckedTemporaries CheckedTemps;
2682   return CheckEvaluationResult(
2683       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2684       ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2685 }
2686 
2687 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2688 /// "the allocated storage is deallocated within the evaluation".
2689 static bool CheckMemoryLeaks(EvalInfo &Info) {
2690   if (!Info.HeapAllocs.empty()) {
2691     // We can still fold to a constant despite a compile-time memory leak,
2692     // so long as the heap allocation isn't referenced in the result (we check
2693     // that in CheckConstantExpression).
2694     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2695                  diag::note_constexpr_memory_leak)
2696         << unsigned(Info.HeapAllocs.size() - 1);
2697   }
2698   return true;
2699 }
2700 
2701 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2702   // A null base expression indicates a null pointer.  These are always
2703   // evaluatable, and they are false unless the offset is zero.
2704   if (!Value.getLValueBase()) {
2705     // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2706     Result = !Value.getLValueOffset().isZero();
2707     return true;
2708   }
2709 
2710   // We have a non-null base.  These are generally known to be true, but if it's
2711   // a weak declaration it can be null at runtime.
2712   Result = true;
2713   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2714   return !Decl || !Decl->isWeak();
2715 }
2716 
2717 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2718   // TODO: This function should produce notes if it fails.
2719   switch (Val.getKind()) {
2720   case APValue::None:
2721   case APValue::Indeterminate:
2722     return false;
2723   case APValue::Int:
2724     Result = Val.getInt().getBoolValue();
2725     return true;
2726   case APValue::FixedPoint:
2727     Result = Val.getFixedPoint().getBoolValue();
2728     return true;
2729   case APValue::Float:
2730     Result = !Val.getFloat().isZero();
2731     return true;
2732   case APValue::ComplexInt:
2733     Result = Val.getComplexIntReal().getBoolValue() ||
2734              Val.getComplexIntImag().getBoolValue();
2735     return true;
2736   case APValue::ComplexFloat:
2737     Result = !Val.getComplexFloatReal().isZero() ||
2738              !Val.getComplexFloatImag().isZero();
2739     return true;
2740   case APValue::LValue:
2741     return EvalPointerValueAsBool(Val, Result);
2742   case APValue::MemberPointer:
2743     if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2744       return false;
2745     }
2746     Result = Val.getMemberPointerDecl();
2747     return true;
2748   case APValue::Vector:
2749   case APValue::Array:
2750   case APValue::Struct:
2751   case APValue::Union:
2752   case APValue::AddrLabelDiff:
2753     return false;
2754   }
2755 
2756   llvm_unreachable("unknown APValue kind");
2757 }
2758 
2759 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2760                                        EvalInfo &Info) {
2761   assert(!E->isValueDependent());
2762   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2763   APValue Val;
2764   if (!Evaluate(Val, Info, E))
2765     return false;
2766   return HandleConversionToBool(Val, Result);
2767 }
2768 
2769 template<typename T>
2770 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2771                            const T &SrcValue, QualType DestType) {
2772   Info.CCEDiag(E, diag::note_constexpr_overflow)
2773     << SrcValue << DestType;
2774   return Info.noteUndefinedBehavior();
2775 }
2776 
2777 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2778                                  QualType SrcType, const APFloat &Value,
2779                                  QualType DestType, APSInt &Result) {
2780   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2781   // Determine whether we are converting to unsigned or signed.
2782   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2783 
2784   Result = APSInt(DestWidth, !DestSigned);
2785   bool ignored;
2786   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2787       & APFloat::opInvalidOp)
2788     return HandleOverflow(Info, E, Value, DestType);
2789   return true;
2790 }
2791 
2792 /// Get rounding mode to use in evaluation of the specified expression.
2793 ///
2794 /// If rounding mode is unknown at compile time, still try to evaluate the
2795 /// expression. If the result is exact, it does not depend on rounding mode.
2796 /// So return "tonearest" mode instead of "dynamic".
2797 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2798   llvm::RoundingMode RM =
2799       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2800   if (RM == llvm::RoundingMode::Dynamic)
2801     RM = llvm::RoundingMode::NearestTiesToEven;
2802   return RM;
2803 }
2804 
2805 /// Check if the given evaluation result is allowed for constant evaluation.
2806 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2807                                      APFloat::opStatus St) {
2808   // In a constant context, assume that any dynamic rounding mode or FP
2809   // exception state matches the default floating-point environment.
2810   if (Info.InConstantContext)
2811     return true;
2812 
2813   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2814   if ((St & APFloat::opInexact) &&
2815       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2816     // Inexact result means that it depends on rounding mode. If the requested
2817     // mode is dynamic, the evaluation cannot be made in compile time.
2818     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2819     return false;
2820   }
2821 
2822   if ((St != APFloat::opOK) &&
2823       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2824        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2825        FPO.getAllowFEnvAccess())) {
2826     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2827     return false;
2828   }
2829 
2830   if ((St & APFloat::opStatus::opInvalidOp) &&
2831       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2832     // There is no usefully definable result.
2833     Info.FFDiag(E);
2834     return false;
2835   }
2836 
2837   // FIXME: if:
2838   // - evaluation triggered other FP exception, and
2839   // - exception mode is not "ignore", and
2840   // - the expression being evaluated is not a part of global variable
2841   //   initializer,
2842   // the evaluation probably need to be rejected.
2843   return true;
2844 }
2845 
2846 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2847                                    QualType SrcType, QualType DestType,
2848                                    APFloat &Result) {
2849   assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2850           isa<ConvertVectorExpr>(E)) &&
2851          "HandleFloatToFloatCast has been checked with only CastExpr, "
2852          "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2853          "the new expression or address the root cause of this usage.");
2854   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2855   APFloat::opStatus St;
2856   APFloat Value = Result;
2857   bool ignored;
2858   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2859   return checkFloatingPointResult(Info, E, St);
2860 }
2861 
2862 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2863                                  QualType DestType, QualType SrcType,
2864                                  const APSInt &Value) {
2865   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2866   // Figure out if this is a truncate, extend or noop cast.
2867   // If the input is signed, do a sign extend, noop, or truncate.
2868   APSInt Result = Value.extOrTrunc(DestWidth);
2869   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2870   if (DestType->isBooleanType())
2871     Result = Value.getBoolValue();
2872   return Result;
2873 }
2874 
2875 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2876                                  const FPOptions FPO,
2877                                  QualType SrcType, const APSInt &Value,
2878                                  QualType DestType, APFloat &Result) {
2879   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2880   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2881   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2882   return checkFloatingPointResult(Info, E, St);
2883 }
2884 
2885 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2886                                   APValue &Value, const FieldDecl *FD) {
2887   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2888 
2889   if (!Value.isInt()) {
2890     // Trying to store a pointer-cast-to-integer into a bitfield.
2891     // FIXME: In this case, we should provide the diagnostic for casting
2892     // a pointer to an integer.
2893     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2894     Info.FFDiag(E);
2895     return false;
2896   }
2897 
2898   APSInt &Int = Value.getInt();
2899   unsigned OldBitWidth = Int.getBitWidth();
2900   unsigned NewBitWidth = FD->getBitWidthValue();
2901   if (NewBitWidth < OldBitWidth)
2902     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2903   return true;
2904 }
2905 
2906 /// Perform the given integer operation, which is known to need at most BitWidth
2907 /// bits, and check for overflow in the original type (if that type was not an
2908 /// unsigned type).
2909 template<typename Operation>
2910 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2911                                  const APSInt &LHS, const APSInt &RHS,
2912                                  unsigned BitWidth, Operation Op,
2913                                  APSInt &Result) {
2914   if (LHS.isUnsigned()) {
2915     Result = Op(LHS, RHS);
2916     return true;
2917   }
2918 
2919   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2920   Result = Value.trunc(LHS.getBitWidth());
2921   if (Result.extend(BitWidth) != Value) {
2922     if (Info.checkingForUndefinedBehavior())
2923       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2924                                        diag::warn_integer_constant_overflow)
2925           << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2926                       /*UpperCase=*/true, /*InsertSeparators=*/true)
2927           << E->getType() << E->getSourceRange();
2928     return HandleOverflow(Info, E, Value, E->getType());
2929   }
2930   return true;
2931 }
2932 
2933 /// Perform the given binary integer operation.
2934 static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2935                               const APSInt &LHS, BinaryOperatorKind Opcode,
2936                               APSInt RHS, APSInt &Result) {
2937   bool HandleOverflowResult = true;
2938   switch (Opcode) {
2939   default:
2940     Info.FFDiag(E);
2941     return false;
2942   case BO_Mul:
2943     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2944                                 std::multiplies<APSInt>(), Result);
2945   case BO_Add:
2946     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2947                                 std::plus<APSInt>(), Result);
2948   case BO_Sub:
2949     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2950                                 std::minus<APSInt>(), Result);
2951   case BO_And: Result = LHS & RHS; return true;
2952   case BO_Xor: Result = LHS ^ RHS; return true;
2953   case BO_Or:  Result = LHS | RHS; return true;
2954   case BO_Div:
2955   case BO_Rem:
2956     if (RHS == 0) {
2957       Info.FFDiag(E, diag::note_expr_divide_by_zero)
2958           << E->getRHS()->getSourceRange();
2959       return false;
2960     }
2961     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2962     // this operation and gives the two's complement result.
2963     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2964         LHS.isMinSignedValue())
2965       HandleOverflowResult = HandleOverflow(
2966           Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2967     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2968     return HandleOverflowResult;
2969   case BO_Shl: {
2970     if (Info.getLangOpts().OpenCL)
2971       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2972       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2973                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2974                     RHS.isUnsigned());
2975     else if (RHS.isSigned() && RHS.isNegative()) {
2976       // During constant-folding, a negative shift is an opposite shift. Such
2977       // a shift is not a constant expression.
2978       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2979       if (!Info.noteUndefinedBehavior())
2980         return false;
2981       RHS = -RHS;
2982       goto shift_right;
2983     }
2984   shift_left:
2985     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2986     // the shifted type.
2987     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2988     if (SA != RHS) {
2989       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2990         << RHS << E->getType() << LHS.getBitWidth();
2991       if (!Info.noteUndefinedBehavior())
2992         return false;
2993     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2994       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2995       // operand, and must not overflow the corresponding unsigned type.
2996       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2997       // E1 x 2^E2 module 2^N.
2998       if (LHS.isNegative()) {
2999         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
3000         if (!Info.noteUndefinedBehavior())
3001           return false;
3002       } else if (LHS.countl_zero() < SA) {
3003         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
3004         if (!Info.noteUndefinedBehavior())
3005           return false;
3006       }
3007     }
3008     Result = LHS << SA;
3009     return true;
3010   }
3011   case BO_Shr: {
3012     if (Info.getLangOpts().OpenCL)
3013       // OpenCL 6.3j: shift values are effectively % word size of LHS.
3014       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
3015                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
3016                     RHS.isUnsigned());
3017     else if (RHS.isSigned() && RHS.isNegative()) {
3018       // During constant-folding, a negative shift is an opposite shift. Such a
3019       // shift is not a constant expression.
3020       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
3021       if (!Info.noteUndefinedBehavior())
3022         return false;
3023       RHS = -RHS;
3024       goto shift_left;
3025     }
3026   shift_right:
3027     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3028     // shifted type.
3029     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3030     if (SA != RHS) {
3031       Info.CCEDiag(E, diag::note_constexpr_large_shift)
3032         << RHS << E->getType() << LHS.getBitWidth();
3033       if (!Info.noteUndefinedBehavior())
3034         return false;
3035     }
3036 
3037     Result = LHS >> SA;
3038     return true;
3039   }
3040 
3041   case BO_LT: Result = LHS < RHS; return true;
3042   case BO_GT: Result = LHS > RHS; return true;
3043   case BO_LE: Result = LHS <= RHS; return true;
3044   case BO_GE: Result = LHS >= RHS; return true;
3045   case BO_EQ: Result = LHS == RHS; return true;
3046   case BO_NE: Result = LHS != RHS; return true;
3047   case BO_Cmp:
3048     llvm_unreachable("BO_Cmp should be handled elsewhere");
3049   }
3050 }
3051 
3052 /// Perform the given binary floating-point operation, in-place, on LHS.
3053 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3054                                   APFloat &LHS, BinaryOperatorKind Opcode,
3055                                   const APFloat &RHS) {
3056   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3057   APFloat::opStatus St;
3058   switch (Opcode) {
3059   default:
3060     Info.FFDiag(E);
3061     return false;
3062   case BO_Mul:
3063     St = LHS.multiply(RHS, RM);
3064     break;
3065   case BO_Add:
3066     St = LHS.add(RHS, RM);
3067     break;
3068   case BO_Sub:
3069     St = LHS.subtract(RHS, RM);
3070     break;
3071   case BO_Div:
3072     // [expr.mul]p4:
3073     //   If the second operand of / or % is zero the behavior is undefined.
3074     if (RHS.isZero())
3075       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3076     St = LHS.divide(RHS, RM);
3077     break;
3078   }
3079 
3080   // [expr.pre]p4:
3081   //   If during the evaluation of an expression, the result is not
3082   //   mathematically defined [...], the behavior is undefined.
3083   // FIXME: C++ rules require us to not conform to IEEE 754 here.
3084   if (LHS.isNaN()) {
3085     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3086     return Info.noteUndefinedBehavior();
3087   }
3088 
3089   return checkFloatingPointResult(Info, E, St);
3090 }
3091 
3092 static bool handleLogicalOpForVector(const APInt &LHSValue,
3093                                      BinaryOperatorKind Opcode,
3094                                      const APInt &RHSValue, APInt &Result) {
3095   bool LHS = (LHSValue != 0);
3096   bool RHS = (RHSValue != 0);
3097 
3098   if (Opcode == BO_LAnd)
3099     Result = LHS && RHS;
3100   else
3101     Result = LHS || RHS;
3102   return true;
3103 }
3104 static bool handleLogicalOpForVector(const APFloat &LHSValue,
3105                                      BinaryOperatorKind Opcode,
3106                                      const APFloat &RHSValue, APInt &Result) {
3107   bool LHS = !LHSValue.isZero();
3108   bool RHS = !RHSValue.isZero();
3109 
3110   if (Opcode == BO_LAnd)
3111     Result = LHS && RHS;
3112   else
3113     Result = LHS || RHS;
3114   return true;
3115 }
3116 
3117 static bool handleLogicalOpForVector(const APValue &LHSValue,
3118                                      BinaryOperatorKind Opcode,
3119                                      const APValue &RHSValue, APInt &Result) {
3120   // The result is always an int type, however operands match the first.
3121   if (LHSValue.getKind() == APValue::Int)
3122     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3123                                     RHSValue.getInt(), Result);
3124   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3125   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3126                                   RHSValue.getFloat(), Result);
3127 }
3128 
3129 template <typename APTy>
3130 static bool
3131 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
3132                                const APTy &RHSValue, APInt &Result) {
3133   switch (Opcode) {
3134   default:
3135     llvm_unreachable("unsupported binary operator");
3136   case BO_EQ:
3137     Result = (LHSValue == RHSValue);
3138     break;
3139   case BO_NE:
3140     Result = (LHSValue != RHSValue);
3141     break;
3142   case BO_LT:
3143     Result = (LHSValue < RHSValue);
3144     break;
3145   case BO_GT:
3146     Result = (LHSValue > RHSValue);
3147     break;
3148   case BO_LE:
3149     Result = (LHSValue <= RHSValue);
3150     break;
3151   case BO_GE:
3152     Result = (LHSValue >= RHSValue);
3153     break;
3154   }
3155 
3156   // The boolean operations on these vector types use an instruction that
3157   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
3158   // to -1 to make sure that we produce the correct value.
3159   Result.negate();
3160 
3161   return true;
3162 }
3163 
3164 static bool handleCompareOpForVector(const APValue &LHSValue,
3165                                      BinaryOperatorKind Opcode,
3166                                      const APValue &RHSValue, APInt &Result) {
3167   // The result is always an int type, however operands match the first.
3168   if (LHSValue.getKind() == APValue::Int)
3169     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3170                                           RHSValue.getInt(), Result);
3171   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3172   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3173                                         RHSValue.getFloat(), Result);
3174 }
3175 
3176 // Perform binary operations for vector types, in place on the LHS.
3177 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3178                                     BinaryOperatorKind Opcode,
3179                                     APValue &LHSValue,
3180                                     const APValue &RHSValue) {
3181   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3182          "Operation not supported on vector types");
3183 
3184   const auto *VT = E->getType()->castAs<VectorType>();
3185   unsigned NumElements = VT->getNumElements();
3186   QualType EltTy = VT->getElementType();
3187 
3188   // In the cases (typically C as I've observed) where we aren't evaluating
3189   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3190   // just give up.
3191   if (!LHSValue.isVector()) {
3192     assert(LHSValue.isLValue() &&
3193            "A vector result that isn't a vector OR uncalculated LValue");
3194     Info.FFDiag(E);
3195     return false;
3196   }
3197 
3198   assert(LHSValue.getVectorLength() == NumElements &&
3199          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3200 
3201   SmallVector<APValue, 4> ResultElements;
3202 
3203   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3204     APValue LHSElt = LHSValue.getVectorElt(EltNum);
3205     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3206 
3207     if (EltTy->isIntegerType()) {
3208       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3209                        EltTy->isUnsignedIntegerType()};
3210       bool Success = true;
3211 
3212       if (BinaryOperator::isLogicalOp(Opcode))
3213         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3214       else if (BinaryOperator::isComparisonOp(Opcode))
3215         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3216       else
3217         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3218                                     RHSElt.getInt(), EltResult);
3219 
3220       if (!Success) {
3221         Info.FFDiag(E);
3222         return false;
3223       }
3224       ResultElements.emplace_back(EltResult);
3225 
3226     } else if (EltTy->isFloatingType()) {
3227       assert(LHSElt.getKind() == APValue::Float &&
3228              RHSElt.getKind() == APValue::Float &&
3229              "Mismatched LHS/RHS/Result Type");
3230       APFloat LHSFloat = LHSElt.getFloat();
3231 
3232       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3233                                  RHSElt.getFloat())) {
3234         Info.FFDiag(E);
3235         return false;
3236       }
3237 
3238       ResultElements.emplace_back(LHSFloat);
3239     }
3240   }
3241 
3242   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3243   return true;
3244 }
3245 
3246 /// Cast an lvalue referring to a base subobject to a derived class, by
3247 /// truncating the lvalue's path to the given length.
3248 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3249                                const RecordDecl *TruncatedType,
3250                                unsigned TruncatedElements) {
3251   SubobjectDesignator &D = Result.Designator;
3252 
3253   // Check we actually point to a derived class object.
3254   if (TruncatedElements == D.Entries.size())
3255     return true;
3256   assert(TruncatedElements >= D.MostDerivedPathLength &&
3257          "not casting to a derived class");
3258   if (!Result.checkSubobject(Info, E, CSK_Derived))
3259     return false;
3260 
3261   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3262   const RecordDecl *RD = TruncatedType;
3263   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3264     if (RD->isInvalidDecl()) return false;
3265     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3266     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3267     if (isVirtualBaseClass(D.Entries[I]))
3268       Result.Offset -= Layout.getVBaseClassOffset(Base);
3269     else
3270       Result.Offset -= Layout.getBaseClassOffset(Base);
3271     RD = Base;
3272   }
3273   D.Entries.resize(TruncatedElements);
3274   return true;
3275 }
3276 
3277 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3278                                    const CXXRecordDecl *Derived,
3279                                    const CXXRecordDecl *Base,
3280                                    const ASTRecordLayout *RL = nullptr) {
3281   if (!RL) {
3282     if (Derived->isInvalidDecl()) return false;
3283     RL = &Info.Ctx.getASTRecordLayout(Derived);
3284   }
3285 
3286   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3287   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3288   return true;
3289 }
3290 
3291 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3292                              const CXXRecordDecl *DerivedDecl,
3293                              const CXXBaseSpecifier *Base) {
3294   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3295 
3296   if (!Base->isVirtual())
3297     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3298 
3299   SubobjectDesignator &D = Obj.Designator;
3300   if (D.Invalid)
3301     return false;
3302 
3303   // Extract most-derived object and corresponding type.
3304   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3305   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3306     return false;
3307 
3308   // Find the virtual base class.
3309   if (DerivedDecl->isInvalidDecl()) return false;
3310   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3311   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3312   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3313   return true;
3314 }
3315 
3316 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3317                                  QualType Type, LValue &Result) {
3318   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3319                                      PathE = E->path_end();
3320        PathI != PathE; ++PathI) {
3321     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3322                           *PathI))
3323       return false;
3324     Type = (*PathI)->getType();
3325   }
3326   return true;
3327 }
3328 
3329 /// Cast an lvalue referring to a derived class to a known base subobject.
3330 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3331                             const CXXRecordDecl *DerivedRD,
3332                             const CXXRecordDecl *BaseRD) {
3333   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3334                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3335   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3336     llvm_unreachable("Class must be derived from the passed in base class!");
3337 
3338   for (CXXBasePathElement &Elem : Paths.front())
3339     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3340       return false;
3341   return true;
3342 }
3343 
3344 /// Update LVal to refer to the given field, which must be a member of the type
3345 /// currently described by LVal.
3346 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3347                                const FieldDecl *FD,
3348                                const ASTRecordLayout *RL = nullptr) {
3349   if (!RL) {
3350     if (FD->getParent()->isInvalidDecl()) return false;
3351     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3352   }
3353 
3354   unsigned I = FD->getFieldIndex();
3355   LVal.addDecl(Info, E, FD);
3356   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3357   return true;
3358 }
3359 
3360 /// Update LVal to refer to the given indirect field.
3361 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3362                                        LValue &LVal,
3363                                        const IndirectFieldDecl *IFD) {
3364   for (const auto *C : IFD->chain())
3365     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3366       return false;
3367   return true;
3368 }
3369 
3370 enum class SizeOfType {
3371   SizeOf,
3372   DataSizeOf,
3373 };
3374 
3375 /// Get the size of the given type in char units.
3376 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3377                          CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3378   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3379   // extension.
3380   if (Type->isVoidType() || Type->isFunctionType()) {
3381     Size = CharUnits::One();
3382     return true;
3383   }
3384 
3385   if (Type->isDependentType()) {
3386     Info.FFDiag(Loc);
3387     return false;
3388   }
3389 
3390   if (!Type->isConstantSizeType()) {
3391     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3392     // FIXME: Better diagnostic.
3393     Info.FFDiag(Loc);
3394     return false;
3395   }
3396 
3397   if (SOT == SizeOfType::SizeOf)
3398     Size = Info.Ctx.getTypeSizeInChars(Type);
3399   else
3400     Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3401   return true;
3402 }
3403 
3404 /// Update a pointer value to model pointer arithmetic.
3405 /// \param Info - Information about the ongoing evaluation.
3406 /// \param E - The expression being evaluated, for diagnostic purposes.
3407 /// \param LVal - The pointer value to be updated.
3408 /// \param EltTy - The pointee type represented by LVal.
3409 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3410 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3411                                         LValue &LVal, QualType EltTy,
3412                                         APSInt Adjustment) {
3413   CharUnits SizeOfPointee;
3414   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3415     return false;
3416 
3417   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3418   return true;
3419 }
3420 
3421 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3422                                         LValue &LVal, QualType EltTy,
3423                                         int64_t Adjustment) {
3424   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3425                                      APSInt::get(Adjustment));
3426 }
3427 
3428 /// Update an lvalue to refer to a component of a complex number.
3429 /// \param Info - Information about the ongoing evaluation.
3430 /// \param LVal - The lvalue to be updated.
3431 /// \param EltTy - The complex number's component type.
3432 /// \param Imag - False for the real component, true for the imaginary.
3433 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3434                                        LValue &LVal, QualType EltTy,
3435                                        bool Imag) {
3436   if (Imag) {
3437     CharUnits SizeOfComponent;
3438     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3439       return false;
3440     LVal.Offset += SizeOfComponent;
3441   }
3442   LVal.addComplex(Info, E, EltTy, Imag);
3443   return true;
3444 }
3445 
3446 static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3447                                       LValue &LVal, QualType EltTy,
3448                                       uint64_t Size, uint64_t Idx) {
3449   if (Idx) {
3450     CharUnits SizeOfElement;
3451     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3452       return false;
3453     LVal.Offset += SizeOfElement * Idx;
3454   }
3455   LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3456   return true;
3457 }
3458 
3459 /// Try to evaluate the initializer for a variable declaration.
3460 ///
3461 /// \param Info   Information about the ongoing evaluation.
3462 /// \param E      An expression to be used when printing diagnostics.
3463 /// \param VD     The variable whose initializer should be obtained.
3464 /// \param Version The version of the variable within the frame.
3465 /// \param Frame  The frame in which the variable was created. Must be null
3466 ///               if this variable is not local to the evaluation.
3467 /// \param Result Filled in with a pointer to the value of the variable.
3468 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3469                                 const VarDecl *VD, CallStackFrame *Frame,
3470                                 unsigned Version, APValue *&Result) {
3471   // C++23 [expr.const]p8 If we have a reference type allow unknown references
3472   // and pointers.
3473   bool AllowConstexprUnknown =
3474       Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3475 
3476   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3477 
3478   // If this is a local variable, dig out its value.
3479   if (Frame) {
3480     Result = Frame->getTemporary(VD, Version);
3481     if (Result)
3482       return true;
3483 
3484     if (!isa<ParmVarDecl>(VD)) {
3485       // Assume variables referenced within a lambda's call operator that were
3486       // not declared within the call operator are captures and during checking
3487       // of a potential constant expression, assume they are unknown constant
3488       // expressions.
3489       assert(isLambdaCallOperator(Frame->Callee) &&
3490              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3491              "missing value for local variable");
3492       if (Info.checkingPotentialConstantExpression())
3493         return false;
3494       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3495       // still reachable at all?
3496       Info.FFDiag(E->getBeginLoc(),
3497                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3498           << "captures not currently allowed";
3499       return false;
3500     }
3501   }
3502 
3503   // If we're currently evaluating the initializer of this declaration, use that
3504   // in-flight value.
3505   if (Info.EvaluatingDecl == Base) {
3506     Result = Info.EvaluatingDeclValue;
3507     return true;
3508   }
3509 
3510   // P2280R4 struck the restriction that variable of reference type lifetime
3511   // should begin within the evaluation of E
3512   // Used to be C++20 [expr.const]p5.12.2:
3513   // ... its lifetime began within the evaluation of E;
3514   if (isa<ParmVarDecl>(VD) && !AllowConstexprUnknown) {
3515     // Assume parameters of a potential constant expression are usable in
3516     // constant expressions.
3517     if (!Info.checkingPotentialConstantExpression() ||
3518         !Info.CurrentCall->Callee ||
3519         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3520       if (Info.getLangOpts().CPlusPlus11) {
3521         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3522             << VD;
3523         NoteLValueLocation(Info, Base);
3524       } else {
3525         Info.FFDiag(E);
3526       }
3527     }
3528     return false;
3529   }
3530 
3531   if (E->isValueDependent())
3532     return false;
3533 
3534   // Dig out the initializer, and use the declaration which it's attached to.
3535   // FIXME: We should eventually check whether the variable has a reachable
3536   // initializing declaration.
3537   const Expr *Init = VD->getAnyInitializer(VD);
3538   // P2280R4 struck the restriction that variable of reference type should have
3539   // a preceding initialization.
3540   // Used to be C++20 [expr.const]p5.12:
3541   //   ... reference has a preceding initialization and either ...
3542   if (!Init && !AllowConstexprUnknown) {
3543     // Don't diagnose during potential constant expression checking; an
3544     // initializer might be added later.
3545     if (!Info.checkingPotentialConstantExpression()) {
3546       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3547         << VD;
3548       NoteLValueLocation(Info, Base);
3549     }
3550     return false;
3551   }
3552 
3553   // P2280R4 struck the initialization requirement for variables of reference
3554   // type so we can no longer assume we have an Init.
3555   // Used to be C++20 [expr.const]p5.12:
3556   //  ... reference has a preceding initialization and either ...
3557   if (Init && Init->isValueDependent()) {
3558     // The DeclRefExpr is not value-dependent, but the variable it refers to
3559     // has a value-dependent initializer. This should only happen in
3560     // constant-folding cases, where the variable is not actually of a suitable
3561     // type for use in a constant expression (otherwise the DeclRefExpr would
3562     // have been value-dependent too), so diagnose that.
3563     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3564     if (!Info.checkingPotentialConstantExpression()) {
3565       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3566                          ? diag::note_constexpr_ltor_non_constexpr
3567                          : diag::note_constexpr_ltor_non_integral, 1)
3568           << VD << VD->getType();
3569       NoteLValueLocation(Info, Base);
3570     }
3571     return false;
3572   }
3573 
3574   // Check that we can fold the initializer. In C++, we will have already done
3575   // this in the cases where it matters for conformance.
3576   // P2280R4 struck the initialization requirement for variables of reference
3577   // type so we can no longer assume we have an Init.
3578   // Used to be C++20 [expr.const]p5.12:
3579   //  ... reference has a preceding initialization and either ...
3580   if (Init && !VD->evaluateValue()) {
3581     if (AllowConstexprUnknown) {
3582       Result = &Info.CurrentCall->createConstexprUnknownAPValues(VD, Base);
3583       return true;
3584     }
3585     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3586     NoteLValueLocation(Info, Base);
3587     return false;
3588   }
3589 
3590   // Check that the variable is actually usable in constant expressions. For a
3591   // const integral variable or a reference, we might have a non-constant
3592   // initializer that we can nonetheless evaluate the initializer for. Such
3593   // variables are not usable in constant expressions. In C++98, the
3594   // initializer also syntactically needs to be an ICE.
3595   //
3596   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3597   // expressions here; doing so would regress diagnostics for things like
3598   // reading from a volatile constexpr variable.
3599   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3600        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3601       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3602        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3603     if (Init) {
3604       Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3605       NoteLValueLocation(Info, Base);
3606     } else {
3607       Info.CCEDiag(E);
3608     }
3609   }
3610 
3611   // Never use the initializer of a weak variable, not even for constant
3612   // folding. We can't be sure that this is the definition that will be used.
3613   if (VD->isWeak()) {
3614     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3615     NoteLValueLocation(Info, Base);
3616     return false;
3617   }
3618 
3619   Result = VD->getEvaluatedValue();
3620 
3621   // C++23 [expr.const]p8
3622   // ... For such an object that is not usable in constant expressions, the
3623   // dynamic type of the object is constexpr-unknown. For such a reference that
3624   // is not usable in constant expressions, the reference is treated as binding
3625   // to an unspecified object of the referenced type whose lifetime and that of
3626   // all subobjects includes the entire constant evaluation and whose dynamic
3627   // type is constexpr-unknown.
3628   if (AllowConstexprUnknown) {
3629     if (!Result)
3630       Result = &Info.CurrentCall->createConstexprUnknownAPValues(VD, Base);
3631     else
3632       Result->setConstexprUnknown();
3633   }
3634   return true;
3635 }
3636 
3637 /// Get the base index of the given base class within an APValue representing
3638 /// the given derived class.
3639 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3640                              const CXXRecordDecl *Base) {
3641   Base = Base->getCanonicalDecl();
3642   unsigned Index = 0;
3643   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3644          E = Derived->bases_end(); I != E; ++I, ++Index) {
3645     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3646       return Index;
3647   }
3648 
3649   llvm_unreachable("base class missing from derived class's bases list");
3650 }
3651 
3652 /// Extract the value of a character from a string literal.
3653 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3654                                             uint64_t Index) {
3655   assert(!isa<SourceLocExpr>(Lit) &&
3656          "SourceLocExpr should have already been converted to a StringLiteral");
3657 
3658   // FIXME: Support MakeStringConstant
3659   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3660     std::string Str;
3661     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3662     assert(Index <= Str.size() && "Index too large");
3663     return APSInt::getUnsigned(Str.c_str()[Index]);
3664   }
3665 
3666   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3667     Lit = PE->getFunctionName();
3668   const StringLiteral *S = cast<StringLiteral>(Lit);
3669   const ConstantArrayType *CAT =
3670       Info.Ctx.getAsConstantArrayType(S->getType());
3671   assert(CAT && "string literal isn't an array");
3672   QualType CharType = CAT->getElementType();
3673   assert(CharType->isIntegerType() && "unexpected character type");
3674   APSInt Value(Info.Ctx.getTypeSize(CharType),
3675                CharType->isUnsignedIntegerType());
3676   if (Index < S->getLength())
3677     Value = S->getCodeUnit(Index);
3678   return Value;
3679 }
3680 
3681 // Expand a string literal into an array of characters.
3682 //
3683 // FIXME: This is inefficient; we should probably introduce something similar
3684 // to the LLVM ConstantDataArray to make this cheaper.
3685 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3686                                 APValue &Result,
3687                                 QualType AllocType = QualType()) {
3688   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3689       AllocType.isNull() ? S->getType() : AllocType);
3690   assert(CAT && "string literal isn't an array");
3691   QualType CharType = CAT->getElementType();
3692   assert(CharType->isIntegerType() && "unexpected character type");
3693 
3694   unsigned Elts = CAT->getZExtSize();
3695   Result = APValue(APValue::UninitArray(),
3696                    std::min(S->getLength(), Elts), Elts);
3697   APSInt Value(Info.Ctx.getTypeSize(CharType),
3698                CharType->isUnsignedIntegerType());
3699   if (Result.hasArrayFiller())
3700     Result.getArrayFiller() = APValue(Value);
3701   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3702     Value = S->getCodeUnit(I);
3703     Result.getArrayInitializedElt(I) = APValue(Value);
3704   }
3705 }
3706 
3707 // Expand an array so that it has more than Index filled elements.
3708 static void expandArray(APValue &Array, unsigned Index) {
3709   unsigned Size = Array.getArraySize();
3710   assert(Index < Size);
3711 
3712   // Always at least double the number of elements for which we store a value.
3713   unsigned OldElts = Array.getArrayInitializedElts();
3714   unsigned NewElts = std::max(Index+1, OldElts * 2);
3715   NewElts = std::min(Size, std::max(NewElts, 8u));
3716 
3717   // Copy the data across.
3718   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3719   for (unsigned I = 0; I != OldElts; ++I)
3720     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3721   for (unsigned I = OldElts; I != NewElts; ++I)
3722     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3723   if (NewValue.hasArrayFiller())
3724     NewValue.getArrayFiller() = Array.getArrayFiller();
3725   Array.swap(NewValue);
3726 }
3727 
3728 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3729 /// conversion. If it's of class type, we may assume that the copy operation
3730 /// is trivial. Note that this is never true for a union type with fields
3731 /// (because the copy always "reads" the active member) and always true for
3732 /// a non-class type.
3733 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3734 static bool isReadByLvalueToRvalueConversion(QualType T) {
3735   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3736   return !RD || isReadByLvalueToRvalueConversion(RD);
3737 }
3738 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3739   // FIXME: A trivial copy of a union copies the object representation, even if
3740   // the union is empty.
3741   if (RD->isUnion())
3742     return !RD->field_empty();
3743   if (RD->isEmpty())
3744     return false;
3745 
3746   for (auto *Field : RD->fields())
3747     if (!Field->isUnnamedBitField() &&
3748         isReadByLvalueToRvalueConversion(Field->getType()))
3749       return true;
3750 
3751   for (auto &BaseSpec : RD->bases())
3752     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3753       return true;
3754 
3755   return false;
3756 }
3757 
3758 /// Diagnose an attempt to read from any unreadable field within the specified
3759 /// type, which might be a class type.
3760 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3761                                   QualType T) {
3762   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3763   if (!RD)
3764     return false;
3765 
3766   if (!RD->hasMutableFields())
3767     return false;
3768 
3769   for (auto *Field : RD->fields()) {
3770     // If we're actually going to read this field in some way, then it can't
3771     // be mutable. If we're in a union, then assigning to a mutable field
3772     // (even an empty one) can change the active member, so that's not OK.
3773     // FIXME: Add core issue number for the union case.
3774     if (Field->isMutable() &&
3775         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3776       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3777       Info.Note(Field->getLocation(), diag::note_declared_at);
3778       return true;
3779     }
3780 
3781     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3782       return true;
3783   }
3784 
3785   for (auto &BaseSpec : RD->bases())
3786     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3787       return true;
3788 
3789   // All mutable fields were empty, and thus not actually read.
3790   return false;
3791 }
3792 
3793 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3794                                         APValue::LValueBase Base,
3795                                         bool MutableSubobject = false) {
3796   // A temporary or transient heap allocation we created.
3797   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3798     return true;
3799 
3800   switch (Info.IsEvaluatingDecl) {
3801   case EvalInfo::EvaluatingDeclKind::None:
3802     return false;
3803 
3804   case EvalInfo::EvaluatingDeclKind::Ctor:
3805     // The variable whose initializer we're evaluating.
3806     if (Info.EvaluatingDecl == Base)
3807       return true;
3808 
3809     // A temporary lifetime-extended by the variable whose initializer we're
3810     // evaluating.
3811     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3812       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3813         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3814     return false;
3815 
3816   case EvalInfo::EvaluatingDeclKind::Dtor:
3817     // C++2a [expr.const]p6:
3818     //   [during constant destruction] the lifetime of a and its non-mutable
3819     //   subobjects (but not its mutable subobjects) [are] considered to start
3820     //   within e.
3821     if (MutableSubobject || Base != Info.EvaluatingDecl)
3822       return false;
3823     // FIXME: We can meaningfully extend this to cover non-const objects, but
3824     // we will need special handling: we should be able to access only
3825     // subobjects of such objects that are themselves declared const.
3826     QualType T = getType(Base);
3827     return T.isConstQualified() || T->isReferenceType();
3828   }
3829 
3830   llvm_unreachable("unknown evaluating decl kind");
3831 }
3832 
3833 static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3834                            SourceLocation CallLoc = {}) {
3835   return Info.CheckArraySize(
3836       CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3837       CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3838       /*Diag=*/true);
3839 }
3840 
3841 namespace {
3842 /// A handle to a complete object (an object that is not a subobject of
3843 /// another object).
3844 struct CompleteObject {
3845   /// The identity of the object.
3846   APValue::LValueBase Base;
3847   /// The value of the complete object.
3848   APValue *Value;
3849   /// The type of the complete object.
3850   QualType Type;
3851 
3852   CompleteObject() : Value(nullptr) {}
3853   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3854       : Base(Base), Value(Value), Type(Type) {}
3855 
3856   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3857     // If this isn't a "real" access (eg, if it's just accessing the type
3858     // info), allow it. We assume the type doesn't change dynamically for
3859     // subobjects of constexpr objects (even though we'd hit UB here if it
3860     // did). FIXME: Is this right?
3861     if (!isAnyAccess(AK))
3862       return true;
3863 
3864     // In C++14 onwards, it is permitted to read a mutable member whose
3865     // lifetime began within the evaluation.
3866     // FIXME: Should we also allow this in C++11?
3867     if (!Info.getLangOpts().CPlusPlus14 &&
3868         AK != AccessKinds::AK_IsWithinLifetime)
3869       return false;
3870     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3871   }
3872 
3873   explicit operator bool() const { return !Type.isNull(); }
3874 };
3875 } // end anonymous namespace
3876 
3877 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3878                                  bool IsMutable = false) {
3879   // C++ [basic.type.qualifier]p1:
3880   // - A const object is an object of type const T or a non-mutable subobject
3881   //   of a const object.
3882   if (ObjType.isConstQualified() && !IsMutable)
3883     SubobjType.addConst();
3884   // - A volatile object is an object of type const T or a subobject of a
3885   //   volatile object.
3886   if (ObjType.isVolatileQualified())
3887     SubobjType.addVolatile();
3888   return SubobjType;
3889 }
3890 
3891 /// Find the designated sub-object of an rvalue.
3892 template <typename SubobjectHandler>
3893 static typename SubobjectHandler::result_type
3894 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3895               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3896   if (Sub.Invalid)
3897     // A diagnostic will have already been produced.
3898     return handler.failed();
3899   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3900     if (Info.getLangOpts().CPlusPlus11)
3901       Info.FFDiag(E, Sub.isOnePastTheEnd()
3902                          ? diag::note_constexpr_access_past_end
3903                          : diag::note_constexpr_access_unsized_array)
3904           << handler.AccessKind;
3905     else
3906       Info.FFDiag(E);
3907     return handler.failed();
3908   }
3909 
3910   APValue *O = Obj.Value;
3911   QualType ObjType = Obj.Type;
3912   const FieldDecl *LastField = nullptr;
3913   const FieldDecl *VolatileField = nullptr;
3914 
3915   // C++23 [expr.const]p8 If we have an unknown reference or pointers and it
3916   // does not have a value then bail out.
3917   if (O->allowConstexprUnknown() && !O->hasValue())
3918     return false;
3919 
3920   // Walk the designator's path to find the subobject.
3921   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3922     // Reading an indeterminate value is undefined, but assigning over one is OK.
3923     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3924         (O->isIndeterminate() &&
3925          !isValidIndeterminateAccess(handler.AccessKind))) {
3926       // Object has ended lifetime.
3927       // If I is non-zero, some subobject (member or array element) of a
3928       // complete object has ended its lifetime, so this is valid for
3929       // IsWithinLifetime, resulting in false.
3930       if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3931         return false;
3932       if (!Info.checkingPotentialConstantExpression())
3933         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3934             << handler.AccessKind << O->isIndeterminate()
3935             << E->getSourceRange();
3936       return handler.failed();
3937     }
3938 
3939     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3940     //    const and volatile semantics are not applied on an object under
3941     //    {con,de}struction.
3942     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3943         ObjType->isRecordType() &&
3944         Info.isEvaluatingCtorDtor(
3945             Obj.Base,
3946             llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3947             ConstructionPhase::None) {
3948       ObjType = Info.Ctx.getCanonicalType(ObjType);
3949       ObjType.removeLocalConst();
3950       ObjType.removeLocalVolatile();
3951     }
3952 
3953     // If this is our last pass, check that the final object type is OK.
3954     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3955       // Accesses to volatile objects are prohibited.
3956       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3957         if (Info.getLangOpts().CPlusPlus) {
3958           int DiagKind;
3959           SourceLocation Loc;
3960           const NamedDecl *Decl = nullptr;
3961           if (VolatileField) {
3962             DiagKind = 2;
3963             Loc = VolatileField->getLocation();
3964             Decl = VolatileField;
3965           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3966             DiagKind = 1;
3967             Loc = VD->getLocation();
3968             Decl = VD;
3969           } else {
3970             DiagKind = 0;
3971             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3972               Loc = E->getExprLoc();
3973           }
3974           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3975               << handler.AccessKind << DiagKind << Decl;
3976           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3977         } else {
3978           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3979         }
3980         return handler.failed();
3981       }
3982 
3983       // If we are reading an object of class type, there may still be more
3984       // things we need to check: if there are any mutable subobjects, we
3985       // cannot perform this read. (This only happens when performing a trivial
3986       // copy or assignment.)
3987       if (ObjType->isRecordType() &&
3988           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3989           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3990         return handler.failed();
3991     }
3992 
3993     if (I == N) {
3994       if (!handler.found(*O, ObjType))
3995         return false;
3996 
3997       // If we modified a bit-field, truncate it to the right width.
3998       if (isModification(handler.AccessKind) &&
3999           LastField && LastField->isBitField() &&
4000           !truncateBitfieldValue(Info, E, *O, LastField))
4001         return false;
4002 
4003       return true;
4004     }
4005 
4006     LastField = nullptr;
4007     if (ObjType->isArrayType()) {
4008       // Next subobject is an array element.
4009       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
4010       assert(CAT && "vla in literal type?");
4011       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4012       if (CAT->getSize().ule(Index)) {
4013         // Note, it should not be possible to form a pointer with a valid
4014         // designator which points more than one past the end of the array.
4015         if (Info.getLangOpts().CPlusPlus11)
4016           Info.FFDiag(E, diag::note_constexpr_access_past_end)
4017             << handler.AccessKind;
4018         else
4019           Info.FFDiag(E);
4020         return handler.failed();
4021       }
4022 
4023       ObjType = CAT->getElementType();
4024 
4025       if (O->getArrayInitializedElts() > Index)
4026         O = &O->getArrayInitializedElt(Index);
4027       else if (!isRead(handler.AccessKind)) {
4028         if (!CheckArraySize(Info, CAT, E->getExprLoc()))
4029           return handler.failed();
4030 
4031         expandArray(*O, Index);
4032         O = &O->getArrayInitializedElt(Index);
4033       } else
4034         O = &O->getArrayFiller();
4035     } else if (ObjType->isAnyComplexType()) {
4036       // Next subobject is a complex number.
4037       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4038       if (Index > 1) {
4039         if (Info.getLangOpts().CPlusPlus11)
4040           Info.FFDiag(E, diag::note_constexpr_access_past_end)
4041             << handler.AccessKind;
4042         else
4043           Info.FFDiag(E);
4044         return handler.failed();
4045       }
4046 
4047       ObjType = getSubobjectType(
4048           ObjType, ObjType->castAs<ComplexType>()->getElementType());
4049 
4050       assert(I == N - 1 && "extracting subobject of scalar?");
4051       if (O->isComplexInt()) {
4052         return handler.found(Index ? O->getComplexIntImag()
4053                                    : O->getComplexIntReal(), ObjType);
4054       } else {
4055         assert(O->isComplexFloat());
4056         return handler.found(Index ? O->getComplexFloatImag()
4057                                    : O->getComplexFloatReal(), ObjType);
4058       }
4059     } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4060       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4061       unsigned NumElements = VT->getNumElements();
4062       if (Index == NumElements) {
4063         if (Info.getLangOpts().CPlusPlus11)
4064           Info.FFDiag(E, diag::note_constexpr_access_past_end)
4065               << handler.AccessKind;
4066         else
4067           Info.FFDiag(E);
4068         return handler.failed();
4069       }
4070 
4071       if (Index > NumElements) {
4072         Info.CCEDiag(E, diag::note_constexpr_array_index)
4073             << Index << /*array*/ 0 << NumElements;
4074         return handler.failed();
4075       }
4076 
4077       ObjType = VT->getElementType();
4078       assert(I == N - 1 && "extracting subobject of scalar?");
4079       return handler.found(O->getVectorElt(Index), ObjType);
4080     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4081       if (Field->isMutable() &&
4082           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4083         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4084           << handler.AccessKind << Field;
4085         Info.Note(Field->getLocation(), diag::note_declared_at);
4086         return handler.failed();
4087       }
4088 
4089       // Next subobject is a class, struct or union field.
4090       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
4091       if (RD->isUnion()) {
4092         const FieldDecl *UnionField = O->getUnionField();
4093         if (!UnionField ||
4094             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4095           if (I == N - 1 && handler.AccessKind == AK_Construct) {
4096             // Placement new onto an inactive union member makes it active.
4097             O->setUnion(Field, APValue());
4098           } else {
4099             // Pointer to/into inactive union member: Not within lifetime
4100             if (handler.AccessKind == AK_IsWithinLifetime)
4101               return false;
4102             // FIXME: If O->getUnionValue() is absent, report that there's no
4103             // active union member rather than reporting the prior active union
4104             // member. We'll need to fix nullptr_t to not use APValue() as its
4105             // representation first.
4106             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4107                 << handler.AccessKind << Field << !UnionField << UnionField;
4108             return handler.failed();
4109           }
4110         }
4111         O = &O->getUnionValue();
4112       } else
4113         O = &O->getStructField(Field->getFieldIndex());
4114 
4115       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4116       LastField = Field;
4117       if (Field->getType().isVolatileQualified())
4118         VolatileField = Field;
4119     } else {
4120       // Next subobject is a base class.
4121       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4122       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4123       O = &O->getStructBase(getBaseIndex(Derived, Base));
4124 
4125       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
4126     }
4127   }
4128 }
4129 
4130 namespace {
4131 struct ExtractSubobjectHandler {
4132   EvalInfo &Info;
4133   const Expr *E;
4134   APValue &Result;
4135   const AccessKinds AccessKind;
4136 
4137   typedef bool result_type;
4138   bool failed() { return false; }
4139   bool found(APValue &Subobj, QualType SubobjType) {
4140     Result = Subobj;
4141     if (AccessKind == AK_ReadObjectRepresentation)
4142       return true;
4143     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4144   }
4145   bool found(APSInt &Value, QualType SubobjType) {
4146     Result = APValue(Value);
4147     return true;
4148   }
4149   bool found(APFloat &Value, QualType SubobjType) {
4150     Result = APValue(Value);
4151     return true;
4152   }
4153 };
4154 } // end anonymous namespace
4155 
4156 /// Extract the designated sub-object of an rvalue.
4157 static bool extractSubobject(EvalInfo &Info, const Expr *E,
4158                              const CompleteObject &Obj,
4159                              const SubobjectDesignator &Sub, APValue &Result,
4160                              AccessKinds AK = AK_Read) {
4161   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4162   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4163   return findSubobject(Info, E, Obj, Sub, Handler);
4164 }
4165 
4166 namespace {
4167 struct ModifySubobjectHandler {
4168   EvalInfo &Info;
4169   APValue &NewVal;
4170   const Expr *E;
4171 
4172   typedef bool result_type;
4173   static const AccessKinds AccessKind = AK_Assign;
4174 
4175   bool checkConst(QualType QT) {
4176     // Assigning to a const object has undefined behavior.
4177     if (QT.isConstQualified()) {
4178       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4179       return false;
4180     }
4181     return true;
4182   }
4183 
4184   bool failed() { return false; }
4185   bool found(APValue &Subobj, QualType SubobjType) {
4186     if (!checkConst(SubobjType))
4187       return false;
4188     // We've been given ownership of NewVal, so just swap it in.
4189     Subobj.swap(NewVal);
4190     return true;
4191   }
4192   bool found(APSInt &Value, QualType SubobjType) {
4193     if (!checkConst(SubobjType))
4194       return false;
4195     if (!NewVal.isInt()) {
4196       // Maybe trying to write a cast pointer value into a complex?
4197       Info.FFDiag(E);
4198       return false;
4199     }
4200     Value = NewVal.getInt();
4201     return true;
4202   }
4203   bool found(APFloat &Value, QualType SubobjType) {
4204     if (!checkConst(SubobjType))
4205       return false;
4206     Value = NewVal.getFloat();
4207     return true;
4208   }
4209 };
4210 } // end anonymous namespace
4211 
4212 const AccessKinds ModifySubobjectHandler::AccessKind;
4213 
4214 /// Update the designated sub-object of an rvalue to the given value.
4215 static bool modifySubobject(EvalInfo &Info, const Expr *E,
4216                             const CompleteObject &Obj,
4217                             const SubobjectDesignator &Sub,
4218                             APValue &NewVal) {
4219   ModifySubobjectHandler Handler = { Info, NewVal, E };
4220   return findSubobject(Info, E, Obj, Sub, Handler);
4221 }
4222 
4223 /// Find the position where two subobject designators diverge, or equivalently
4224 /// the length of the common initial subsequence.
4225 static unsigned FindDesignatorMismatch(QualType ObjType,
4226                                        const SubobjectDesignator &A,
4227                                        const SubobjectDesignator &B,
4228                                        bool &WasArrayIndex) {
4229   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4230   for (/**/; I != N; ++I) {
4231     if (!ObjType.isNull() &&
4232         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4233       // Next subobject is an array element.
4234       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4235         WasArrayIndex = true;
4236         return I;
4237       }
4238       if (ObjType->isAnyComplexType())
4239         ObjType = ObjType->castAs<ComplexType>()->getElementType();
4240       else
4241         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4242     } else {
4243       if (A.Entries[I].getAsBaseOrMember() !=
4244           B.Entries[I].getAsBaseOrMember()) {
4245         WasArrayIndex = false;
4246         return I;
4247       }
4248       if (const FieldDecl *FD = getAsField(A.Entries[I]))
4249         // Next subobject is a field.
4250         ObjType = FD->getType();
4251       else
4252         // Next subobject is a base class.
4253         ObjType = QualType();
4254     }
4255   }
4256   WasArrayIndex = false;
4257   return I;
4258 }
4259 
4260 /// Determine whether the given subobject designators refer to elements of the
4261 /// same array object.
4262 static bool AreElementsOfSameArray(QualType ObjType,
4263                                    const SubobjectDesignator &A,
4264                                    const SubobjectDesignator &B) {
4265   if (A.Entries.size() != B.Entries.size())
4266     return false;
4267 
4268   bool IsArray = A.MostDerivedIsArrayElement;
4269   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4270     // A is a subobject of the array element.
4271     return false;
4272 
4273   // If A (and B) designates an array element, the last entry will be the array
4274   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4275   // of length 1' case, and the entire path must match.
4276   bool WasArrayIndex;
4277   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4278   return CommonLength >= A.Entries.size() - IsArray;
4279 }
4280 
4281 /// Find the complete object to which an LValue refers.
4282 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4283                                          AccessKinds AK, const LValue &LVal,
4284                                          QualType LValType) {
4285   if (LVal.InvalidBase) {
4286     Info.FFDiag(E);
4287     return CompleteObject();
4288   }
4289 
4290   if (!LVal.Base) {
4291     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4292     return CompleteObject();
4293   }
4294 
4295   CallStackFrame *Frame = nullptr;
4296   unsigned Depth = 0;
4297   if (LVal.getLValueCallIndex()) {
4298     std::tie(Frame, Depth) =
4299         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4300     if (!Frame) {
4301       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4302         << AK << LVal.Base.is<const ValueDecl*>();
4303       NoteLValueLocation(Info, LVal.Base);
4304       return CompleteObject();
4305     }
4306   }
4307 
4308   bool IsAccess = isAnyAccess(AK);
4309 
4310   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4311   // is not a constant expression (even if the object is non-volatile). We also
4312   // apply this rule to C++98, in order to conform to the expected 'volatile'
4313   // semantics.
4314   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4315     if (Info.getLangOpts().CPlusPlus)
4316       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4317         << AK << LValType;
4318     else
4319       Info.FFDiag(E);
4320     return CompleteObject();
4321   }
4322 
4323   // Compute value storage location and type of base object.
4324   APValue *BaseVal = nullptr;
4325   QualType BaseType = getType(LVal.Base);
4326 
4327   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4328       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4329     // This is the object whose initializer we're evaluating, so its lifetime
4330     // started in the current evaluation.
4331     BaseVal = Info.EvaluatingDeclValue;
4332   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4333     // Allow reading from a GUID declaration.
4334     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4335       if (isModification(AK)) {
4336         // All the remaining cases do not permit modification of the object.
4337         Info.FFDiag(E, diag::note_constexpr_modify_global);
4338         return CompleteObject();
4339       }
4340       APValue &V = GD->getAsAPValue();
4341       if (V.isAbsent()) {
4342         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4343             << GD->getType();
4344         return CompleteObject();
4345       }
4346       return CompleteObject(LVal.Base, &V, GD->getType());
4347     }
4348 
4349     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4350     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4351       if (isModification(AK)) {
4352         Info.FFDiag(E, diag::note_constexpr_modify_global);
4353         return CompleteObject();
4354       }
4355       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4356                             GCD->getType());
4357     }
4358 
4359     // Allow reading from template parameter objects.
4360     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4361       if (isModification(AK)) {
4362         Info.FFDiag(E, diag::note_constexpr_modify_global);
4363         return CompleteObject();
4364       }
4365       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4366                             TPO->getType());
4367     }
4368 
4369     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4370     // In C++11, constexpr, non-volatile variables initialized with constant
4371     // expressions are constant expressions too. Inside constexpr functions,
4372     // parameters are constant expressions even if they're non-const.
4373     // In C++1y, objects local to a constant expression (those with a Frame) are
4374     // both readable and writable inside constant expressions.
4375     // In C, such things can also be folded, although they are not ICEs.
4376     const VarDecl *VD = dyn_cast<VarDecl>(D);
4377     if (VD) {
4378       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4379         VD = VDef;
4380     }
4381     if (!VD || VD->isInvalidDecl()) {
4382       Info.FFDiag(E);
4383       return CompleteObject();
4384     }
4385 
4386     bool IsConstant = BaseType.isConstant(Info.Ctx);
4387     bool ConstexprVar = false;
4388     if (const auto *VD = dyn_cast_if_present<VarDecl>(
4389             Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4390       ConstexprVar = VD->isConstexpr();
4391 
4392     // Unless we're looking at a local variable or argument in a constexpr call,
4393     // the variable we're reading must be const.
4394     if (!Frame) {
4395       if (IsAccess && isa<ParmVarDecl>(VD)) {
4396         // Access of a parameter that's not associated with a frame isn't going
4397         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4398         // suitable diagnostic.
4399       } else if (Info.getLangOpts().CPlusPlus14 &&
4400                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4401         // OK, we can read and modify an object if we're in the process of
4402         // evaluating its initializer, because its lifetime began in this
4403         // evaluation.
4404       } else if (isModification(AK)) {
4405         // All the remaining cases do not permit modification of the object.
4406         Info.FFDiag(E, diag::note_constexpr_modify_global);
4407         return CompleteObject();
4408       } else if (VD->isConstexpr()) {
4409         // OK, we can read this variable.
4410       } else if (Info.getLangOpts().C23 && ConstexprVar) {
4411         Info.FFDiag(E);
4412         return CompleteObject();
4413       } else if (BaseType->isIntegralOrEnumerationType()) {
4414         if (!IsConstant) {
4415           if (!IsAccess)
4416             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4417           if (Info.getLangOpts().CPlusPlus) {
4418             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4419             Info.Note(VD->getLocation(), diag::note_declared_at);
4420           } else {
4421             Info.FFDiag(E);
4422           }
4423           return CompleteObject();
4424         }
4425       } else if (!IsAccess) {
4426         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4427       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4428                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4429         // This variable might end up being constexpr. Don't diagnose it yet.
4430       } else if (IsConstant) {
4431         // Keep evaluating to see what we can do. In particular, we support
4432         // folding of const floating-point types, in order to make static const
4433         // data members of such types (supported as an extension) more useful.
4434         if (Info.getLangOpts().CPlusPlus) {
4435           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4436                               ? diag::note_constexpr_ltor_non_constexpr
4437                               : diag::note_constexpr_ltor_non_integral, 1)
4438               << VD << BaseType;
4439           Info.Note(VD->getLocation(), diag::note_declared_at);
4440         } else {
4441           Info.CCEDiag(E);
4442         }
4443       } else {
4444         // Never allow reading a non-const value.
4445         if (Info.getLangOpts().CPlusPlus) {
4446           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4447                              ? diag::note_constexpr_ltor_non_constexpr
4448                              : diag::note_constexpr_ltor_non_integral, 1)
4449               << VD << BaseType;
4450           Info.Note(VD->getLocation(), diag::note_declared_at);
4451         } else {
4452           Info.FFDiag(E);
4453         }
4454         return CompleteObject();
4455       }
4456     }
4457 
4458     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4459       return CompleteObject();
4460   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4461     std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4462     if (!Alloc) {
4463       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4464       return CompleteObject();
4465     }
4466     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4467                           LVal.Base.getDynamicAllocType());
4468   } else {
4469     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4470 
4471     if (!Frame) {
4472       if (const MaterializeTemporaryExpr *MTE =
4473               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4474         assert(MTE->getStorageDuration() == SD_Static &&
4475                "should have a frame for a non-global materialized temporary");
4476 
4477         // C++20 [expr.const]p4: [DR2126]
4478         //   An object or reference is usable in constant expressions if it is
4479         //   - a temporary object of non-volatile const-qualified literal type
4480         //     whose lifetime is extended to that of a variable that is usable
4481         //     in constant expressions
4482         //
4483         // C++20 [expr.const]p5:
4484         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4485         //   - a non-volatile glvalue that refers to an object that is usable
4486         //     in constant expressions, or
4487         //   - a non-volatile glvalue of literal type that refers to a
4488         //     non-volatile object whose lifetime began within the evaluation
4489         //     of E;
4490         //
4491         // C++11 misses the 'began within the evaluation of e' check and
4492         // instead allows all temporaries, including things like:
4493         //   int &&r = 1;
4494         //   int x = ++r;
4495         //   constexpr int k = r;
4496         // Therefore we use the C++14-onwards rules in C++11 too.
4497         //
4498         // Note that temporaries whose lifetimes began while evaluating a
4499         // variable's constructor are not usable while evaluating the
4500         // corresponding destructor, not even if they're of const-qualified
4501         // types.
4502         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4503             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4504           if (!IsAccess)
4505             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4506           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4507           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4508           return CompleteObject();
4509         }
4510 
4511         BaseVal = MTE->getOrCreateValue(false);
4512         assert(BaseVal && "got reference to unevaluated temporary");
4513       } else {
4514         if (!IsAccess)
4515           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4516         APValue Val;
4517         LVal.moveInto(Val);
4518         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4519             << AK
4520             << Val.getAsString(Info.Ctx,
4521                                Info.Ctx.getLValueReferenceType(LValType));
4522         NoteLValueLocation(Info, LVal.Base);
4523         return CompleteObject();
4524       }
4525     } else {
4526       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4527       assert(BaseVal && "missing value for temporary");
4528     }
4529   }
4530 
4531   // In C++14, we can't safely access any mutable state when we might be
4532   // evaluating after an unmodeled side effect. Parameters are modeled as state
4533   // in the caller, but aren't visible once the call returns, so they can be
4534   // modified in a speculatively-evaluated call.
4535   //
4536   // FIXME: Not all local state is mutable. Allow local constant subobjects
4537   // to be read here (but take care with 'mutable' fields).
4538   unsigned VisibleDepth = Depth;
4539   if (llvm::isa_and_nonnull<ParmVarDecl>(
4540           LVal.Base.dyn_cast<const ValueDecl *>()))
4541     ++VisibleDepth;
4542   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4543        Info.EvalStatus.HasSideEffects) ||
4544       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4545     return CompleteObject();
4546 
4547   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4548 }
4549 
4550 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4551 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4552 /// glvalue referred to by an entity of reference type.
4553 ///
4554 /// \param Info - Information about the ongoing evaluation.
4555 /// \param Conv - The expression for which we are performing the conversion.
4556 ///               Used for diagnostics.
4557 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4558 ///               case of a non-class type).
4559 /// \param LVal - The glvalue on which we are attempting to perform this action.
4560 /// \param RVal - The produced value will be placed here.
4561 /// \param WantObjectRepresentation - If true, we're looking for the object
4562 ///               representation rather than the value, and in particular,
4563 ///               there is no requirement that the result be fully initialized.
4564 static bool
4565 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4566                                const LValue &LVal, APValue &RVal,
4567                                bool WantObjectRepresentation = false) {
4568   if (LVal.Designator.Invalid)
4569     return false;
4570 
4571   // Check for special cases where there is no existing APValue to look at.
4572   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4573 
4574   AccessKinds AK =
4575       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4576 
4577   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4578     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4579       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4580       // initializer until now for such expressions. Such an expression can't be
4581       // an ICE in C, so this only matters for fold.
4582       if (Type.isVolatileQualified()) {
4583         Info.FFDiag(Conv);
4584         return false;
4585       }
4586 
4587       APValue Lit;
4588       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4589         return false;
4590 
4591       // According to GCC info page:
4592       //
4593       // 6.28 Compound Literals
4594       //
4595       // As an optimization, G++ sometimes gives array compound literals longer
4596       // lifetimes: when the array either appears outside a function or has a
4597       // const-qualified type. If foo and its initializer had elements of type
4598       // char *const rather than char *, or if foo were a global variable, the
4599       // array would have static storage duration. But it is probably safest
4600       // just to avoid the use of array compound literals in C++ code.
4601       //
4602       // Obey that rule by checking constness for converted array types.
4603 
4604       QualType CLETy = CLE->getType();
4605       if (CLETy->isArrayType() && !Type->isArrayType()) {
4606         if (!CLETy.isConstant(Info.Ctx)) {
4607           Info.FFDiag(Conv);
4608           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4609           return false;
4610         }
4611       }
4612 
4613       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4614       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4615     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4616       // Special-case character extraction so we don't have to construct an
4617       // APValue for the whole string.
4618       assert(LVal.Designator.Entries.size() <= 1 &&
4619              "Can only read characters from string literals");
4620       if (LVal.Designator.Entries.empty()) {
4621         // Fail for now for LValue to RValue conversion of an array.
4622         // (This shouldn't show up in C/C++, but it could be triggered by a
4623         // weird EvaluateAsRValue call from a tool.)
4624         Info.FFDiag(Conv);
4625         return false;
4626       }
4627       if (LVal.Designator.isOnePastTheEnd()) {
4628         if (Info.getLangOpts().CPlusPlus11)
4629           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4630         else
4631           Info.FFDiag(Conv);
4632         return false;
4633       }
4634       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4635       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4636       return true;
4637     }
4638   }
4639 
4640   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4641   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4642 }
4643 
4644 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4645 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4646                              QualType LValType, APValue &Val) {
4647   if (LVal.Designator.Invalid)
4648     return false;
4649 
4650   if (!Info.getLangOpts().CPlusPlus14) {
4651     Info.FFDiag(E);
4652     return false;
4653   }
4654 
4655   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4656   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4657 }
4658 
4659 namespace {
4660 struct CompoundAssignSubobjectHandler {
4661   EvalInfo &Info;
4662   const CompoundAssignOperator *E;
4663   QualType PromotedLHSType;
4664   BinaryOperatorKind Opcode;
4665   const APValue &RHS;
4666 
4667   static const AccessKinds AccessKind = AK_Assign;
4668 
4669   typedef bool result_type;
4670 
4671   bool checkConst(QualType QT) {
4672     // Assigning to a const object has undefined behavior.
4673     if (QT.isConstQualified()) {
4674       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4675       return false;
4676     }
4677     return true;
4678   }
4679 
4680   bool failed() { return false; }
4681   bool found(APValue &Subobj, QualType SubobjType) {
4682     switch (Subobj.getKind()) {
4683     case APValue::Int:
4684       return found(Subobj.getInt(), SubobjType);
4685     case APValue::Float:
4686       return found(Subobj.getFloat(), SubobjType);
4687     case APValue::ComplexInt:
4688     case APValue::ComplexFloat:
4689       // FIXME: Implement complex compound assignment.
4690       Info.FFDiag(E);
4691       return false;
4692     case APValue::LValue:
4693       return foundPointer(Subobj, SubobjType);
4694     case APValue::Vector:
4695       return foundVector(Subobj, SubobjType);
4696     case APValue::Indeterminate:
4697       Info.FFDiag(E, diag::note_constexpr_access_uninit)
4698           << /*read of=*/0 << /*uninitialized object=*/1
4699           << E->getLHS()->getSourceRange();
4700       return false;
4701     default:
4702       // FIXME: can this happen?
4703       Info.FFDiag(E);
4704       return false;
4705     }
4706   }
4707 
4708   bool foundVector(APValue &Value, QualType SubobjType) {
4709     if (!checkConst(SubobjType))
4710       return false;
4711 
4712     if (!SubobjType->isVectorType()) {
4713       Info.FFDiag(E);
4714       return false;
4715     }
4716     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4717   }
4718 
4719   bool found(APSInt &Value, QualType SubobjType) {
4720     if (!checkConst(SubobjType))
4721       return false;
4722 
4723     if (!SubobjType->isIntegerType()) {
4724       // We don't support compound assignment on integer-cast-to-pointer
4725       // values.
4726       Info.FFDiag(E);
4727       return false;
4728     }
4729 
4730     if (RHS.isInt()) {
4731       APSInt LHS =
4732           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4733       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4734         return false;
4735       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4736       return true;
4737     } else if (RHS.isFloat()) {
4738       const FPOptions FPO = E->getFPFeaturesInEffect(
4739                                     Info.Ctx.getLangOpts());
4740       APFloat FValue(0.0);
4741       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4742                                   PromotedLHSType, FValue) &&
4743              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4744              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4745                                   Value);
4746     }
4747 
4748     Info.FFDiag(E);
4749     return false;
4750   }
4751   bool found(APFloat &Value, QualType SubobjType) {
4752     return checkConst(SubobjType) &&
4753            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4754                                   Value) &&
4755            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4756            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4757   }
4758   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4759     if (!checkConst(SubobjType))
4760       return false;
4761 
4762     QualType PointeeType;
4763     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4764       PointeeType = PT->getPointeeType();
4765 
4766     if (PointeeType.isNull() || !RHS.isInt() ||
4767         (Opcode != BO_Add && Opcode != BO_Sub)) {
4768       Info.FFDiag(E);
4769       return false;
4770     }
4771 
4772     APSInt Offset = RHS.getInt();
4773     if (Opcode == BO_Sub)
4774       negateAsSigned(Offset);
4775 
4776     LValue LVal;
4777     LVal.setFrom(Info.Ctx, Subobj);
4778     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4779       return false;
4780     LVal.moveInto(Subobj);
4781     return true;
4782   }
4783 };
4784 } // end anonymous namespace
4785 
4786 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4787 
4788 /// Perform a compound assignment of LVal <op>= RVal.
4789 static bool handleCompoundAssignment(EvalInfo &Info,
4790                                      const CompoundAssignOperator *E,
4791                                      const LValue &LVal, QualType LValType,
4792                                      QualType PromotedLValType,
4793                                      BinaryOperatorKind Opcode,
4794                                      const APValue &RVal) {
4795   if (LVal.Designator.Invalid)
4796     return false;
4797 
4798   if (!Info.getLangOpts().CPlusPlus14) {
4799     Info.FFDiag(E);
4800     return false;
4801   }
4802 
4803   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4804   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4805                                              RVal };
4806   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4807 }
4808 
4809 namespace {
4810 struct IncDecSubobjectHandler {
4811   EvalInfo &Info;
4812   const UnaryOperator *E;
4813   AccessKinds AccessKind;
4814   APValue *Old;
4815 
4816   typedef bool result_type;
4817 
4818   bool checkConst(QualType QT) {
4819     // Assigning to a const object has undefined behavior.
4820     if (QT.isConstQualified()) {
4821       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4822       return false;
4823     }
4824     return true;
4825   }
4826 
4827   bool failed() { return false; }
4828   bool found(APValue &Subobj, QualType SubobjType) {
4829     // Stash the old value. Also clear Old, so we don't clobber it later
4830     // if we're post-incrementing a complex.
4831     if (Old) {
4832       *Old = Subobj;
4833       Old = nullptr;
4834     }
4835 
4836     switch (Subobj.getKind()) {
4837     case APValue::Int:
4838       return found(Subobj.getInt(), SubobjType);
4839     case APValue::Float:
4840       return found(Subobj.getFloat(), SubobjType);
4841     case APValue::ComplexInt:
4842       return found(Subobj.getComplexIntReal(),
4843                    SubobjType->castAs<ComplexType>()->getElementType()
4844                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4845     case APValue::ComplexFloat:
4846       return found(Subobj.getComplexFloatReal(),
4847                    SubobjType->castAs<ComplexType>()->getElementType()
4848                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4849     case APValue::LValue:
4850       return foundPointer(Subobj, SubobjType);
4851     default:
4852       // FIXME: can this happen?
4853       Info.FFDiag(E);
4854       return false;
4855     }
4856   }
4857   bool found(APSInt &Value, QualType SubobjType) {
4858     if (!checkConst(SubobjType))
4859       return false;
4860 
4861     if (!SubobjType->isIntegerType()) {
4862       // We don't support increment / decrement on integer-cast-to-pointer
4863       // values.
4864       Info.FFDiag(E);
4865       return false;
4866     }
4867 
4868     if (Old) *Old = APValue(Value);
4869 
4870     // bool arithmetic promotes to int, and the conversion back to bool
4871     // doesn't reduce mod 2^n, so special-case it.
4872     if (SubobjType->isBooleanType()) {
4873       if (AccessKind == AK_Increment)
4874         Value = 1;
4875       else
4876         Value = !Value;
4877       return true;
4878     }
4879 
4880     bool WasNegative = Value.isNegative();
4881     if (AccessKind == AK_Increment) {
4882       ++Value;
4883 
4884       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4885         APSInt ActualValue(Value, /*IsUnsigned*/true);
4886         return HandleOverflow(Info, E, ActualValue, SubobjType);
4887       }
4888     } else {
4889       --Value;
4890 
4891       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4892         unsigned BitWidth = Value.getBitWidth();
4893         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4894         ActualValue.setBit(BitWidth);
4895         return HandleOverflow(Info, E, ActualValue, SubobjType);
4896       }
4897     }
4898     return true;
4899   }
4900   bool found(APFloat &Value, QualType SubobjType) {
4901     if (!checkConst(SubobjType))
4902       return false;
4903 
4904     if (Old) *Old = APValue(Value);
4905 
4906     APFloat One(Value.getSemantics(), 1);
4907     llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4908     APFloat::opStatus St;
4909     if (AccessKind == AK_Increment)
4910       St = Value.add(One, RM);
4911     else
4912       St = Value.subtract(One, RM);
4913     return checkFloatingPointResult(Info, E, St);
4914   }
4915   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4916     if (!checkConst(SubobjType))
4917       return false;
4918 
4919     QualType PointeeType;
4920     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4921       PointeeType = PT->getPointeeType();
4922     else {
4923       Info.FFDiag(E);
4924       return false;
4925     }
4926 
4927     LValue LVal;
4928     LVal.setFrom(Info.Ctx, Subobj);
4929     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4930                                      AccessKind == AK_Increment ? 1 : -1))
4931       return false;
4932     LVal.moveInto(Subobj);
4933     return true;
4934   }
4935 };
4936 } // end anonymous namespace
4937 
4938 /// Perform an increment or decrement on LVal.
4939 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4940                          QualType LValType, bool IsIncrement, APValue *Old) {
4941   if (LVal.Designator.Invalid)
4942     return false;
4943 
4944   if (!Info.getLangOpts().CPlusPlus14) {
4945     Info.FFDiag(E);
4946     return false;
4947   }
4948 
4949   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4950   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4951   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4952   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4953 }
4954 
4955 /// Build an lvalue for the object argument of a member function call.
4956 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4957                                    LValue &This) {
4958   if (Object->getType()->isPointerType() && Object->isPRValue())
4959     return EvaluatePointer(Object, This, Info);
4960 
4961   if (Object->isGLValue())
4962     return EvaluateLValue(Object, This, Info);
4963 
4964   if (Object->getType()->isLiteralType(Info.Ctx))
4965     return EvaluateTemporary(Object, This, Info);
4966 
4967   if (Object->getType()->isRecordType() && Object->isPRValue())
4968     return EvaluateTemporary(Object, This, Info);
4969 
4970   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4971   return false;
4972 }
4973 
4974 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4975 /// lvalue referring to the result.
4976 ///
4977 /// \param Info - Information about the ongoing evaluation.
4978 /// \param LV - An lvalue referring to the base of the member pointer.
4979 /// \param RHS - The member pointer expression.
4980 /// \param IncludeMember - Specifies whether the member itself is included in
4981 ///        the resulting LValue subobject designator. This is not possible when
4982 ///        creating a bound member function.
4983 /// \return The field or method declaration to which the member pointer refers,
4984 ///         or 0 if evaluation fails.
4985 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4986                                                   QualType LVType,
4987                                                   LValue &LV,
4988                                                   const Expr *RHS,
4989                                                   bool IncludeMember = true) {
4990   MemberPtr MemPtr;
4991   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4992     return nullptr;
4993 
4994   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4995   // member value, the behavior is undefined.
4996   if (!MemPtr.getDecl()) {
4997     // FIXME: Specific diagnostic.
4998     Info.FFDiag(RHS);
4999     return nullptr;
5000   }
5001 
5002   if (MemPtr.isDerivedMember()) {
5003     // This is a member of some derived class. Truncate LV appropriately.
5004     // The end of the derived-to-base path for the base object must match the
5005     // derived-to-base path for the member pointer.
5006     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5007         LV.Designator.Entries.size()) {
5008       Info.FFDiag(RHS);
5009       return nullptr;
5010     }
5011     unsigned PathLengthToMember =
5012         LV.Designator.Entries.size() - MemPtr.Path.size();
5013     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5014       const CXXRecordDecl *LVDecl = getAsBaseClass(
5015           LV.Designator.Entries[PathLengthToMember + I]);
5016       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5017       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5018         Info.FFDiag(RHS);
5019         return nullptr;
5020       }
5021     }
5022 
5023     // Truncate the lvalue to the appropriate derived class.
5024     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5025                             PathLengthToMember))
5026       return nullptr;
5027   } else if (!MemPtr.Path.empty()) {
5028     // Extend the LValue path with the member pointer's path.
5029     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5030                                   MemPtr.Path.size() + IncludeMember);
5031 
5032     // Walk down to the appropriate base class.
5033     if (const PointerType *PT = LVType->getAs<PointerType>())
5034       LVType = PT->getPointeeType();
5035     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5036     assert(RD && "member pointer access on non-class-type expression");
5037     // The first class in the path is that of the lvalue.
5038     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5039       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5040       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5041         return nullptr;
5042       RD = Base;
5043     }
5044     // Finally cast to the class containing the member.
5045     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5046                                 MemPtr.getContainingRecord()))
5047       return nullptr;
5048   }
5049 
5050   // Add the member. Note that we cannot build bound member functions here.
5051   if (IncludeMember) {
5052     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5053       if (!HandleLValueMember(Info, RHS, LV, FD))
5054         return nullptr;
5055     } else if (const IndirectFieldDecl *IFD =
5056                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5057       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5058         return nullptr;
5059     } else {
5060       llvm_unreachable("can't construct reference to bound member function");
5061     }
5062   }
5063 
5064   return MemPtr.getDecl();
5065 }
5066 
5067 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5068                                                   const BinaryOperator *BO,
5069                                                   LValue &LV,
5070                                                   bool IncludeMember = true) {
5071   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5072 
5073   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5074     if (Info.noteFailure()) {
5075       MemberPtr MemPtr;
5076       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5077     }
5078     return nullptr;
5079   }
5080 
5081   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5082                                    BO->getRHS(), IncludeMember);
5083 }
5084 
5085 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5086 /// the provided lvalue, which currently refers to the base object.
5087 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5088                                     LValue &Result) {
5089   SubobjectDesignator &D = Result.Designator;
5090   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5091     return false;
5092 
5093   QualType TargetQT = E->getType();
5094   if (const PointerType *PT = TargetQT->getAs<PointerType>())
5095     TargetQT = PT->getPointeeType();
5096 
5097   // Check this cast lands within the final derived-to-base subobject path.
5098   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
5099     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5100       << D.MostDerivedType << TargetQT;
5101     return false;
5102   }
5103 
5104   // Check the type of the final cast. We don't need to check the path,
5105   // since a cast can only be formed if the path is unique.
5106   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5107   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5108   const CXXRecordDecl *FinalType;
5109   if (NewEntriesSize == D.MostDerivedPathLength)
5110     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5111   else
5112     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5113   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
5114     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5115       << D.MostDerivedType << TargetQT;
5116     return false;
5117   }
5118 
5119   // Truncate the lvalue to the appropriate derived class.
5120   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5121 }
5122 
5123 /// Get the value to use for a default-initialized object of type T.
5124 /// Return false if it encounters something invalid.
5125 static bool handleDefaultInitValue(QualType T, APValue &Result) {
5126   bool Success = true;
5127 
5128   // If there is already a value present don't overwrite it.
5129   if (!Result.isAbsent())
5130     return true;
5131 
5132   if (auto *RD = T->getAsCXXRecordDecl()) {
5133     if (RD->isInvalidDecl()) {
5134       Result = APValue();
5135       return false;
5136     }
5137     if (RD->isUnion()) {
5138       Result = APValue((const FieldDecl *)nullptr);
5139       return true;
5140     }
5141     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5142                      std::distance(RD->field_begin(), RD->field_end()));
5143 
5144     unsigned Index = 0;
5145     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5146                                                   End = RD->bases_end();
5147          I != End; ++I, ++Index)
5148       Success &=
5149           handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5150 
5151     for (const auto *I : RD->fields()) {
5152       if (I->isUnnamedBitField())
5153         continue;
5154       Success &= handleDefaultInitValue(
5155           I->getType(), Result.getStructField(I->getFieldIndex()));
5156     }
5157     return Success;
5158   }
5159 
5160   if (auto *AT =
5161           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5162     Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5163     if (Result.hasArrayFiller())
5164       Success &=
5165           handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5166 
5167     return Success;
5168   }
5169 
5170   Result = APValue::IndeterminateValue();
5171   return true;
5172 }
5173 
5174 namespace {
5175 enum EvalStmtResult {
5176   /// Evaluation failed.
5177   ESR_Failed,
5178   /// Hit a 'return' statement.
5179   ESR_Returned,
5180   /// Evaluation succeeded.
5181   ESR_Succeeded,
5182   /// Hit a 'continue' statement.
5183   ESR_Continue,
5184   /// Hit a 'break' statement.
5185   ESR_Break,
5186   /// Still scanning for 'case' or 'default' statement.
5187   ESR_CaseNotFound
5188 };
5189 }
5190 
5191 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5192   if (VD->isInvalidDecl())
5193     return false;
5194   // We don't need to evaluate the initializer for a static local.
5195   if (!VD->hasLocalStorage())
5196     return true;
5197 
5198   LValue Result;
5199   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5200                                                    ScopeKind::Block, Result);
5201 
5202   const Expr *InitE = VD->getInit();
5203   if (!InitE) {
5204     if (VD->getType()->isDependentType())
5205       return Info.noteSideEffect();
5206     return handleDefaultInitValue(VD->getType(), Val);
5207   }
5208   if (InitE->isValueDependent())
5209     return false;
5210 
5211   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5212     // Wipe out any partially-computed value, to allow tracking that this
5213     // evaluation failed.
5214     Val = APValue();
5215     return false;
5216   }
5217 
5218   return true;
5219 }
5220 
5221 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
5222   bool OK = true;
5223 
5224   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5225     OK &= EvaluateVarDecl(Info, VD);
5226 
5227   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
5228     for (auto *BD : DD->flat_bindings())
5229       if (auto *VD = BD->getHoldingVar())
5230         OK &= EvaluateDecl(Info, VD);
5231 
5232   return OK;
5233 }
5234 
5235 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5236   assert(E->isValueDependent());
5237   if (Info.noteSideEffect())
5238     return true;
5239   assert(E->containsErrors() && "valid value-dependent expression should never "
5240                                 "reach invalid code path.");
5241   return false;
5242 }
5243 
5244 /// Evaluate a condition (either a variable declaration or an expression).
5245 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5246                          const Expr *Cond, bool &Result) {
5247   if (Cond->isValueDependent())
5248     return false;
5249   FullExpressionRAII Scope(Info);
5250   if (CondDecl && !EvaluateDecl(Info, CondDecl))
5251     return false;
5252   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5253     return false;
5254   return Scope.destroy();
5255 }
5256 
5257 namespace {
5258 /// A location where the result (returned value) of evaluating a
5259 /// statement should be stored.
5260 struct StmtResult {
5261   /// The APValue that should be filled in with the returned value.
5262   APValue &Value;
5263   /// The location containing the result, if any (used to support RVO).
5264   const LValue *Slot;
5265 };
5266 
5267 struct TempVersionRAII {
5268   CallStackFrame &Frame;
5269 
5270   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5271     Frame.pushTempVersion();
5272   }
5273 
5274   ~TempVersionRAII() {
5275     Frame.popTempVersion();
5276   }
5277 };
5278 
5279 }
5280 
5281 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5282                                    const Stmt *S,
5283                                    const SwitchCase *SC = nullptr);
5284 
5285 /// Evaluate the body of a loop, and translate the result as appropriate.
5286 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5287                                        const Stmt *Body,
5288                                        const SwitchCase *Case = nullptr) {
5289   BlockScopeRAII Scope(Info);
5290 
5291   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5292   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5293     ESR = ESR_Failed;
5294 
5295   switch (ESR) {
5296   case ESR_Break:
5297     return ESR_Succeeded;
5298   case ESR_Succeeded:
5299   case ESR_Continue:
5300     return ESR_Continue;
5301   case ESR_Failed:
5302   case ESR_Returned:
5303   case ESR_CaseNotFound:
5304     return ESR;
5305   }
5306   llvm_unreachable("Invalid EvalStmtResult!");
5307 }
5308 
5309 /// Evaluate a switch statement.
5310 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5311                                      const SwitchStmt *SS) {
5312   BlockScopeRAII Scope(Info);
5313 
5314   // Evaluate the switch condition.
5315   APSInt Value;
5316   {
5317     if (const Stmt *Init = SS->getInit()) {
5318       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5319       if (ESR != ESR_Succeeded) {
5320         if (ESR != ESR_Failed && !Scope.destroy())
5321           ESR = ESR_Failed;
5322         return ESR;
5323       }
5324     }
5325 
5326     FullExpressionRAII CondScope(Info);
5327     if (SS->getConditionVariable() &&
5328         !EvaluateDecl(Info, SS->getConditionVariable()))
5329       return ESR_Failed;
5330     if (SS->getCond()->isValueDependent()) {
5331       // We don't know what the value is, and which branch should jump to.
5332       EvaluateDependentExpr(SS->getCond(), Info);
5333       return ESR_Failed;
5334     }
5335     if (!EvaluateInteger(SS->getCond(), Value, Info))
5336       return ESR_Failed;
5337 
5338     if (!CondScope.destroy())
5339       return ESR_Failed;
5340   }
5341 
5342   // Find the switch case corresponding to the value of the condition.
5343   // FIXME: Cache this lookup.
5344   const SwitchCase *Found = nullptr;
5345   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5346        SC = SC->getNextSwitchCase()) {
5347     if (isa<DefaultStmt>(SC)) {
5348       Found = SC;
5349       continue;
5350     }
5351 
5352     const CaseStmt *CS = cast<CaseStmt>(SC);
5353     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5354     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5355                               : LHS;
5356     if (LHS <= Value && Value <= RHS) {
5357       Found = SC;
5358       break;
5359     }
5360   }
5361 
5362   if (!Found)
5363     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5364 
5365   // Search the switch body for the switch case and evaluate it from there.
5366   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5367   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5368     return ESR_Failed;
5369 
5370   switch (ESR) {
5371   case ESR_Break:
5372     return ESR_Succeeded;
5373   case ESR_Succeeded:
5374   case ESR_Continue:
5375   case ESR_Failed:
5376   case ESR_Returned:
5377     return ESR;
5378   case ESR_CaseNotFound:
5379     // This can only happen if the switch case is nested within a statement
5380     // expression. We have no intention of supporting that.
5381     Info.FFDiag(Found->getBeginLoc(),
5382                 diag::note_constexpr_stmt_expr_unsupported);
5383     return ESR_Failed;
5384   }
5385   llvm_unreachable("Invalid EvalStmtResult!");
5386 }
5387 
5388 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5389   // An expression E is a core constant expression unless the evaluation of E
5390   // would evaluate one of the following: [C++23] - a control flow that passes
5391   // through a declaration of a variable with static or thread storage duration
5392   // unless that variable is usable in constant expressions.
5393   if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5394       !VD->isUsableInConstantExpressions(Info.Ctx)) {
5395     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5396         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5397     return false;
5398   }
5399   return true;
5400 }
5401 
5402 // Evaluate a statement.
5403 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5404                                    const Stmt *S, const SwitchCase *Case) {
5405   if (!Info.nextStep(S))
5406     return ESR_Failed;
5407 
5408   // If we're hunting down a 'case' or 'default' label, recurse through
5409   // substatements until we hit the label.
5410   if (Case) {
5411     switch (S->getStmtClass()) {
5412     case Stmt::CompoundStmtClass:
5413       // FIXME: Precompute which substatement of a compound statement we
5414       // would jump to, and go straight there rather than performing a
5415       // linear scan each time.
5416     case Stmt::LabelStmtClass:
5417     case Stmt::AttributedStmtClass:
5418     case Stmt::DoStmtClass:
5419       break;
5420 
5421     case Stmt::CaseStmtClass:
5422     case Stmt::DefaultStmtClass:
5423       if (Case == S)
5424         Case = nullptr;
5425       break;
5426 
5427     case Stmt::IfStmtClass: {
5428       // FIXME: Precompute which side of an 'if' we would jump to, and go
5429       // straight there rather than scanning both sides.
5430       const IfStmt *IS = cast<IfStmt>(S);
5431 
5432       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5433       // preceded by our switch label.
5434       BlockScopeRAII Scope(Info);
5435 
5436       // Step into the init statement in case it brings an (uninitialized)
5437       // variable into scope.
5438       if (const Stmt *Init = IS->getInit()) {
5439         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5440         if (ESR != ESR_CaseNotFound) {
5441           assert(ESR != ESR_Succeeded);
5442           return ESR;
5443         }
5444       }
5445 
5446       // Condition variable must be initialized if it exists.
5447       // FIXME: We can skip evaluating the body if there's a condition
5448       // variable, as there can't be any case labels within it.
5449       // (The same is true for 'for' statements.)
5450 
5451       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5452       if (ESR == ESR_Failed)
5453         return ESR;
5454       if (ESR != ESR_CaseNotFound)
5455         return Scope.destroy() ? ESR : ESR_Failed;
5456       if (!IS->getElse())
5457         return ESR_CaseNotFound;
5458 
5459       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5460       if (ESR == ESR_Failed)
5461         return ESR;
5462       if (ESR != ESR_CaseNotFound)
5463         return Scope.destroy() ? ESR : ESR_Failed;
5464       return ESR_CaseNotFound;
5465     }
5466 
5467     case Stmt::WhileStmtClass: {
5468       EvalStmtResult ESR =
5469           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5470       if (ESR != ESR_Continue)
5471         return ESR;
5472       break;
5473     }
5474 
5475     case Stmt::ForStmtClass: {
5476       const ForStmt *FS = cast<ForStmt>(S);
5477       BlockScopeRAII Scope(Info);
5478 
5479       // Step into the init statement in case it brings an (uninitialized)
5480       // variable into scope.
5481       if (const Stmt *Init = FS->getInit()) {
5482         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5483         if (ESR != ESR_CaseNotFound) {
5484           assert(ESR != ESR_Succeeded);
5485           return ESR;
5486         }
5487       }
5488 
5489       EvalStmtResult ESR =
5490           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5491       if (ESR != ESR_Continue)
5492         return ESR;
5493       if (const auto *Inc = FS->getInc()) {
5494         if (Inc->isValueDependent()) {
5495           if (!EvaluateDependentExpr(Inc, Info))
5496             return ESR_Failed;
5497         } else {
5498           FullExpressionRAII IncScope(Info);
5499           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5500             return ESR_Failed;
5501         }
5502       }
5503       break;
5504     }
5505 
5506     case Stmt::DeclStmtClass: {
5507       // Start the lifetime of any uninitialized variables we encounter. They
5508       // might be used by the selected branch of the switch.
5509       const DeclStmt *DS = cast<DeclStmt>(S);
5510       for (const auto *D : DS->decls()) {
5511         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5512           if (!CheckLocalVariableDeclaration(Info, VD))
5513             return ESR_Failed;
5514           if (VD->hasLocalStorage() && !VD->getInit())
5515             if (!EvaluateVarDecl(Info, VD))
5516               return ESR_Failed;
5517           // FIXME: If the variable has initialization that can't be jumped
5518           // over, bail out of any immediately-surrounding compound-statement
5519           // too. There can't be any case labels here.
5520         }
5521       }
5522       return ESR_CaseNotFound;
5523     }
5524 
5525     default:
5526       return ESR_CaseNotFound;
5527     }
5528   }
5529 
5530   switch (S->getStmtClass()) {
5531   default:
5532     if (const Expr *E = dyn_cast<Expr>(S)) {
5533       if (E->isValueDependent()) {
5534         if (!EvaluateDependentExpr(E, Info))
5535           return ESR_Failed;
5536       } else {
5537         // Don't bother evaluating beyond an expression-statement which couldn't
5538         // be evaluated.
5539         // FIXME: Do we need the FullExpressionRAII object here?
5540         // VisitExprWithCleanups should create one when necessary.
5541         FullExpressionRAII Scope(Info);
5542         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5543           return ESR_Failed;
5544       }
5545       return ESR_Succeeded;
5546     }
5547 
5548     Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5549     return ESR_Failed;
5550 
5551   case Stmt::NullStmtClass:
5552     return ESR_Succeeded;
5553 
5554   case Stmt::DeclStmtClass: {
5555     const DeclStmt *DS = cast<DeclStmt>(S);
5556     for (const auto *D : DS->decls()) {
5557       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5558       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5559         return ESR_Failed;
5560       // Each declaration initialization is its own full-expression.
5561       FullExpressionRAII Scope(Info);
5562       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5563         return ESR_Failed;
5564       if (!Scope.destroy())
5565         return ESR_Failed;
5566     }
5567     return ESR_Succeeded;
5568   }
5569 
5570   case Stmt::ReturnStmtClass: {
5571     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5572     FullExpressionRAII Scope(Info);
5573     if (RetExpr && RetExpr->isValueDependent()) {
5574       EvaluateDependentExpr(RetExpr, Info);
5575       // We know we returned, but we don't know what the value is.
5576       return ESR_Failed;
5577     }
5578     if (RetExpr &&
5579         !(Result.Slot
5580               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5581               : Evaluate(Result.Value, Info, RetExpr)))
5582       return ESR_Failed;
5583     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5584   }
5585 
5586   case Stmt::CompoundStmtClass: {
5587     BlockScopeRAII Scope(Info);
5588 
5589     const CompoundStmt *CS = cast<CompoundStmt>(S);
5590     for (const auto *BI : CS->body()) {
5591       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5592       if (ESR == ESR_Succeeded)
5593         Case = nullptr;
5594       else if (ESR != ESR_CaseNotFound) {
5595         if (ESR != ESR_Failed && !Scope.destroy())
5596           return ESR_Failed;
5597         return ESR;
5598       }
5599     }
5600     if (Case)
5601       return ESR_CaseNotFound;
5602     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5603   }
5604 
5605   case Stmt::IfStmtClass: {
5606     const IfStmt *IS = cast<IfStmt>(S);
5607 
5608     // Evaluate the condition, as either a var decl or as an expression.
5609     BlockScopeRAII Scope(Info);
5610     if (const Stmt *Init = IS->getInit()) {
5611       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5612       if (ESR != ESR_Succeeded) {
5613         if (ESR != ESR_Failed && !Scope.destroy())
5614           return ESR_Failed;
5615         return ESR;
5616       }
5617     }
5618     bool Cond;
5619     if (IS->isConsteval()) {
5620       Cond = IS->isNonNegatedConsteval();
5621       // If we are not in a constant context, if consteval should not evaluate
5622       // to true.
5623       if (!Info.InConstantContext)
5624         Cond = !Cond;
5625     } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5626                              Cond))
5627       return ESR_Failed;
5628 
5629     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5630       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5631       if (ESR != ESR_Succeeded) {
5632         if (ESR != ESR_Failed && !Scope.destroy())
5633           return ESR_Failed;
5634         return ESR;
5635       }
5636     }
5637     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5638   }
5639 
5640   case Stmt::WhileStmtClass: {
5641     const WhileStmt *WS = cast<WhileStmt>(S);
5642     while (true) {
5643       BlockScopeRAII Scope(Info);
5644       bool Continue;
5645       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5646                         Continue))
5647         return ESR_Failed;
5648       if (!Continue)
5649         break;
5650 
5651       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5652       if (ESR != ESR_Continue) {
5653         if (ESR != ESR_Failed && !Scope.destroy())
5654           return ESR_Failed;
5655         return ESR;
5656       }
5657       if (!Scope.destroy())
5658         return ESR_Failed;
5659     }
5660     return ESR_Succeeded;
5661   }
5662 
5663   case Stmt::DoStmtClass: {
5664     const DoStmt *DS = cast<DoStmt>(S);
5665     bool Continue;
5666     do {
5667       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5668       if (ESR != ESR_Continue)
5669         return ESR;
5670       Case = nullptr;
5671 
5672       if (DS->getCond()->isValueDependent()) {
5673         EvaluateDependentExpr(DS->getCond(), Info);
5674         // Bailout as we don't know whether to keep going or terminate the loop.
5675         return ESR_Failed;
5676       }
5677       FullExpressionRAII CondScope(Info);
5678       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5679           !CondScope.destroy())
5680         return ESR_Failed;
5681     } while (Continue);
5682     return ESR_Succeeded;
5683   }
5684 
5685   case Stmt::ForStmtClass: {
5686     const ForStmt *FS = cast<ForStmt>(S);
5687     BlockScopeRAII ForScope(Info);
5688     if (FS->getInit()) {
5689       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5690       if (ESR != ESR_Succeeded) {
5691         if (ESR != ESR_Failed && !ForScope.destroy())
5692           return ESR_Failed;
5693         return ESR;
5694       }
5695     }
5696     while (true) {
5697       BlockScopeRAII IterScope(Info);
5698       bool Continue = true;
5699       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5700                                          FS->getCond(), Continue))
5701         return ESR_Failed;
5702       if (!Continue)
5703         break;
5704 
5705       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5706       if (ESR != ESR_Continue) {
5707         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5708           return ESR_Failed;
5709         return ESR;
5710       }
5711 
5712       if (const auto *Inc = FS->getInc()) {
5713         if (Inc->isValueDependent()) {
5714           if (!EvaluateDependentExpr(Inc, Info))
5715             return ESR_Failed;
5716         } else {
5717           FullExpressionRAII IncScope(Info);
5718           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5719             return ESR_Failed;
5720         }
5721       }
5722 
5723       if (!IterScope.destroy())
5724         return ESR_Failed;
5725     }
5726     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5727   }
5728 
5729   case Stmt::CXXForRangeStmtClass: {
5730     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5731     BlockScopeRAII Scope(Info);
5732 
5733     // Evaluate the init-statement if present.
5734     if (FS->getInit()) {
5735       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5736       if (ESR != ESR_Succeeded) {
5737         if (ESR != ESR_Failed && !Scope.destroy())
5738           return ESR_Failed;
5739         return ESR;
5740       }
5741     }
5742 
5743     // Initialize the __range variable.
5744     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5745     if (ESR != ESR_Succeeded) {
5746       if (ESR != ESR_Failed && !Scope.destroy())
5747         return ESR_Failed;
5748       return ESR;
5749     }
5750 
5751     // In error-recovery cases it's possible to get here even if we failed to
5752     // synthesize the __begin and __end variables.
5753     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5754       return ESR_Failed;
5755 
5756     // Create the __begin and __end iterators.
5757     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5758     if (ESR != ESR_Succeeded) {
5759       if (ESR != ESR_Failed && !Scope.destroy())
5760         return ESR_Failed;
5761       return ESR;
5762     }
5763     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5764     if (ESR != ESR_Succeeded) {
5765       if (ESR != ESR_Failed && !Scope.destroy())
5766         return ESR_Failed;
5767       return ESR;
5768     }
5769 
5770     while (true) {
5771       // Condition: __begin != __end.
5772       {
5773         if (FS->getCond()->isValueDependent()) {
5774           EvaluateDependentExpr(FS->getCond(), Info);
5775           // We don't know whether to keep going or terminate the loop.
5776           return ESR_Failed;
5777         }
5778         bool Continue = true;
5779         FullExpressionRAII CondExpr(Info);
5780         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5781           return ESR_Failed;
5782         if (!Continue)
5783           break;
5784       }
5785 
5786       // User's variable declaration, initialized by *__begin.
5787       BlockScopeRAII InnerScope(Info);
5788       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5789       if (ESR != ESR_Succeeded) {
5790         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5791           return ESR_Failed;
5792         return ESR;
5793       }
5794 
5795       // Loop body.
5796       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5797       if (ESR != ESR_Continue) {
5798         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5799           return ESR_Failed;
5800         return ESR;
5801       }
5802       if (FS->getInc()->isValueDependent()) {
5803         if (!EvaluateDependentExpr(FS->getInc(), Info))
5804           return ESR_Failed;
5805       } else {
5806         // Increment: ++__begin
5807         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5808           return ESR_Failed;
5809       }
5810 
5811       if (!InnerScope.destroy())
5812         return ESR_Failed;
5813     }
5814 
5815     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5816   }
5817 
5818   case Stmt::SwitchStmtClass:
5819     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5820 
5821   case Stmt::ContinueStmtClass:
5822     return ESR_Continue;
5823 
5824   case Stmt::BreakStmtClass:
5825     return ESR_Break;
5826 
5827   case Stmt::LabelStmtClass:
5828     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5829 
5830   case Stmt::AttributedStmtClass: {
5831     const auto *AS = cast<AttributedStmt>(S);
5832     const auto *SS = AS->getSubStmt();
5833     MSConstexprContextRAII ConstexprContext(
5834         *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5835                                isa<ReturnStmt>(SS));
5836 
5837     auto LO = Info.getASTContext().getLangOpts();
5838     if (LO.CXXAssumptions && !LO.MSVCCompat) {
5839       for (auto *Attr : AS->getAttrs()) {
5840         auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5841         if (!AA)
5842           continue;
5843 
5844         auto *Assumption = AA->getAssumption();
5845         if (Assumption->isValueDependent())
5846           return ESR_Failed;
5847 
5848         if (Assumption->HasSideEffects(Info.getASTContext()))
5849           continue;
5850 
5851         bool Value;
5852         if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5853           return ESR_Failed;
5854         if (!Value) {
5855           Info.CCEDiag(Assumption->getExprLoc(),
5856                        diag::note_constexpr_assumption_failed);
5857           return ESR_Failed;
5858         }
5859       }
5860     }
5861 
5862     return EvaluateStmt(Result, Info, SS, Case);
5863   }
5864 
5865   case Stmt::CaseStmtClass:
5866   case Stmt::DefaultStmtClass:
5867     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5868   case Stmt::CXXTryStmtClass:
5869     // Evaluate try blocks by evaluating all sub statements.
5870     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5871   }
5872 }
5873 
5874 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5875 /// default constructor. If so, we'll fold it whether or not it's marked as
5876 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5877 /// so we need special handling.
5878 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5879                                            const CXXConstructorDecl *CD,
5880                                            bool IsValueInitialization) {
5881   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5882     return false;
5883 
5884   // Value-initialization does not call a trivial default constructor, so such a
5885   // call is a core constant expression whether or not the constructor is
5886   // constexpr.
5887   if (!CD->isConstexpr() && !IsValueInitialization) {
5888     if (Info.getLangOpts().CPlusPlus11) {
5889       // FIXME: If DiagDecl is an implicitly-declared special member function,
5890       // we should be much more explicit about why it's not constexpr.
5891       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5892         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5893       Info.Note(CD->getLocation(), diag::note_declared_at);
5894     } else {
5895       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5896     }
5897   }
5898   return true;
5899 }
5900 
5901 /// CheckConstexprFunction - Check that a function can be called in a constant
5902 /// expression.
5903 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5904                                    const FunctionDecl *Declaration,
5905                                    const FunctionDecl *Definition,
5906                                    const Stmt *Body) {
5907   // Potential constant expressions can contain calls to declared, but not yet
5908   // defined, constexpr functions.
5909   if (Info.checkingPotentialConstantExpression() && !Definition &&
5910       Declaration->isConstexpr())
5911     return false;
5912 
5913   // Bail out if the function declaration itself is invalid.  We will
5914   // have produced a relevant diagnostic while parsing it, so just
5915   // note the problematic sub-expression.
5916   if (Declaration->isInvalidDecl()) {
5917     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5918     return false;
5919   }
5920 
5921   // DR1872: An instantiated virtual constexpr function can't be called in a
5922   // constant expression (prior to C++20). We can still constant-fold such a
5923   // call.
5924   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5925       cast<CXXMethodDecl>(Declaration)->isVirtual())
5926     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5927 
5928   if (Definition && Definition->isInvalidDecl()) {
5929     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5930     return false;
5931   }
5932 
5933   // Can we evaluate this function call?
5934   if (Definition && Body &&
5935       (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5936                                         Definition->hasAttr<MSConstexprAttr>())))
5937     return true;
5938 
5939   if (Info.getLangOpts().CPlusPlus11) {
5940     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5941 
5942     // If this function is not constexpr because it is an inherited
5943     // non-constexpr constructor, diagnose that directly.
5944     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5945     if (CD && CD->isInheritingConstructor()) {
5946       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5947       if (!Inherited->isConstexpr())
5948         DiagDecl = CD = Inherited;
5949     }
5950 
5951     // FIXME: If DiagDecl is an implicitly-declared special member function
5952     // or an inheriting constructor, we should be much more explicit about why
5953     // it's not constexpr.
5954     if (CD && CD->isInheritingConstructor())
5955       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5956         << CD->getInheritedConstructor().getConstructor()->getParent();
5957     else
5958       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5959         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5960     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5961   } else {
5962     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5963   }
5964   return false;
5965 }
5966 
5967 namespace {
5968 struct CheckDynamicTypeHandler {
5969   AccessKinds AccessKind;
5970   typedef bool result_type;
5971   bool failed() { return false; }
5972   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5973   bool found(APSInt &Value, QualType SubobjType) { return true; }
5974   bool found(APFloat &Value, QualType SubobjType) { return true; }
5975 };
5976 } // end anonymous namespace
5977 
5978 /// Check that we can access the notional vptr of an object / determine its
5979 /// dynamic type.
5980 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5981                              AccessKinds AK, bool Polymorphic) {
5982   // We are not allowed to invoke a virtual function whose dynamic type
5983   // is constexpr-unknown, so stop early and let this fail later on if we
5984   // attempt to do so.
5985   // C++23 [expr.const]p5.6
5986   // an invocation of a virtual function ([class.virtual]) for an object whose
5987   // dynamic type is constexpr-unknown;
5988   if (This.allowConstexprUnknown())
5989     return true;
5990 
5991   if (This.Designator.Invalid)
5992     return false;
5993 
5994   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5995 
5996   if (!Obj)
5997     return false;
5998 
5999   if (!Obj.Value) {
6000     // The object is not usable in constant expressions, so we can't inspect
6001     // its value to see if it's in-lifetime or what the active union members
6002     // are. We can still check for a one-past-the-end lvalue.
6003     if (This.Designator.isOnePastTheEnd() ||
6004         This.Designator.isMostDerivedAnUnsizedArray()) {
6005       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6006                          ? diag::note_constexpr_access_past_end
6007                          : diag::note_constexpr_access_unsized_array)
6008           << AK;
6009       return false;
6010     } else if (Polymorphic) {
6011       // Conservatively refuse to perform a polymorphic operation if we would
6012       // not be able to read a notional 'vptr' value.
6013       APValue Val;
6014       This.moveInto(Val);
6015       QualType StarThisType =
6016           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6017       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6018           << AK << Val.getAsString(Info.Ctx, StarThisType);
6019       return false;
6020     }
6021     return true;
6022   }
6023 
6024   CheckDynamicTypeHandler Handler{AK};
6025   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6026 }
6027 
6028 /// Check that the pointee of the 'this' pointer in a member function call is
6029 /// either within its lifetime or in its period of construction or destruction.
6030 static bool
6031 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
6032                                      const LValue &This,
6033                                      const CXXMethodDecl *NamedMember) {
6034   return checkDynamicType(
6035       Info, E, This,
6036       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6037 }
6038 
6039 struct DynamicType {
6040   /// The dynamic class type of the object.
6041   const CXXRecordDecl *Type;
6042   /// The corresponding path length in the lvalue.
6043   unsigned PathLength;
6044 };
6045 
6046 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6047                                              unsigned PathLength) {
6048   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6049       Designator.Entries.size() && "invalid path length");
6050   return (PathLength == Designator.MostDerivedPathLength)
6051              ? Designator.MostDerivedType->getAsCXXRecordDecl()
6052              : getAsBaseClass(Designator.Entries[PathLength - 1]);
6053 }
6054 
6055 /// Determine the dynamic type of an object.
6056 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6057                                                      const Expr *E,
6058                                                      LValue &This,
6059                                                      AccessKinds AK) {
6060   // If we don't have an lvalue denoting an object of class type, there is no
6061   // meaningful dynamic type. (We consider objects of non-class type to have no
6062   // dynamic type.)
6063   if (!checkDynamicType(Info, E, This, AK,
6064                         (AK == AK_TypeId
6065                              ? (E->getType()->isReferenceType() ? true : false)
6066                              : true)))
6067     return std::nullopt;
6068 
6069   if (This.Designator.Invalid)
6070     return std::nullopt;
6071 
6072   // Refuse to compute a dynamic type in the presence of virtual bases. This
6073   // shouldn't happen other than in constant-folding situations, since literal
6074   // types can't have virtual bases.
6075   //
6076   // Note that consumers of DynamicType assume that the type has no virtual
6077   // bases, and will need modifications if this restriction is relaxed.
6078   const CXXRecordDecl *Class =
6079       This.Designator.MostDerivedType->getAsCXXRecordDecl();
6080   if (!Class || Class->getNumVBases()) {
6081     Info.FFDiag(E);
6082     return std::nullopt;
6083   }
6084 
6085   // FIXME: For very deep class hierarchies, it might be beneficial to use a
6086   // binary search here instead. But the overwhelmingly common case is that
6087   // we're not in the middle of a constructor, so it probably doesn't matter
6088   // in practice.
6089   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6090   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6091        PathLength <= Path.size(); ++PathLength) {
6092     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6093                                       Path.slice(0, PathLength))) {
6094     case ConstructionPhase::Bases:
6095     case ConstructionPhase::DestroyingBases:
6096       // We're constructing or destroying a base class. This is not the dynamic
6097       // type.
6098       break;
6099 
6100     case ConstructionPhase::None:
6101     case ConstructionPhase::AfterBases:
6102     case ConstructionPhase::AfterFields:
6103     case ConstructionPhase::Destroying:
6104       // We've finished constructing the base classes and not yet started
6105       // destroying them again, so this is the dynamic type.
6106       return DynamicType{getBaseClassType(This.Designator, PathLength),
6107                          PathLength};
6108     }
6109   }
6110 
6111   // CWG issue 1517: we're constructing a base class of the object described by
6112   // 'This', so that object has not yet begun its period of construction and
6113   // any polymorphic operation on it results in undefined behavior.
6114   Info.FFDiag(E);
6115   return std::nullopt;
6116 }
6117 
6118 /// Perform virtual dispatch.
6119 static const CXXMethodDecl *HandleVirtualDispatch(
6120     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6121     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6122   std::optional<DynamicType> DynType = ComputeDynamicType(
6123       Info, E, This,
6124       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6125   if (!DynType)
6126     return nullptr;
6127 
6128   // Find the final overrider. It must be declared in one of the classes on the
6129   // path from the dynamic type to the static type.
6130   // FIXME: If we ever allow literal types to have virtual base classes, that
6131   // won't be true.
6132   const CXXMethodDecl *Callee = Found;
6133   unsigned PathLength = DynType->PathLength;
6134   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6135     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6136     const CXXMethodDecl *Overrider =
6137         Found->getCorrespondingMethodDeclaredInClass(Class, false);
6138     if (Overrider) {
6139       Callee = Overrider;
6140       break;
6141     }
6142   }
6143 
6144   // C++2a [class.abstract]p6:
6145   //   the effect of making a virtual call to a pure virtual function [...] is
6146   //   undefined
6147   if (Callee->isPureVirtual()) {
6148     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6149     Info.Note(Callee->getLocation(), diag::note_declared_at);
6150     return nullptr;
6151   }
6152 
6153   // If necessary, walk the rest of the path to determine the sequence of
6154   // covariant adjustment steps to apply.
6155   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6156                                        Found->getReturnType())) {
6157     CovariantAdjustmentPath.push_back(Callee->getReturnType());
6158     for (unsigned CovariantPathLength = PathLength + 1;
6159          CovariantPathLength != This.Designator.Entries.size();
6160          ++CovariantPathLength) {
6161       const CXXRecordDecl *NextClass =
6162           getBaseClassType(This.Designator, CovariantPathLength);
6163       const CXXMethodDecl *Next =
6164           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6165       if (Next && !Info.Ctx.hasSameUnqualifiedType(
6166                       Next->getReturnType(), CovariantAdjustmentPath.back()))
6167         CovariantAdjustmentPath.push_back(Next->getReturnType());
6168     }
6169     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6170                                          CovariantAdjustmentPath.back()))
6171       CovariantAdjustmentPath.push_back(Found->getReturnType());
6172   }
6173 
6174   // Perform 'this' adjustment.
6175   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6176     return nullptr;
6177 
6178   return Callee;
6179 }
6180 
6181 /// Perform the adjustment from a value returned by a virtual function to
6182 /// a value of the statically expected type, which may be a pointer or
6183 /// reference to a base class of the returned type.
6184 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6185                                             APValue &Result,
6186                                             ArrayRef<QualType> Path) {
6187   assert(Result.isLValue() &&
6188          "unexpected kind of APValue for covariant return");
6189   if (Result.isNullPointer())
6190     return true;
6191 
6192   LValue LVal;
6193   LVal.setFrom(Info.Ctx, Result);
6194 
6195   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6196   for (unsigned I = 1; I != Path.size(); ++I) {
6197     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6198     assert(OldClass && NewClass && "unexpected kind of covariant return");
6199     if (OldClass != NewClass &&
6200         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6201       return false;
6202     OldClass = NewClass;
6203   }
6204 
6205   LVal.moveInto(Result);
6206   return true;
6207 }
6208 
6209 /// Determine whether \p Base, which is known to be a direct base class of
6210 /// \p Derived, is a public base class.
6211 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6212                               const CXXRecordDecl *Base) {
6213   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6214     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6215     if (BaseClass && declaresSameEntity(BaseClass, Base))
6216       return BaseSpec.getAccessSpecifier() == AS_public;
6217   }
6218   llvm_unreachable("Base is not a direct base of Derived");
6219 }
6220 
6221 /// Apply the given dynamic cast operation on the provided lvalue.
6222 ///
6223 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
6224 /// to find a suitable target subobject.
6225 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6226                               LValue &Ptr) {
6227   // We can't do anything with a non-symbolic pointer value.
6228   SubobjectDesignator &D = Ptr.Designator;
6229   if (D.Invalid)
6230     return false;
6231 
6232   // C++ [expr.dynamic.cast]p6:
6233   //   If v is a null pointer value, the result is a null pointer value.
6234   if (Ptr.isNullPointer() && !E->isGLValue())
6235     return true;
6236 
6237   // For all the other cases, we need the pointer to point to an object within
6238   // its lifetime / period of construction / destruction, and we need to know
6239   // its dynamic type.
6240   std::optional<DynamicType> DynType =
6241       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6242   if (!DynType)
6243     return false;
6244 
6245   // C++ [expr.dynamic.cast]p7:
6246   //   If T is "pointer to cv void", then the result is a pointer to the most
6247   //   derived object
6248   if (E->getType()->isVoidPointerType())
6249     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6250 
6251   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6252   assert(C && "dynamic_cast target is not void pointer nor class");
6253   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
6254 
6255   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6256     // C++ [expr.dynamic.cast]p9:
6257     if (!E->isGLValue()) {
6258       //   The value of a failed cast to pointer type is the null pointer value
6259       //   of the required result type.
6260       Ptr.setNull(Info.Ctx, E->getType());
6261       return true;
6262     }
6263 
6264     //   A failed cast to reference type throws [...] std::bad_cast.
6265     unsigned DiagKind;
6266     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6267                    DynType->Type->isDerivedFrom(C)))
6268       DiagKind = 0;
6269     else if (!Paths || Paths->begin() == Paths->end())
6270       DiagKind = 1;
6271     else if (Paths->isAmbiguous(CQT))
6272       DiagKind = 2;
6273     else {
6274       assert(Paths->front().Access != AS_public && "why did the cast fail?");
6275       DiagKind = 3;
6276     }
6277     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6278         << DiagKind << Ptr.Designator.getType(Info.Ctx)
6279         << Info.Ctx.getRecordType(DynType->Type)
6280         << E->getType().getUnqualifiedType();
6281     return false;
6282   };
6283 
6284   // Runtime check, phase 1:
6285   //   Walk from the base subobject towards the derived object looking for the
6286   //   target type.
6287   for (int PathLength = Ptr.Designator.Entries.size();
6288        PathLength >= (int)DynType->PathLength; --PathLength) {
6289     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6290     if (declaresSameEntity(Class, C))
6291       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6292     // We can only walk across public inheritance edges.
6293     if (PathLength > (int)DynType->PathLength &&
6294         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6295                            Class))
6296       return RuntimeCheckFailed(nullptr);
6297   }
6298 
6299   // Runtime check, phase 2:
6300   //   Search the dynamic type for an unambiguous public base of type C.
6301   CXXBasePaths Paths(/*FindAmbiguities=*/true,
6302                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
6303   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6304       Paths.front().Access == AS_public) {
6305     // Downcast to the dynamic type...
6306     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6307       return false;
6308     // ... then upcast to the chosen base class subobject.
6309     for (CXXBasePathElement &Elem : Paths.front())
6310       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6311         return false;
6312     return true;
6313   }
6314 
6315   // Otherwise, the runtime check fails.
6316   return RuntimeCheckFailed(&Paths);
6317 }
6318 
6319 namespace {
6320 struct StartLifetimeOfUnionMemberHandler {
6321   EvalInfo &Info;
6322   const Expr *LHSExpr;
6323   const FieldDecl *Field;
6324   bool DuringInit;
6325   bool Failed = false;
6326   static const AccessKinds AccessKind = AK_Assign;
6327 
6328   typedef bool result_type;
6329   bool failed() { return Failed; }
6330   bool found(APValue &Subobj, QualType SubobjType) {
6331     // We are supposed to perform no initialization but begin the lifetime of
6332     // the object. We interpret that as meaning to do what default
6333     // initialization of the object would do if all constructors involved were
6334     // trivial:
6335     //  * All base, non-variant member, and array element subobjects' lifetimes
6336     //    begin
6337     //  * No variant members' lifetimes begin
6338     //  * All scalar subobjects whose lifetimes begin have indeterminate values
6339     assert(SubobjType->isUnionType());
6340     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6341       // This union member is already active. If it's also in-lifetime, there's
6342       // nothing to do.
6343       if (Subobj.getUnionValue().hasValue())
6344         return true;
6345     } else if (DuringInit) {
6346       // We're currently in the process of initializing a different union
6347       // member.  If we carried on, that initialization would attempt to
6348       // store to an inactive union member, resulting in undefined behavior.
6349       Info.FFDiag(LHSExpr,
6350                   diag::note_constexpr_union_member_change_during_init);
6351       return false;
6352     }
6353     APValue Result;
6354     Failed = !handleDefaultInitValue(Field->getType(), Result);
6355     Subobj.setUnion(Field, Result);
6356     return true;
6357   }
6358   bool found(APSInt &Value, QualType SubobjType) {
6359     llvm_unreachable("wrong value kind for union object");
6360   }
6361   bool found(APFloat &Value, QualType SubobjType) {
6362     llvm_unreachable("wrong value kind for union object");
6363   }
6364 };
6365 } // end anonymous namespace
6366 
6367 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6368 
6369 /// Handle a builtin simple-assignment or a call to a trivial assignment
6370 /// operator whose left-hand side might involve a union member access. If it
6371 /// does, implicitly start the lifetime of any accessed union elements per
6372 /// C++20 [class.union]5.
6373 static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6374                                                const Expr *LHSExpr,
6375                                                const LValue &LHS) {
6376   if (LHS.InvalidBase || LHS.Designator.Invalid)
6377     return false;
6378 
6379   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6380   // C++ [class.union]p5:
6381   //   define the set S(E) of subexpressions of E as follows:
6382   unsigned PathLength = LHS.Designator.Entries.size();
6383   for (const Expr *E = LHSExpr; E != nullptr;) {
6384     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
6385     if (auto *ME = dyn_cast<MemberExpr>(E)) {
6386       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6387       // Note that we can't implicitly start the lifetime of a reference,
6388       // so we don't need to proceed any further if we reach one.
6389       if (!FD || FD->getType()->isReferenceType())
6390         break;
6391 
6392       //    ... and also contains A.B if B names a union member ...
6393       if (FD->getParent()->isUnion()) {
6394         //    ... of a non-class, non-array type, or of a class type with a
6395         //    trivial default constructor that is not deleted, or an array of
6396         //    such types.
6397         auto *RD =
6398             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6399         if (!RD || RD->hasTrivialDefaultConstructor())
6400           UnionPathLengths.push_back({PathLength - 1, FD});
6401       }
6402 
6403       E = ME->getBase();
6404       --PathLength;
6405       assert(declaresSameEntity(FD,
6406                                 LHS.Designator.Entries[PathLength]
6407                                     .getAsBaseOrMember().getPointer()));
6408 
6409       //   -- If E is of the form A[B] and is interpreted as a built-in array
6410       //      subscripting operator, S(E) is [S(the array operand, if any)].
6411     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6412       // Step over an ArrayToPointerDecay implicit cast.
6413       auto *Base = ASE->getBase()->IgnoreImplicit();
6414       if (!Base->getType()->isArrayType())
6415         break;
6416 
6417       E = Base;
6418       --PathLength;
6419 
6420     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6421       // Step over a derived-to-base conversion.
6422       E = ICE->getSubExpr();
6423       if (ICE->getCastKind() == CK_NoOp)
6424         continue;
6425       if (ICE->getCastKind() != CK_DerivedToBase &&
6426           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6427         break;
6428       // Walk path backwards as we walk up from the base to the derived class.
6429       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6430         if (Elt->isVirtual()) {
6431           // A class with virtual base classes never has a trivial default
6432           // constructor, so S(E) is empty in this case.
6433           E = nullptr;
6434           break;
6435         }
6436 
6437         --PathLength;
6438         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6439                                   LHS.Designator.Entries[PathLength]
6440                                       .getAsBaseOrMember().getPointer()));
6441       }
6442 
6443     //   -- Otherwise, S(E) is empty.
6444     } else {
6445       break;
6446     }
6447   }
6448 
6449   // Common case: no unions' lifetimes are started.
6450   if (UnionPathLengths.empty())
6451     return true;
6452 
6453   //   if modification of X [would access an inactive union member], an object
6454   //   of the type of X is implicitly created
6455   CompleteObject Obj =
6456       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6457   if (!Obj)
6458     return false;
6459   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6460            llvm::reverse(UnionPathLengths)) {
6461     // Form a designator for the union object.
6462     SubobjectDesignator D = LHS.Designator;
6463     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6464 
6465     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6466                       ConstructionPhase::AfterBases;
6467     StartLifetimeOfUnionMemberHandler StartLifetime{
6468         Info, LHSExpr, LengthAndField.second, DuringInit};
6469     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6470       return false;
6471   }
6472 
6473   return true;
6474 }
6475 
6476 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6477                             CallRef Call, EvalInfo &Info,
6478                             bool NonNull = false) {
6479   LValue LV;
6480   // Create the parameter slot and register its destruction. For a vararg
6481   // argument, create a temporary.
6482   // FIXME: For calling conventions that destroy parameters in the callee,
6483   // should we consider performing destruction when the function returns
6484   // instead?
6485   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6486                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6487                                                        ScopeKind::Call, LV);
6488   if (!EvaluateInPlace(V, Info, LV, Arg))
6489     return false;
6490 
6491   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6492   // undefined behavior, so is non-constant.
6493   if (NonNull && V.isLValue() && V.isNullPointer()) {
6494     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6495     return false;
6496   }
6497 
6498   return true;
6499 }
6500 
6501 /// Evaluate the arguments to a function call.
6502 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6503                          EvalInfo &Info, const FunctionDecl *Callee,
6504                          bool RightToLeft = false) {
6505   bool Success = true;
6506   llvm::SmallBitVector ForbiddenNullArgs;
6507   if (Callee->hasAttr<NonNullAttr>()) {
6508     ForbiddenNullArgs.resize(Args.size());
6509     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6510       if (!Attr->args_size()) {
6511         ForbiddenNullArgs.set();
6512         break;
6513       } else
6514         for (auto Idx : Attr->args()) {
6515           unsigned ASTIdx = Idx.getASTIndex();
6516           if (ASTIdx >= Args.size())
6517             continue;
6518           ForbiddenNullArgs[ASTIdx] = true;
6519         }
6520     }
6521   }
6522   for (unsigned I = 0; I < Args.size(); I++) {
6523     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6524     const ParmVarDecl *PVD =
6525         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6526     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6527     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6528       // If we're checking for a potential constant expression, evaluate all
6529       // initializers even if some of them fail.
6530       if (!Info.noteFailure())
6531         return false;
6532       Success = false;
6533     }
6534   }
6535   return Success;
6536 }
6537 
6538 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6539 /// constructor or assignment operator.
6540 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6541                               const Expr *E, APValue &Result,
6542                               bool CopyObjectRepresentation) {
6543   // Find the reference argument.
6544   CallStackFrame *Frame = Info.CurrentCall;
6545   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6546   if (!RefValue) {
6547     Info.FFDiag(E);
6548     return false;
6549   }
6550 
6551   // Copy out the contents of the RHS object.
6552   LValue RefLValue;
6553   RefLValue.setFrom(Info.Ctx, *RefValue);
6554   return handleLValueToRValueConversion(
6555       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6556       CopyObjectRepresentation);
6557 }
6558 
6559 /// Evaluate a function call.
6560 static bool HandleFunctionCall(SourceLocation CallLoc,
6561                                const FunctionDecl *Callee, const LValue *This,
6562                                const Expr *E, ArrayRef<const Expr *> Args,
6563                                CallRef Call, const Stmt *Body, EvalInfo &Info,
6564                                APValue &Result, const LValue *ResultSlot) {
6565   if (!Info.CheckCallLimit(CallLoc))
6566     return false;
6567 
6568   CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6569 
6570   // For a trivial copy or move assignment, perform an APValue copy. This is
6571   // essential for unions, where the operations performed by the assignment
6572   // operator cannot be represented as statements.
6573   //
6574   // Skip this for non-union classes with no fields; in that case, the defaulted
6575   // copy/move does not actually read the object.
6576   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6577   if (MD && MD->isDefaulted() &&
6578       (MD->getParent()->isUnion() ||
6579        (MD->isTrivial() &&
6580         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6581     assert(This &&
6582            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6583     APValue RHSValue;
6584     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6585                            MD->getParent()->isUnion()))
6586       return false;
6587     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6588                           RHSValue))
6589       return false;
6590     This->moveInto(Result);
6591     return true;
6592   } else if (MD && isLambdaCallOperator(MD)) {
6593     // We're in a lambda; determine the lambda capture field maps unless we're
6594     // just constexpr checking a lambda's call operator. constexpr checking is
6595     // done before the captures have been added to the closure object (unless
6596     // we're inferring constexpr-ness), so we don't have access to them in this
6597     // case. But since we don't need the captures to constexpr check, we can
6598     // just ignore them.
6599     if (!Info.checkingPotentialConstantExpression())
6600       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6601                                         Frame.LambdaThisCaptureField);
6602   }
6603 
6604   StmtResult Ret = {Result, ResultSlot};
6605   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6606   if (ESR == ESR_Succeeded) {
6607     if (Callee->getReturnType()->isVoidType())
6608       return true;
6609     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6610   }
6611   return ESR == ESR_Returned;
6612 }
6613 
6614 /// Evaluate a constructor call.
6615 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6616                                   CallRef Call,
6617                                   const CXXConstructorDecl *Definition,
6618                                   EvalInfo &Info, APValue &Result) {
6619   SourceLocation CallLoc = E->getExprLoc();
6620   if (!Info.CheckCallLimit(CallLoc))
6621     return false;
6622 
6623   const CXXRecordDecl *RD = Definition->getParent();
6624   if (RD->getNumVBases()) {
6625     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6626     return false;
6627   }
6628 
6629   EvalInfo::EvaluatingConstructorRAII EvalObj(
6630       Info,
6631       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6632       RD->getNumBases());
6633   CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6634 
6635   // FIXME: Creating an APValue just to hold a nonexistent return value is
6636   // wasteful.
6637   APValue RetVal;
6638   StmtResult Ret = {RetVal, nullptr};
6639 
6640   // If it's a delegating constructor, delegate.
6641   if (Definition->isDelegatingConstructor()) {
6642     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6643     if ((*I)->getInit()->isValueDependent()) {
6644       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6645         return false;
6646     } else {
6647       FullExpressionRAII InitScope(Info);
6648       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6649           !InitScope.destroy())
6650         return false;
6651     }
6652     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6653   }
6654 
6655   // For a trivial copy or move constructor, perform an APValue copy. This is
6656   // essential for unions (or classes with anonymous union members), where the
6657   // operations performed by the constructor cannot be represented by
6658   // ctor-initializers.
6659   //
6660   // Skip this for empty non-union classes; we should not perform an
6661   // lvalue-to-rvalue conversion on them because their copy constructor does not
6662   // actually read them.
6663   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6664       (Definition->getParent()->isUnion() ||
6665        (Definition->isTrivial() &&
6666         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6667     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6668                              Definition->getParent()->isUnion());
6669   }
6670 
6671   // Reserve space for the struct members.
6672   if (!Result.hasValue()) {
6673     if (!RD->isUnion())
6674       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6675                        std::distance(RD->field_begin(), RD->field_end()));
6676     else
6677       // A union starts with no active member.
6678       Result = APValue((const FieldDecl*)nullptr);
6679   }
6680 
6681   if (RD->isInvalidDecl()) return false;
6682   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6683 
6684   // A scope for temporaries lifetime-extended by reference members.
6685   BlockScopeRAII LifetimeExtendedScope(Info);
6686 
6687   bool Success = true;
6688   unsigned BasesSeen = 0;
6689 #ifndef NDEBUG
6690   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6691 #endif
6692   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6693   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6694     // We might be initializing the same field again if this is an indirect
6695     // field initialization.
6696     if (FieldIt == RD->field_end() ||
6697         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6698       assert(Indirect && "fields out of order?");
6699       return;
6700     }
6701 
6702     // Default-initialize any fields with no explicit initializer.
6703     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6704       assert(FieldIt != RD->field_end() && "missing field?");
6705       if (!FieldIt->isUnnamedBitField())
6706         Success &= handleDefaultInitValue(
6707             FieldIt->getType(),
6708             Result.getStructField(FieldIt->getFieldIndex()));
6709     }
6710     ++FieldIt;
6711   };
6712   for (const auto *I : Definition->inits()) {
6713     LValue Subobject = This;
6714     LValue SubobjectParent = This;
6715     APValue *Value = &Result;
6716 
6717     // Determine the subobject to initialize.
6718     FieldDecl *FD = nullptr;
6719     if (I->isBaseInitializer()) {
6720       QualType BaseType(I->getBaseClass(), 0);
6721 #ifndef NDEBUG
6722       // Non-virtual base classes are initialized in the order in the class
6723       // definition. We have already checked for virtual base classes.
6724       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6725       assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6726              "base class initializers not in expected order");
6727       ++BaseIt;
6728 #endif
6729       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6730                                   BaseType->getAsCXXRecordDecl(), &Layout))
6731         return false;
6732       Value = &Result.getStructBase(BasesSeen++);
6733     } else if ((FD = I->getMember())) {
6734       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6735         return false;
6736       if (RD->isUnion()) {
6737         Result = APValue(FD);
6738         Value = &Result.getUnionValue();
6739       } else {
6740         SkipToField(FD, false);
6741         Value = &Result.getStructField(FD->getFieldIndex());
6742       }
6743     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6744       // Walk the indirect field decl's chain to find the object to initialize,
6745       // and make sure we've initialized every step along it.
6746       auto IndirectFieldChain = IFD->chain();
6747       for (auto *C : IndirectFieldChain) {
6748         FD = cast<FieldDecl>(C);
6749         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6750         // Switch the union field if it differs. This happens if we had
6751         // preceding zero-initialization, and we're now initializing a union
6752         // subobject other than the first.
6753         // FIXME: In this case, the values of the other subobjects are
6754         // specified, since zero-initialization sets all padding bits to zero.
6755         if (!Value->hasValue() ||
6756             (Value->isUnion() && Value->getUnionField() != FD)) {
6757           if (CD->isUnion())
6758             *Value = APValue(FD);
6759           else
6760             // FIXME: This immediately starts the lifetime of all members of
6761             // an anonymous struct. It would be preferable to strictly start
6762             // member lifetime in initialization order.
6763             Success &=
6764                 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6765         }
6766         // Store Subobject as its parent before updating it for the last element
6767         // in the chain.
6768         if (C == IndirectFieldChain.back())
6769           SubobjectParent = Subobject;
6770         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6771           return false;
6772         if (CD->isUnion())
6773           Value = &Value->getUnionValue();
6774         else {
6775           if (C == IndirectFieldChain.front() && !RD->isUnion())
6776             SkipToField(FD, true);
6777           Value = &Value->getStructField(FD->getFieldIndex());
6778         }
6779       }
6780     } else {
6781       llvm_unreachable("unknown base initializer kind");
6782     }
6783 
6784     // Need to override This for implicit field initializers as in this case
6785     // This refers to innermost anonymous struct/union containing initializer,
6786     // not to currently constructed class.
6787     const Expr *Init = I->getInit();
6788     if (Init->isValueDependent()) {
6789       if (!EvaluateDependentExpr(Init, Info))
6790         return false;
6791     } else {
6792       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6793                                     isa<CXXDefaultInitExpr>(Init));
6794       FullExpressionRAII InitScope(Info);
6795       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6796           (FD && FD->isBitField() &&
6797            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6798         // If we're checking for a potential constant expression, evaluate all
6799         // initializers even if some of them fail.
6800         if (!Info.noteFailure())
6801           return false;
6802         Success = false;
6803       }
6804     }
6805 
6806     // This is the point at which the dynamic type of the object becomes this
6807     // class type.
6808     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6809       EvalObj.finishedConstructingBases();
6810   }
6811 
6812   // Default-initialize any remaining fields.
6813   if (!RD->isUnion()) {
6814     for (; FieldIt != RD->field_end(); ++FieldIt) {
6815       if (!FieldIt->isUnnamedBitField())
6816         Success &= handleDefaultInitValue(
6817             FieldIt->getType(),
6818             Result.getStructField(FieldIt->getFieldIndex()));
6819     }
6820   }
6821 
6822   EvalObj.finishedConstructingFields();
6823 
6824   return Success &&
6825          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6826          LifetimeExtendedScope.destroy();
6827 }
6828 
6829 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6830                                   ArrayRef<const Expr*> Args,
6831                                   const CXXConstructorDecl *Definition,
6832                                   EvalInfo &Info, APValue &Result) {
6833   CallScopeRAII CallScope(Info);
6834   CallRef Call = Info.CurrentCall->createCall(Definition);
6835   if (!EvaluateArgs(Args, Call, Info, Definition))
6836     return false;
6837 
6838   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6839          CallScope.destroy();
6840 }
6841 
6842 static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6843                                   const LValue &This, APValue &Value,
6844                                   QualType T) {
6845   // Objects can only be destroyed while they're within their lifetimes.
6846   // FIXME: We have no representation for whether an object of type nullptr_t
6847   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6848   // as indeterminate instead?
6849   if (Value.isAbsent() && !T->isNullPtrType()) {
6850     APValue Printable;
6851     This.moveInto(Printable);
6852     Info.FFDiag(CallRange.getBegin(),
6853                 diag::note_constexpr_destroy_out_of_lifetime)
6854         << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6855     return false;
6856   }
6857 
6858   // Invent an expression for location purposes.
6859   // FIXME: We shouldn't need to do this.
6860   OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6861 
6862   // For arrays, destroy elements right-to-left.
6863   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6864     uint64_t Size = CAT->getZExtSize();
6865     QualType ElemT = CAT->getElementType();
6866 
6867     if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6868       return false;
6869 
6870     LValue ElemLV = This;
6871     ElemLV.addArray(Info, &LocE, CAT);
6872     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6873       return false;
6874 
6875     // Ensure that we have actual array elements available to destroy; the
6876     // destructors might mutate the value, so we can't run them on the array
6877     // filler.
6878     if (Size && Size > Value.getArrayInitializedElts())
6879       expandArray(Value, Value.getArraySize() - 1);
6880 
6881     // The size of the array might have been reduced by
6882     // a placement new.
6883     for (Size = Value.getArraySize(); Size != 0; --Size) {
6884       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6885       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6886           !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6887         return false;
6888     }
6889 
6890     // End the lifetime of this array now.
6891     Value = APValue();
6892     return true;
6893   }
6894 
6895   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6896   if (!RD) {
6897     if (T.isDestructedType()) {
6898       Info.FFDiag(CallRange.getBegin(),
6899                   diag::note_constexpr_unsupported_destruction)
6900           << T;
6901       return false;
6902     }
6903 
6904     Value = APValue();
6905     return true;
6906   }
6907 
6908   if (RD->getNumVBases()) {
6909     Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6910     return false;
6911   }
6912 
6913   const CXXDestructorDecl *DD = RD->getDestructor();
6914   if (!DD && !RD->hasTrivialDestructor()) {
6915     Info.FFDiag(CallRange.getBegin());
6916     return false;
6917   }
6918 
6919   if (!DD || DD->isTrivial() ||
6920       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6921     // A trivial destructor just ends the lifetime of the object. Check for
6922     // this case before checking for a body, because we might not bother
6923     // building a body for a trivial destructor. Note that it doesn't matter
6924     // whether the destructor is constexpr in this case; all trivial
6925     // destructors are constexpr.
6926     //
6927     // If an anonymous union would be destroyed, some enclosing destructor must
6928     // have been explicitly defined, and the anonymous union destruction should
6929     // have no effect.
6930     Value = APValue();
6931     return true;
6932   }
6933 
6934   if (!Info.CheckCallLimit(CallRange.getBegin()))
6935     return false;
6936 
6937   const FunctionDecl *Definition = nullptr;
6938   const Stmt *Body = DD->getBody(Definition);
6939 
6940   if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6941     return false;
6942 
6943   CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6944                        CallRef());
6945 
6946   // We're now in the period of destruction of this object.
6947   unsigned BasesLeft = RD->getNumBases();
6948   EvalInfo::EvaluatingDestructorRAII EvalObj(
6949       Info,
6950       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6951   if (!EvalObj.DidInsert) {
6952     // C++2a [class.dtor]p19:
6953     //   the behavior is undefined if the destructor is invoked for an object
6954     //   whose lifetime has ended
6955     // (Note that formally the lifetime ends when the period of destruction
6956     // begins, even though certain uses of the object remain valid until the
6957     // period of destruction ends.)
6958     Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6959     return false;
6960   }
6961 
6962   // FIXME: Creating an APValue just to hold a nonexistent return value is
6963   // wasteful.
6964   APValue RetVal;
6965   StmtResult Ret = {RetVal, nullptr};
6966   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6967     return false;
6968 
6969   // A union destructor does not implicitly destroy its members.
6970   if (RD->isUnion())
6971     return true;
6972 
6973   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6974 
6975   // We don't have a good way to iterate fields in reverse, so collect all the
6976   // fields first and then walk them backwards.
6977   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6978   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6979     if (FD->isUnnamedBitField())
6980       continue;
6981 
6982     LValue Subobject = This;
6983     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6984       return false;
6985 
6986     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6987     if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6988                                FD->getType()))
6989       return false;
6990   }
6991 
6992   if (BasesLeft != 0)
6993     EvalObj.startedDestroyingBases();
6994 
6995   // Destroy base classes in reverse order.
6996   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6997     --BasesLeft;
6998 
6999     QualType BaseType = Base.getType();
7000     LValue Subobject = This;
7001     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
7002                                 BaseType->getAsCXXRecordDecl(), &Layout))
7003       return false;
7004 
7005     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7006     if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7007                                BaseType))
7008       return false;
7009   }
7010   assert(BasesLeft == 0 && "NumBases was wrong?");
7011 
7012   // The period of destruction ends now. The object is gone.
7013   Value = APValue();
7014   return true;
7015 }
7016 
7017 namespace {
7018 struct DestroyObjectHandler {
7019   EvalInfo &Info;
7020   const Expr *E;
7021   const LValue &This;
7022   const AccessKinds AccessKind;
7023 
7024   typedef bool result_type;
7025   bool failed() { return false; }
7026   bool found(APValue &Subobj, QualType SubobjType) {
7027     return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7028                                  SubobjType);
7029   }
7030   bool found(APSInt &Value, QualType SubobjType) {
7031     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7032     return false;
7033   }
7034   bool found(APFloat &Value, QualType SubobjType) {
7035     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7036     return false;
7037   }
7038 };
7039 }
7040 
7041 /// Perform a destructor or pseudo-destructor call on the given object, which
7042 /// might in general not be a complete object.
7043 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7044                               const LValue &This, QualType ThisType) {
7045   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7046   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7047   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7048 }
7049 
7050 /// Destroy and end the lifetime of the given complete object.
7051 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7052                               APValue::LValueBase LVBase, APValue &Value,
7053                               QualType T) {
7054   // If we've had an unmodeled side-effect, we can't rely on mutable state
7055   // (such as the object we're about to destroy) being correct.
7056   if (Info.EvalStatus.HasSideEffects)
7057     return false;
7058 
7059   LValue LV;
7060   LV.set({LVBase});
7061   return HandleDestructionImpl(Info, Loc, LV, Value, T);
7062 }
7063 
7064 /// Perform a call to 'operator new' or to `__builtin_operator_new'.
7065 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7066                                   LValue &Result) {
7067   if (Info.checkingPotentialConstantExpression() ||
7068       Info.SpeculativeEvaluationDepth)
7069     return false;
7070 
7071   // This is permitted only within a call to std::allocator<T>::allocate.
7072   auto Caller = Info.getStdAllocatorCaller("allocate");
7073   if (!Caller) {
7074     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7075                                      ? diag::note_constexpr_new_untyped
7076                                      : diag::note_constexpr_new);
7077     return false;
7078   }
7079 
7080   QualType ElemType = Caller.ElemType;
7081   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7082     Info.FFDiag(E->getExprLoc(),
7083                 diag::note_constexpr_new_not_complete_object_type)
7084         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7085     return false;
7086   }
7087 
7088   APSInt ByteSize;
7089   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7090     return false;
7091   bool IsNothrow = false;
7092   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7093     EvaluateIgnoredValue(Info, E->getArg(I));
7094     IsNothrow |= E->getType()->isNothrowT();
7095   }
7096 
7097   CharUnits ElemSize;
7098   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7099     return false;
7100   APInt Size, Remainder;
7101   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7102   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7103   if (Remainder != 0) {
7104     // This likely indicates a bug in the implementation of 'std::allocator'.
7105     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7106         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7107     return false;
7108   }
7109 
7110   if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7111                            Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7112     if (IsNothrow) {
7113       Result.setNull(Info.Ctx, E->getType());
7114       return true;
7115     }
7116     return false;
7117   }
7118 
7119   QualType AllocType = Info.Ctx.getConstantArrayType(
7120       ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7121   APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7122   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7123   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7124   return true;
7125 }
7126 
7127 static bool hasVirtualDestructor(QualType T) {
7128   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7129     if (CXXDestructorDecl *DD = RD->getDestructor())
7130       return DD->isVirtual();
7131   return false;
7132 }
7133 
7134 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
7135   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7136     if (CXXDestructorDecl *DD = RD->getDestructor())
7137       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7138   return nullptr;
7139 }
7140 
7141 /// Check that the given object is a suitable pointer to a heap allocation that
7142 /// still exists and is of the right kind for the purpose of a deletion.
7143 ///
7144 /// On success, returns the heap allocation to deallocate. On failure, produces
7145 /// a diagnostic and returns std::nullopt.
7146 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7147                                                  const LValue &Pointer,
7148                                                  DynAlloc::Kind DeallocKind) {
7149   auto PointerAsString = [&] {
7150     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7151   };
7152 
7153   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7154   if (!DA) {
7155     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7156         << PointerAsString();
7157     if (Pointer.Base)
7158       NoteLValueLocation(Info, Pointer.Base);
7159     return std::nullopt;
7160   }
7161 
7162   std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7163   if (!Alloc) {
7164     Info.FFDiag(E, diag::note_constexpr_double_delete);
7165     return std::nullopt;
7166   }
7167 
7168   if (DeallocKind != (*Alloc)->getKind()) {
7169     QualType AllocType = Pointer.Base.getDynamicAllocType();
7170     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7171         << DeallocKind << (*Alloc)->getKind() << AllocType;
7172     NoteLValueLocation(Info, Pointer.Base);
7173     return std::nullopt;
7174   }
7175 
7176   bool Subobject = false;
7177   if (DeallocKind == DynAlloc::New) {
7178     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7179                 Pointer.Designator.isOnePastTheEnd();
7180   } else {
7181     Subobject = Pointer.Designator.Entries.size() != 1 ||
7182                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7183   }
7184   if (Subobject) {
7185     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7186         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7187     return std::nullopt;
7188   }
7189 
7190   return Alloc;
7191 }
7192 
7193 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
7194 static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7195   if (Info.checkingPotentialConstantExpression() ||
7196       Info.SpeculativeEvaluationDepth)
7197     return false;
7198 
7199   // This is permitted only within a call to std::allocator<T>::deallocate.
7200   if (!Info.getStdAllocatorCaller("deallocate")) {
7201     Info.FFDiag(E->getExprLoc());
7202     return true;
7203   }
7204 
7205   LValue Pointer;
7206   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7207     return false;
7208   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7209     EvaluateIgnoredValue(Info, E->getArg(I));
7210 
7211   if (Pointer.Designator.Invalid)
7212     return false;
7213 
7214   // Deleting a null pointer would have no effect, but it's not permitted by
7215   // std::allocator<T>::deallocate's contract.
7216   if (Pointer.isNullPointer()) {
7217     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7218     return true;
7219   }
7220 
7221   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7222     return false;
7223 
7224   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7225   return true;
7226 }
7227 
7228 //===----------------------------------------------------------------------===//
7229 // Generic Evaluation
7230 //===----------------------------------------------------------------------===//
7231 namespace {
7232 
7233 class BitCastBuffer {
7234   // FIXME: We're going to need bit-level granularity when we support
7235   // bit-fields.
7236   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7237   // we don't support a host or target where that is the case. Still, we should
7238   // use a more generic type in case we ever do.
7239   SmallVector<std::optional<unsigned char>, 32> Bytes;
7240 
7241   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7242                 "Need at least 8 bit unsigned char");
7243 
7244   bool TargetIsLittleEndian;
7245 
7246 public:
7247   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7248       : Bytes(Width.getQuantity()),
7249         TargetIsLittleEndian(TargetIsLittleEndian) {}
7250 
7251   [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7252                                 SmallVectorImpl<unsigned char> &Output) const {
7253     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7254       // If a byte of an integer is uninitialized, then the whole integer is
7255       // uninitialized.
7256       if (!Bytes[I.getQuantity()])
7257         return false;
7258       Output.push_back(*Bytes[I.getQuantity()]);
7259     }
7260     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7261       std::reverse(Output.begin(), Output.end());
7262     return true;
7263   }
7264 
7265   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7266     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7267       std::reverse(Input.begin(), Input.end());
7268 
7269     size_t Index = 0;
7270     for (unsigned char Byte : Input) {
7271       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7272       Bytes[Offset.getQuantity() + Index] = Byte;
7273       ++Index;
7274     }
7275   }
7276 
7277   size_t size() { return Bytes.size(); }
7278 };
7279 
7280 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7281 /// target would represent the value at runtime.
7282 class APValueToBufferConverter {
7283   EvalInfo &Info;
7284   BitCastBuffer Buffer;
7285   const CastExpr *BCE;
7286 
7287   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7288                            const CastExpr *BCE)
7289       : Info(Info),
7290         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7291         BCE(BCE) {}
7292 
7293   bool visit(const APValue &Val, QualType Ty) {
7294     return visit(Val, Ty, CharUnits::fromQuantity(0));
7295   }
7296 
7297   // Write out Val with type Ty into Buffer starting at Offset.
7298   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7299     assert((size_t)Offset.getQuantity() <= Buffer.size());
7300 
7301     // As a special case, nullptr_t has an indeterminate value.
7302     if (Ty->isNullPtrType())
7303       return true;
7304 
7305     // Dig through Src to find the byte at SrcOffset.
7306     switch (Val.getKind()) {
7307     case APValue::Indeterminate:
7308     case APValue::None:
7309       return true;
7310 
7311     case APValue::Int:
7312       return visitInt(Val.getInt(), Ty, Offset);
7313     case APValue::Float:
7314       return visitFloat(Val.getFloat(), Ty, Offset);
7315     case APValue::Array:
7316       return visitArray(Val, Ty, Offset);
7317     case APValue::Struct:
7318       return visitRecord(Val, Ty, Offset);
7319     case APValue::Vector:
7320       return visitVector(Val, Ty, Offset);
7321 
7322     case APValue::ComplexInt:
7323     case APValue::ComplexFloat:
7324       return visitComplex(Val, Ty, Offset);
7325     case APValue::FixedPoint:
7326       // FIXME: We should support these.
7327 
7328     case APValue::Union:
7329     case APValue::MemberPointer:
7330     case APValue::AddrLabelDiff: {
7331       Info.FFDiag(BCE->getBeginLoc(),
7332                   diag::note_constexpr_bit_cast_unsupported_type)
7333           << Ty;
7334       return false;
7335     }
7336 
7337     case APValue::LValue:
7338       llvm_unreachable("LValue subobject in bit_cast?");
7339     }
7340     llvm_unreachable("Unhandled APValue::ValueKind");
7341   }
7342 
7343   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7344     const RecordDecl *RD = Ty->getAsRecordDecl();
7345     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7346 
7347     // Visit the base classes.
7348     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7349       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7350         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7351         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7352 
7353         if (!visitRecord(Val.getStructBase(I), BS.getType(),
7354                          Layout.getBaseClassOffset(BaseDecl) + Offset))
7355           return false;
7356       }
7357     }
7358 
7359     // Visit the fields.
7360     unsigned FieldIdx = 0;
7361     for (FieldDecl *FD : RD->fields()) {
7362       if (FD->isBitField()) {
7363         Info.FFDiag(BCE->getBeginLoc(),
7364                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7365         return false;
7366       }
7367 
7368       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7369 
7370       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7371              "only bit-fields can have sub-char alignment");
7372       CharUnits FieldOffset =
7373           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7374       QualType FieldTy = FD->getType();
7375       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7376         return false;
7377       ++FieldIdx;
7378     }
7379 
7380     return true;
7381   }
7382 
7383   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7384     const auto *CAT =
7385         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7386     if (!CAT)
7387       return false;
7388 
7389     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7390     unsigned NumInitializedElts = Val.getArrayInitializedElts();
7391     unsigned ArraySize = Val.getArraySize();
7392     // First, initialize the initialized elements.
7393     for (unsigned I = 0; I != NumInitializedElts; ++I) {
7394       const APValue &SubObj = Val.getArrayInitializedElt(I);
7395       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7396         return false;
7397     }
7398 
7399     // Next, initialize the rest of the array using the filler.
7400     if (Val.hasArrayFiller()) {
7401       const APValue &Filler = Val.getArrayFiller();
7402       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7403         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7404           return false;
7405       }
7406     }
7407 
7408     return true;
7409   }
7410 
7411   bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7412     const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7413     QualType EltTy = ComplexTy->getElementType();
7414     CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7415     bool IsInt = Val.isComplexInt();
7416 
7417     if (IsInt) {
7418       if (!visitInt(Val.getComplexIntReal(), EltTy,
7419                     Offset + (0 * EltSizeChars)))
7420         return false;
7421       if (!visitInt(Val.getComplexIntImag(), EltTy,
7422                     Offset + (1 * EltSizeChars)))
7423         return false;
7424     } else {
7425       if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7426                       Offset + (0 * EltSizeChars)))
7427         return false;
7428       if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7429                       Offset + (1 * EltSizeChars)))
7430         return false;
7431     }
7432 
7433     return true;
7434   }
7435 
7436   bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7437     const VectorType *VTy = Ty->castAs<VectorType>();
7438     QualType EltTy = VTy->getElementType();
7439     unsigned NElts = VTy->getNumElements();
7440 
7441     if (VTy->isExtVectorBoolType()) {
7442       // Special handling for OpenCL bool vectors:
7443       // Since these vectors are stored as packed bits, but we can't write
7444       // individual bits to the BitCastBuffer, we'll buffer all of the elements
7445       // together into an appropriately sized APInt and write them all out at
7446       // once. Because we don't accept vectors where NElts * EltSize isn't a
7447       // multiple of the char size, there will be no padding space, so we don't
7448       // have to worry about writing data which should have been left
7449       // uninitialized.
7450       bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7451 
7452       llvm::APInt Res = llvm::APInt::getZero(NElts);
7453       for (unsigned I = 0; I < NElts; ++I) {
7454         const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7455         assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7456                "bool vector element must be 1-bit unsigned integer!");
7457 
7458         Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7459       }
7460 
7461       SmallVector<uint8_t, 8> Bytes(NElts / 8);
7462       llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7463       Buffer.writeObject(Offset, Bytes);
7464     } else {
7465       // Iterate over each of the elements and write them out to the buffer at
7466       // the appropriate offset.
7467       CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7468       for (unsigned I = 0; I < NElts; ++I) {
7469         if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7470           return false;
7471       }
7472     }
7473 
7474     return true;
7475   }
7476 
7477   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7478     APSInt AdjustedVal = Val;
7479     unsigned Width = AdjustedVal.getBitWidth();
7480     if (Ty->isBooleanType()) {
7481       Width = Info.Ctx.getTypeSize(Ty);
7482       AdjustedVal = AdjustedVal.extend(Width);
7483     }
7484 
7485     SmallVector<uint8_t, 8> Bytes(Width / 8);
7486     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7487     Buffer.writeObject(Offset, Bytes);
7488     return true;
7489   }
7490 
7491   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7492     APSInt AsInt(Val.bitcastToAPInt());
7493     return visitInt(AsInt, Ty, Offset);
7494   }
7495 
7496 public:
7497   static std::optional<BitCastBuffer>
7498   convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7499     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7500     APValueToBufferConverter Converter(Info, DstSize, BCE);
7501     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7502       return std::nullopt;
7503     return Converter.Buffer;
7504   }
7505 };
7506 
7507 /// Write an BitCastBuffer into an APValue.
7508 class BufferToAPValueConverter {
7509   EvalInfo &Info;
7510   const BitCastBuffer &Buffer;
7511   const CastExpr *BCE;
7512 
7513   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7514                            const CastExpr *BCE)
7515       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7516 
7517   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7518   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7519   // Ideally this will be unreachable.
7520   std::nullopt_t unsupportedType(QualType Ty) {
7521     Info.FFDiag(BCE->getBeginLoc(),
7522                 diag::note_constexpr_bit_cast_unsupported_type)
7523         << Ty;
7524     return std::nullopt;
7525   }
7526 
7527   std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7528     Info.FFDiag(BCE->getBeginLoc(),
7529                 diag::note_constexpr_bit_cast_unrepresentable_value)
7530         << Ty << toString(Val, /*Radix=*/10);
7531     return std::nullopt;
7532   }
7533 
7534   std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7535                                const EnumType *EnumSugar = nullptr) {
7536     if (T->isNullPtrType()) {
7537       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7538       return APValue((Expr *)nullptr,
7539                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7540                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7541     }
7542 
7543     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7544 
7545     // Work around floating point types that contain unused padding bytes. This
7546     // is really just `long double` on x86, which is the only fundamental type
7547     // with padding bytes.
7548     if (T->isRealFloatingType()) {
7549       const llvm::fltSemantics &Semantics =
7550           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7551       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7552       assert(NumBits % 8 == 0);
7553       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7554       if (NumBytes != SizeOf)
7555         SizeOf = NumBytes;
7556     }
7557 
7558     SmallVector<uint8_t, 8> Bytes;
7559     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7560       // If this is std::byte or unsigned char, then its okay to store an
7561       // indeterminate value.
7562       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7563       bool IsUChar =
7564           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7565                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7566       if (!IsStdByte && !IsUChar) {
7567         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7568         Info.FFDiag(BCE->getExprLoc(),
7569                     diag::note_constexpr_bit_cast_indet_dest)
7570             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7571         return std::nullopt;
7572       }
7573 
7574       return APValue::IndeterminateValue();
7575     }
7576 
7577     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7578     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7579 
7580     if (T->isIntegralOrEnumerationType()) {
7581       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7582 
7583       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7584       if (IntWidth != Val.getBitWidth()) {
7585         APSInt Truncated = Val.trunc(IntWidth);
7586         if (Truncated.extend(Val.getBitWidth()) != Val)
7587           return unrepresentableValue(QualType(T, 0), Val);
7588         Val = Truncated;
7589       }
7590 
7591       return APValue(Val);
7592     }
7593 
7594     if (T->isRealFloatingType()) {
7595       const llvm::fltSemantics &Semantics =
7596           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7597       return APValue(APFloat(Semantics, Val));
7598     }
7599 
7600     return unsupportedType(QualType(T, 0));
7601   }
7602 
7603   std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7604     const RecordDecl *RD = RTy->getAsRecordDecl();
7605     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7606 
7607     unsigned NumBases = 0;
7608     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7609       NumBases = CXXRD->getNumBases();
7610 
7611     APValue ResultVal(APValue::UninitStruct(), NumBases,
7612                       std::distance(RD->field_begin(), RD->field_end()));
7613 
7614     // Visit the base classes.
7615     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7616       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7617         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7618         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7619 
7620         std::optional<APValue> SubObj = visitType(
7621             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7622         if (!SubObj)
7623           return std::nullopt;
7624         ResultVal.getStructBase(I) = *SubObj;
7625       }
7626     }
7627 
7628     // Visit the fields.
7629     unsigned FieldIdx = 0;
7630     for (FieldDecl *FD : RD->fields()) {
7631       // FIXME: We don't currently support bit-fields. A lot of the logic for
7632       // this is in CodeGen, so we need to factor it around.
7633       if (FD->isBitField()) {
7634         Info.FFDiag(BCE->getBeginLoc(),
7635                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7636         return std::nullopt;
7637       }
7638 
7639       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7640       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7641 
7642       CharUnits FieldOffset =
7643           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7644           Offset;
7645       QualType FieldTy = FD->getType();
7646       std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7647       if (!SubObj)
7648         return std::nullopt;
7649       ResultVal.getStructField(FieldIdx) = *SubObj;
7650       ++FieldIdx;
7651     }
7652 
7653     return ResultVal;
7654   }
7655 
7656   std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7657     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7658     assert(!RepresentationType.isNull() &&
7659            "enum forward decl should be caught by Sema");
7660     const auto *AsBuiltin =
7661         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7662     // Recurse into the underlying type. Treat std::byte transparently as
7663     // unsigned char.
7664     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7665   }
7666 
7667   std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7668     size_t Size = Ty->getLimitedSize();
7669     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7670 
7671     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7672     for (size_t I = 0; I != Size; ++I) {
7673       std::optional<APValue> ElementValue =
7674           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7675       if (!ElementValue)
7676         return std::nullopt;
7677       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7678     }
7679 
7680     return ArrayValue;
7681   }
7682 
7683   std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7684     QualType ElementType = Ty->getElementType();
7685     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7686     bool IsInt = ElementType->isIntegerType();
7687 
7688     std::optional<APValue> Values[2];
7689     for (unsigned I = 0; I != 2; ++I) {
7690       Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7691       if (!Values[I])
7692         return std::nullopt;
7693     }
7694 
7695     if (IsInt)
7696       return APValue(Values[0]->getInt(), Values[1]->getInt());
7697     return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7698   }
7699 
7700   std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7701     QualType EltTy = VTy->getElementType();
7702     unsigned NElts = VTy->getNumElements();
7703     unsigned EltSize =
7704         VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7705 
7706     SmallVector<APValue, 4> Elts;
7707     Elts.reserve(NElts);
7708     if (VTy->isExtVectorBoolType()) {
7709       // Special handling for OpenCL bool vectors:
7710       // Since these vectors are stored as packed bits, but we can't read
7711       // individual bits from the BitCastBuffer, we'll buffer all of the
7712       // elements together into an appropriately sized APInt and write them all
7713       // out at once. Because we don't accept vectors where NElts * EltSize
7714       // isn't a multiple of the char size, there will be no padding space, so
7715       // we don't have to worry about reading any padding data which didn't
7716       // actually need to be accessed.
7717       bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7718 
7719       SmallVector<uint8_t, 8> Bytes;
7720       Bytes.reserve(NElts / 8);
7721       if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7722         return std::nullopt;
7723 
7724       APSInt SValInt(NElts, true);
7725       llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7726 
7727       for (unsigned I = 0; I < NElts; ++I) {
7728         llvm::APInt Elt =
7729             SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7730         Elts.emplace_back(
7731             APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7732       }
7733     } else {
7734       // Iterate over each of the elements and read them from the buffer at
7735       // the appropriate offset.
7736       CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7737       for (unsigned I = 0; I < NElts; ++I) {
7738         std::optional<APValue> EltValue =
7739             visitType(EltTy, Offset + I * EltSizeChars);
7740         if (!EltValue)
7741           return std::nullopt;
7742         Elts.push_back(std::move(*EltValue));
7743       }
7744     }
7745 
7746     return APValue(Elts.data(), Elts.size());
7747   }
7748 
7749   std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7750     return unsupportedType(QualType(Ty, 0));
7751   }
7752 
7753   std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7754     QualType Can = Ty.getCanonicalType();
7755 
7756     switch (Can->getTypeClass()) {
7757 #define TYPE(Class, Base)                                                      \
7758   case Type::Class:                                                            \
7759     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7760 #define ABSTRACT_TYPE(Class, Base)
7761 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7762   case Type::Class:                                                            \
7763     llvm_unreachable("non-canonical type should be impossible!");
7764 #define DEPENDENT_TYPE(Class, Base)                                            \
7765   case Type::Class:                                                            \
7766     llvm_unreachable(                                                          \
7767         "dependent types aren't supported in the constant evaluator!");
7768 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7769   case Type::Class:                                                            \
7770     llvm_unreachable("either dependent or not canonical!");
7771 #include "clang/AST/TypeNodes.inc"
7772     }
7773     llvm_unreachable("Unhandled Type::TypeClass");
7774   }
7775 
7776 public:
7777   // Pull out a full value of type DstType.
7778   static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7779                                         const CastExpr *BCE) {
7780     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7781     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7782   }
7783 };
7784 
7785 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7786                                                  QualType Ty, EvalInfo *Info,
7787                                                  const ASTContext &Ctx,
7788                                                  bool CheckingDest) {
7789   Ty = Ty.getCanonicalType();
7790 
7791   auto diag = [&](int Reason) {
7792     if (Info)
7793       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7794           << CheckingDest << (Reason == 4) << Reason;
7795     return false;
7796   };
7797   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7798     if (Info)
7799       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7800           << NoteTy << Construct << Ty;
7801     return false;
7802   };
7803 
7804   if (Ty->isUnionType())
7805     return diag(0);
7806   if (Ty->isPointerType())
7807     return diag(1);
7808   if (Ty->isMemberPointerType())
7809     return diag(2);
7810   if (Ty.isVolatileQualified())
7811     return diag(3);
7812 
7813   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7814     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7815       for (CXXBaseSpecifier &BS : CXXRD->bases())
7816         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7817                                                   CheckingDest))
7818           return note(1, BS.getType(), BS.getBeginLoc());
7819     }
7820     for (FieldDecl *FD : Record->fields()) {
7821       if (FD->getType()->isReferenceType())
7822         return diag(4);
7823       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7824                                                 CheckingDest))
7825         return note(0, FD->getType(), FD->getBeginLoc());
7826     }
7827   }
7828 
7829   if (Ty->isArrayType() &&
7830       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7831                                             Info, Ctx, CheckingDest))
7832     return false;
7833 
7834   if (const auto *VTy = Ty->getAs<VectorType>()) {
7835     QualType EltTy = VTy->getElementType();
7836     unsigned NElts = VTy->getNumElements();
7837     unsigned EltSize = VTy->isExtVectorBoolType() ? 1 : Ctx.getTypeSize(EltTy);
7838 
7839     if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7840       // The vector's size in bits is not a multiple of the target's byte size,
7841       // so its layout is unspecified. For now, we'll simply treat these cases
7842       // as unsupported (this should only be possible with OpenCL bool vectors
7843       // whose element count isn't a multiple of the byte size).
7844       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7845           << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
7846       return false;
7847     }
7848 
7849     if (EltTy->isRealFloatingType() &&
7850         &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
7851       // The layout for x86_fp80 vectors seems to be handled very inconsistently
7852       // by both clang and LLVM, so for now we won't allow bit_casts involving
7853       // it in a constexpr context.
7854       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
7855           << EltTy;
7856       return false;
7857     }
7858   }
7859 
7860   return true;
7861 }
7862 
7863 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7864                                              const ASTContext &Ctx,
7865                                              const CastExpr *BCE) {
7866   bool DestOK = checkBitCastConstexprEligibilityType(
7867       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7868   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7869                                 BCE->getBeginLoc(),
7870                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7871   return SourceOK;
7872 }
7873 
7874 static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7875                                         const APValue &SourceRValue,
7876                                         const CastExpr *BCE) {
7877   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7878          "no host or target supports non 8-bit chars");
7879 
7880   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7881     return false;
7882 
7883   // Read out SourceValue into a char buffer.
7884   std::optional<BitCastBuffer> Buffer =
7885       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7886   if (!Buffer)
7887     return false;
7888 
7889   // Write out the buffer into a new APValue.
7890   std::optional<APValue> MaybeDestValue =
7891       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7892   if (!MaybeDestValue)
7893     return false;
7894 
7895   DestValue = std::move(*MaybeDestValue);
7896   return true;
7897 }
7898 
7899 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7900                                         APValue &SourceValue,
7901                                         const CastExpr *BCE) {
7902   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7903          "no host or target supports non 8-bit chars");
7904   assert(SourceValue.isLValue() &&
7905          "LValueToRValueBitcast requires an lvalue operand!");
7906 
7907   LValue SourceLValue;
7908   APValue SourceRValue;
7909   SourceLValue.setFrom(Info.Ctx, SourceValue);
7910   if (!handleLValueToRValueConversion(
7911           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7912           SourceRValue, /*WantObjectRepresentation=*/true))
7913     return false;
7914 
7915   return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7916 }
7917 
7918 template <class Derived>
7919 class ExprEvaluatorBase
7920   : public ConstStmtVisitor<Derived, bool> {
7921 private:
7922   Derived &getDerived() { return static_cast<Derived&>(*this); }
7923   bool DerivedSuccess(const APValue &V, const Expr *E) {
7924     return getDerived().Success(V, E);
7925   }
7926   bool DerivedZeroInitialization(const Expr *E) {
7927     return getDerived().ZeroInitialization(E);
7928   }
7929 
7930   // Check whether a conditional operator with a non-constant condition is a
7931   // potential constant expression. If neither arm is a potential constant
7932   // expression, then the conditional operator is not either.
7933   template<typename ConditionalOperator>
7934   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7935     assert(Info.checkingPotentialConstantExpression());
7936 
7937     // Speculatively evaluate both arms.
7938     SmallVector<PartialDiagnosticAt, 8> Diag;
7939     {
7940       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7941       StmtVisitorTy::Visit(E->getFalseExpr());
7942       if (Diag.empty())
7943         return;
7944     }
7945 
7946     {
7947       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7948       Diag.clear();
7949       StmtVisitorTy::Visit(E->getTrueExpr());
7950       if (Diag.empty())
7951         return;
7952     }
7953 
7954     Error(E, diag::note_constexpr_conditional_never_const);
7955   }
7956 
7957 
7958   template<typename ConditionalOperator>
7959   bool HandleConditionalOperator(const ConditionalOperator *E) {
7960     bool BoolResult;
7961     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7962       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7963         CheckPotentialConstantConditional(E);
7964         return false;
7965       }
7966       if (Info.noteFailure()) {
7967         StmtVisitorTy::Visit(E->getTrueExpr());
7968         StmtVisitorTy::Visit(E->getFalseExpr());
7969       }
7970       return false;
7971     }
7972 
7973     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7974     return StmtVisitorTy::Visit(EvalExpr);
7975   }
7976 
7977 protected:
7978   EvalInfo &Info;
7979   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7980   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7981 
7982   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7983     return Info.CCEDiag(E, D);
7984   }
7985 
7986   bool ZeroInitialization(const Expr *E) { return Error(E); }
7987 
7988   bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7989     unsigned BuiltinOp = E->getBuiltinCallee();
7990     return BuiltinOp != 0 &&
7991            Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7992   }
7993 
7994 public:
7995   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7996 
7997   EvalInfo &getEvalInfo() { return Info; }
7998 
7999   /// Report an evaluation error. This should only be called when an error is
8000   /// first discovered. When propagating an error, just return false.
8001   bool Error(const Expr *E, diag::kind D) {
8002     Info.FFDiag(E, D) << E->getSourceRange();
8003     return false;
8004   }
8005   bool Error(const Expr *E) {
8006     return Error(E, diag::note_invalid_subexpr_in_const_expr);
8007   }
8008 
8009   bool VisitStmt(const Stmt *) {
8010     llvm_unreachable("Expression evaluator should not be called on stmts");
8011   }
8012   bool VisitExpr(const Expr *E) {
8013     return Error(E);
8014   }
8015 
8016   bool VisitEmbedExpr(const EmbedExpr *E) {
8017     const auto It = E->begin();
8018     return StmtVisitorTy::Visit(*It);
8019   }
8020 
8021   bool VisitPredefinedExpr(const PredefinedExpr *E) {
8022     return StmtVisitorTy::Visit(E->getFunctionName());
8023   }
8024   bool VisitConstantExpr(const ConstantExpr *E) {
8025     if (E->hasAPValueResult())
8026       return DerivedSuccess(E->getAPValueResult(), E);
8027 
8028     return StmtVisitorTy::Visit(E->getSubExpr());
8029   }
8030 
8031   bool VisitParenExpr(const ParenExpr *E)
8032     { return StmtVisitorTy::Visit(E->getSubExpr()); }
8033   bool VisitUnaryExtension(const UnaryOperator *E)
8034     { return StmtVisitorTy::Visit(E->getSubExpr()); }
8035   bool VisitUnaryPlus(const UnaryOperator *E)
8036     { return StmtVisitorTy::Visit(E->getSubExpr()); }
8037   bool VisitChooseExpr(const ChooseExpr *E)
8038     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8039   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8040     { return StmtVisitorTy::Visit(E->getResultExpr()); }
8041   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8042     { return StmtVisitorTy::Visit(E->getReplacement()); }
8043   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8044     TempVersionRAII RAII(*Info.CurrentCall);
8045     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8046     return StmtVisitorTy::Visit(E->getExpr());
8047   }
8048   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8049     TempVersionRAII RAII(*Info.CurrentCall);
8050     // The initializer may not have been parsed yet, or might be erroneous.
8051     if (!E->getExpr())
8052       return Error(E);
8053     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8054     return StmtVisitorTy::Visit(E->getExpr());
8055   }
8056 
8057   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8058     FullExpressionRAII Scope(Info);
8059     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8060   }
8061 
8062   // Temporaries are registered when created, so we don't care about
8063   // CXXBindTemporaryExpr.
8064   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8065     return StmtVisitorTy::Visit(E->getSubExpr());
8066   }
8067 
8068   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8069     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
8070     return static_cast<Derived*>(this)->VisitCastExpr(E);
8071   }
8072   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8073     if (!Info.Ctx.getLangOpts().CPlusPlus20)
8074       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
8075     return static_cast<Derived*>(this)->VisitCastExpr(E);
8076   }
8077   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8078     return static_cast<Derived*>(this)->VisitCastExpr(E);
8079   }
8080 
8081   bool VisitBinaryOperator(const BinaryOperator *E) {
8082     switch (E->getOpcode()) {
8083     default:
8084       return Error(E);
8085 
8086     case BO_Comma:
8087       VisitIgnoredValue(E->getLHS());
8088       return StmtVisitorTy::Visit(E->getRHS());
8089 
8090     case BO_PtrMemD:
8091     case BO_PtrMemI: {
8092       LValue Obj;
8093       if (!HandleMemberPointerAccess(Info, E, Obj))
8094         return false;
8095       APValue Result;
8096       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8097         return false;
8098       return DerivedSuccess(Result, E);
8099     }
8100     }
8101   }
8102 
8103   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8104     return StmtVisitorTy::Visit(E->getSemanticForm());
8105   }
8106 
8107   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8108     // Evaluate and cache the common expression. We treat it as a temporary,
8109     // even though it's not quite the same thing.
8110     LValue CommonLV;
8111     if (!Evaluate(Info.CurrentCall->createTemporary(
8112                       E->getOpaqueValue(),
8113                       getStorageType(Info.Ctx, E->getOpaqueValue()),
8114                       ScopeKind::FullExpression, CommonLV),
8115                   Info, E->getCommon()))
8116       return false;
8117 
8118     return HandleConditionalOperator(E);
8119   }
8120 
8121   bool VisitConditionalOperator(const ConditionalOperator *E) {
8122     bool IsBcpCall = false;
8123     // If the condition (ignoring parens) is a __builtin_constant_p call,
8124     // the result is a constant expression if it can be folded without
8125     // side-effects. This is an important GNU extension. See GCC PR38377
8126     // for discussion.
8127     if (const CallExpr *CallCE =
8128           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8129       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8130         IsBcpCall = true;
8131 
8132     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8133     // constant expression; we can't check whether it's potentially foldable.
8134     // FIXME: We should instead treat __builtin_constant_p as non-constant if
8135     // it would return 'false' in this mode.
8136     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8137       return false;
8138 
8139     FoldConstant Fold(Info, IsBcpCall);
8140     if (!HandleConditionalOperator(E)) {
8141       Fold.keepDiagnostics();
8142       return false;
8143     }
8144 
8145     return true;
8146   }
8147 
8148   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8149     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8150         Value && !Value->isAbsent())
8151       return DerivedSuccess(*Value, E);
8152 
8153     const Expr *Source = E->getSourceExpr();
8154     if (!Source)
8155       return Error(E);
8156     if (Source == E) {
8157       assert(0 && "OpaqueValueExpr recursively refers to itself");
8158       return Error(E);
8159     }
8160     return StmtVisitorTy::Visit(Source);
8161   }
8162 
8163   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8164     for (const Expr *SemE : E->semantics()) {
8165       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8166         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8167         // result expression: there could be two different LValues that would
8168         // refer to the same object in that case, and we can't model that.
8169         if (SemE == E->getResultExpr())
8170           return Error(E);
8171 
8172         // Unique OVEs get evaluated if and when we encounter them when
8173         // emitting the rest of the semantic form, rather than eagerly.
8174         if (OVE->isUnique())
8175           continue;
8176 
8177         LValue LV;
8178         if (!Evaluate(Info.CurrentCall->createTemporary(
8179                           OVE, getStorageType(Info.Ctx, OVE),
8180                           ScopeKind::FullExpression, LV),
8181                       Info, OVE->getSourceExpr()))
8182           return false;
8183       } else if (SemE == E->getResultExpr()) {
8184         if (!StmtVisitorTy::Visit(SemE))
8185           return false;
8186       } else {
8187         if (!EvaluateIgnoredValue(Info, SemE))
8188           return false;
8189       }
8190     }
8191     return true;
8192   }
8193 
8194   bool VisitCallExpr(const CallExpr *E) {
8195     APValue Result;
8196     if (!handleCallExpr(E, Result, nullptr))
8197       return false;
8198     return DerivedSuccess(Result, E);
8199   }
8200 
8201   bool handleCallExpr(const CallExpr *E, APValue &Result,
8202                      const LValue *ResultSlot) {
8203     CallScopeRAII CallScope(Info);
8204 
8205     const Expr *Callee = E->getCallee()->IgnoreParens();
8206     QualType CalleeType = Callee->getType();
8207 
8208     const FunctionDecl *FD = nullptr;
8209     LValue *This = nullptr, ThisVal;
8210     auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
8211     bool HasQualifier = false;
8212 
8213     CallRef Call;
8214 
8215     // Extract function decl and 'this' pointer from the callee.
8216     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8217       const CXXMethodDecl *Member = nullptr;
8218       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8219         // Explicit bound member calls, such as x.f() or p->g();
8220         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
8221           return false;
8222         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8223         if (!Member)
8224           return Error(Callee);
8225         This = &ThisVal;
8226         HasQualifier = ME->hasQualifier();
8227       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8228         // Indirect bound member calls ('.*' or '->*').
8229         const ValueDecl *D =
8230             HandleMemberPointerAccess(Info, BE, ThisVal, false);
8231         if (!D)
8232           return false;
8233         Member = dyn_cast<CXXMethodDecl>(D);
8234         if (!Member)
8235           return Error(Callee);
8236         This = &ThisVal;
8237       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8238         if (!Info.getLangOpts().CPlusPlus20)
8239           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8240         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
8241                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
8242       } else
8243         return Error(Callee);
8244       FD = Member;
8245     } else if (CalleeType->isFunctionPointerType()) {
8246       LValue CalleeLV;
8247       if (!EvaluatePointer(Callee, CalleeLV, Info))
8248         return false;
8249 
8250       if (!CalleeLV.getLValueOffset().isZero())
8251         return Error(Callee);
8252       if (CalleeLV.isNullPointer()) {
8253         Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8254             << const_cast<Expr *>(Callee);
8255         return false;
8256       }
8257       FD = dyn_cast_or_null<FunctionDecl>(
8258           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8259       if (!FD)
8260         return Error(Callee);
8261       // Don't call function pointers which have been cast to some other type.
8262       // Per DR (no number yet), the caller and callee can differ in noexcept.
8263       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8264         CalleeType->getPointeeType(), FD->getType())) {
8265         return Error(E);
8266       }
8267 
8268       // For an (overloaded) assignment expression, evaluate the RHS before the
8269       // LHS.
8270       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8271       if (OCE && OCE->isAssignmentOp()) {
8272         assert(Args.size() == 2 && "wrong number of arguments in assignment");
8273         Call = Info.CurrentCall->createCall(FD);
8274         bool HasThis = false;
8275         if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8276           HasThis = MD->isImplicitObjectMemberFunction();
8277         if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8278                           /*RightToLeft=*/true))
8279           return false;
8280       }
8281 
8282       // Overloaded operator calls to member functions are represented as normal
8283       // calls with '*this' as the first argument.
8284       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8285       if (MD &&
8286           (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8287         // FIXME: When selecting an implicit conversion for an overloaded
8288         // operator delete, we sometimes try to evaluate calls to conversion
8289         // operators without a 'this' parameter!
8290         if (Args.empty())
8291           return Error(E);
8292 
8293         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
8294           return false;
8295 
8296         // If we are calling a static operator, the 'this' argument needs to be
8297         // ignored after being evaluated.
8298         if (MD->isInstance())
8299           This = &ThisVal;
8300 
8301         // If this is syntactically a simple assignment using a trivial
8302         // assignment operator, start the lifetimes of union members as needed,
8303         // per C++20 [class.union]5.
8304         if (Info.getLangOpts().CPlusPlus20 && OCE &&
8305             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8306             !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
8307           return false;
8308 
8309         Args = Args.slice(1);
8310       } else if (MD && MD->isLambdaStaticInvoker()) {
8311         // Map the static invoker for the lambda back to the call operator.
8312         // Conveniently, we don't have to slice out the 'this' argument (as is
8313         // being done for the non-static case), since a static member function
8314         // doesn't have an implicit argument passed in.
8315         const CXXRecordDecl *ClosureClass = MD->getParent();
8316         assert(
8317             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8318             "Number of captures must be zero for conversion to function-ptr");
8319 
8320         const CXXMethodDecl *LambdaCallOp =
8321             ClosureClass->getLambdaCallOperator();
8322 
8323         // Set 'FD', the function that will be called below, to the call
8324         // operator.  If the closure object represents a generic lambda, find
8325         // the corresponding specialization of the call operator.
8326 
8327         if (ClosureClass->isGenericLambda()) {
8328           assert(MD->isFunctionTemplateSpecialization() &&
8329                  "A generic lambda's static-invoker function must be a "
8330                  "template specialization");
8331           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8332           FunctionTemplateDecl *CallOpTemplate =
8333               LambdaCallOp->getDescribedFunctionTemplate();
8334           void *InsertPos = nullptr;
8335           FunctionDecl *CorrespondingCallOpSpecialization =
8336               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8337           assert(CorrespondingCallOpSpecialization &&
8338                  "We must always have a function call operator specialization "
8339                  "that corresponds to our static invoker specialization");
8340           assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8341           FD = CorrespondingCallOpSpecialization;
8342         } else
8343           FD = LambdaCallOp;
8344       } else if (FD->isReplaceableGlobalAllocationFunction()) {
8345         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8346             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8347           LValue Ptr;
8348           if (!HandleOperatorNewCall(Info, E, Ptr))
8349             return false;
8350           Ptr.moveInto(Result);
8351           return CallScope.destroy();
8352         } else {
8353           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8354         }
8355       }
8356     } else
8357       return Error(E);
8358 
8359     // Evaluate the arguments now if we've not already done so.
8360     if (!Call) {
8361       Call = Info.CurrentCall->createCall(FD);
8362       if (!EvaluateArgs(Args, Call, Info, FD))
8363         return false;
8364     }
8365 
8366     SmallVector<QualType, 4> CovariantAdjustmentPath;
8367     if (This) {
8368       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8369       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8370         // Perform virtual dispatch, if necessary.
8371         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8372                                    CovariantAdjustmentPath);
8373         if (!FD)
8374           return false;
8375       } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8376         // Check that the 'this' pointer points to an object of the right type.
8377         // FIXME: If this is an assignment operator call, we may need to change
8378         // the active union member before we check this.
8379         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8380           return false;
8381       }
8382     }
8383 
8384     // Destructor calls are different enough that they have their own codepath.
8385     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8386       assert(This && "no 'this' pointer for destructor call");
8387       return HandleDestruction(Info, E, *This,
8388                                Info.Ctx.getRecordType(DD->getParent())) &&
8389              CallScope.destroy();
8390     }
8391 
8392     const FunctionDecl *Definition = nullptr;
8393     Stmt *Body = FD->getBody(Definition);
8394 
8395     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8396         !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8397                             Body, Info, Result, ResultSlot))
8398       return false;
8399 
8400     if (!CovariantAdjustmentPath.empty() &&
8401         !HandleCovariantReturnAdjustment(Info, E, Result,
8402                                          CovariantAdjustmentPath))
8403       return false;
8404 
8405     return CallScope.destroy();
8406   }
8407 
8408   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8409     return StmtVisitorTy::Visit(E->getInitializer());
8410   }
8411   bool VisitInitListExpr(const InitListExpr *E) {
8412     if (E->getNumInits() == 0)
8413       return DerivedZeroInitialization(E);
8414     if (E->getNumInits() == 1)
8415       return StmtVisitorTy::Visit(E->getInit(0));
8416     return Error(E);
8417   }
8418   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8419     return DerivedZeroInitialization(E);
8420   }
8421   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8422     return DerivedZeroInitialization(E);
8423   }
8424   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8425     return DerivedZeroInitialization(E);
8426   }
8427 
8428   /// A member expression where the object is a prvalue is itself a prvalue.
8429   bool VisitMemberExpr(const MemberExpr *E) {
8430     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8431            "missing temporary materialization conversion");
8432     assert(!E->isArrow() && "missing call to bound member function?");
8433 
8434     APValue Val;
8435     if (!Evaluate(Val, Info, E->getBase()))
8436       return false;
8437 
8438     QualType BaseTy = E->getBase()->getType();
8439 
8440     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8441     if (!FD) return Error(E);
8442     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8443     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8444            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8445 
8446     // Note: there is no lvalue base here. But this case should only ever
8447     // happen in C or in C++98, where we cannot be evaluating a constexpr
8448     // constructor, which is the only case the base matters.
8449     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8450     SubobjectDesignator Designator(BaseTy);
8451     Designator.addDeclUnchecked(FD);
8452 
8453     APValue Result;
8454     return extractSubobject(Info, E, Obj, Designator, Result) &&
8455            DerivedSuccess(Result, E);
8456   }
8457 
8458   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8459     APValue Val;
8460     if (!Evaluate(Val, Info, E->getBase()))
8461       return false;
8462 
8463     if (Val.isVector()) {
8464       SmallVector<uint32_t, 4> Indices;
8465       E->getEncodedElementAccess(Indices);
8466       if (Indices.size() == 1) {
8467         // Return scalar.
8468         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8469       } else {
8470         // Construct new APValue vector.
8471         SmallVector<APValue, 4> Elts;
8472         for (unsigned I = 0; I < Indices.size(); ++I) {
8473           Elts.push_back(Val.getVectorElt(Indices[I]));
8474         }
8475         APValue VecResult(Elts.data(), Indices.size());
8476         return DerivedSuccess(VecResult, E);
8477       }
8478     }
8479 
8480     return false;
8481   }
8482 
8483   bool VisitCastExpr(const CastExpr *E) {
8484     switch (E->getCastKind()) {
8485     default:
8486       break;
8487 
8488     case CK_AtomicToNonAtomic: {
8489       APValue AtomicVal;
8490       // This does not need to be done in place even for class/array types:
8491       // atomic-to-non-atomic conversion implies copying the object
8492       // representation.
8493       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8494         return false;
8495       return DerivedSuccess(AtomicVal, E);
8496     }
8497 
8498     case CK_NoOp:
8499     case CK_UserDefinedConversion:
8500       return StmtVisitorTy::Visit(E->getSubExpr());
8501 
8502     case CK_LValueToRValue: {
8503       LValue LVal;
8504       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8505         return false;
8506       APValue RVal;
8507       // Note, we use the subexpression's type in order to retain cv-qualifiers.
8508       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8509                                           LVal, RVal))
8510         return false;
8511       return DerivedSuccess(RVal, E);
8512     }
8513     case CK_LValueToRValueBitCast: {
8514       APValue DestValue, SourceValue;
8515       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8516         return false;
8517       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8518         return false;
8519       return DerivedSuccess(DestValue, E);
8520     }
8521 
8522     case CK_AddressSpaceConversion: {
8523       APValue Value;
8524       if (!Evaluate(Value, Info, E->getSubExpr()))
8525         return false;
8526       return DerivedSuccess(Value, E);
8527     }
8528     }
8529 
8530     return Error(E);
8531   }
8532 
8533   bool VisitUnaryPostInc(const UnaryOperator *UO) {
8534     return VisitUnaryPostIncDec(UO);
8535   }
8536   bool VisitUnaryPostDec(const UnaryOperator *UO) {
8537     return VisitUnaryPostIncDec(UO);
8538   }
8539   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8540     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8541       return Error(UO);
8542 
8543     LValue LVal;
8544     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8545       return false;
8546     APValue RVal;
8547     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8548                       UO->isIncrementOp(), &RVal))
8549       return false;
8550     return DerivedSuccess(RVal, UO);
8551   }
8552 
8553   bool VisitStmtExpr(const StmtExpr *E) {
8554     // We will have checked the full-expressions inside the statement expression
8555     // when they were completed, and don't need to check them again now.
8556     llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8557                                           false);
8558 
8559     const CompoundStmt *CS = E->getSubStmt();
8560     if (CS->body_empty())
8561       return true;
8562 
8563     BlockScopeRAII Scope(Info);
8564     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8565                                            BE = CS->body_end();
8566          /**/; ++BI) {
8567       if (BI + 1 == BE) {
8568         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8569         if (!FinalExpr) {
8570           Info.FFDiag((*BI)->getBeginLoc(),
8571                       diag::note_constexpr_stmt_expr_unsupported);
8572           return false;
8573         }
8574         return this->Visit(FinalExpr) && Scope.destroy();
8575       }
8576 
8577       APValue ReturnValue;
8578       StmtResult Result = { ReturnValue, nullptr };
8579       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8580       if (ESR != ESR_Succeeded) {
8581         // FIXME: If the statement-expression terminated due to 'return',
8582         // 'break', or 'continue', it would be nice to propagate that to
8583         // the outer statement evaluation rather than bailing out.
8584         if (ESR != ESR_Failed)
8585           Info.FFDiag((*BI)->getBeginLoc(),
8586                       diag::note_constexpr_stmt_expr_unsupported);
8587         return false;
8588       }
8589     }
8590 
8591     llvm_unreachable("Return from function from the loop above.");
8592   }
8593 
8594   bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8595     return StmtVisitorTy::Visit(E->getSelectedExpr());
8596   }
8597 
8598   /// Visit a value which is evaluated, but whose value is ignored.
8599   void VisitIgnoredValue(const Expr *E) {
8600     EvaluateIgnoredValue(Info, E);
8601   }
8602 
8603   /// Potentially visit a MemberExpr's base expression.
8604   void VisitIgnoredBaseExpression(const Expr *E) {
8605     // While MSVC doesn't evaluate the base expression, it does diagnose the
8606     // presence of side-effecting behavior.
8607     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8608       return;
8609     VisitIgnoredValue(E);
8610   }
8611 };
8612 
8613 } // namespace
8614 
8615 //===----------------------------------------------------------------------===//
8616 // Common base class for lvalue and temporary evaluation.
8617 //===----------------------------------------------------------------------===//
8618 namespace {
8619 template<class Derived>
8620 class LValueExprEvaluatorBase
8621   : public ExprEvaluatorBase<Derived> {
8622 protected:
8623   LValue &Result;
8624   bool InvalidBaseOK;
8625   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8626   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8627 
8628   bool Success(APValue::LValueBase B) {
8629     Result.set(B);
8630     return true;
8631   }
8632 
8633   bool evaluatePointer(const Expr *E, LValue &Result) {
8634     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8635   }
8636 
8637 public:
8638   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8639       : ExprEvaluatorBaseTy(Info), Result(Result),
8640         InvalidBaseOK(InvalidBaseOK) {}
8641 
8642   bool Success(const APValue &V, const Expr *E) {
8643     Result.setFrom(this->Info.Ctx, V);
8644     return true;
8645   }
8646 
8647   bool VisitMemberExpr(const MemberExpr *E) {
8648     // Handle non-static data members.
8649     QualType BaseTy;
8650     bool EvalOK;
8651     if (E->isArrow()) {
8652       EvalOK = evaluatePointer(E->getBase(), Result);
8653       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8654     } else if (E->getBase()->isPRValue()) {
8655       assert(E->getBase()->getType()->isRecordType());
8656       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8657       BaseTy = E->getBase()->getType();
8658     } else {
8659       EvalOK = this->Visit(E->getBase());
8660       BaseTy = E->getBase()->getType();
8661     }
8662     if (!EvalOK) {
8663       if (!InvalidBaseOK)
8664         return false;
8665       Result.setInvalid(E);
8666       return true;
8667     }
8668 
8669     const ValueDecl *MD = E->getMemberDecl();
8670     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8671       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8672              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8673       (void)BaseTy;
8674       if (!HandleLValueMember(this->Info, E, Result, FD))
8675         return false;
8676     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8677       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8678         return false;
8679     } else
8680       return this->Error(E);
8681 
8682     if (MD->getType()->isReferenceType()) {
8683       APValue RefValue;
8684       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8685                                           RefValue))
8686         return false;
8687       return Success(RefValue, E);
8688     }
8689     return true;
8690   }
8691 
8692   bool VisitBinaryOperator(const BinaryOperator *E) {
8693     switch (E->getOpcode()) {
8694     default:
8695       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8696 
8697     case BO_PtrMemD:
8698     case BO_PtrMemI:
8699       return HandleMemberPointerAccess(this->Info, E, Result);
8700     }
8701   }
8702 
8703   bool VisitCastExpr(const CastExpr *E) {
8704     switch (E->getCastKind()) {
8705     default:
8706       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8707 
8708     case CK_DerivedToBase:
8709     case CK_UncheckedDerivedToBase:
8710       if (!this->Visit(E->getSubExpr()))
8711         return false;
8712 
8713       // Now figure out the necessary offset to add to the base LV to get from
8714       // the derived class to the base class.
8715       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8716                                   Result);
8717     }
8718   }
8719 };
8720 }
8721 
8722 //===----------------------------------------------------------------------===//
8723 // LValue Evaluation
8724 //
8725 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8726 // function designators (in C), decl references to void objects (in C), and
8727 // temporaries (if building with -Wno-address-of-temporary).
8728 //
8729 // LValue evaluation produces values comprising a base expression of one of the
8730 // following types:
8731 // - Declarations
8732 //  * VarDecl
8733 //  * FunctionDecl
8734 // - Literals
8735 //  * CompoundLiteralExpr in C (and in global scope in C++)
8736 //  * StringLiteral
8737 //  * PredefinedExpr
8738 //  * ObjCStringLiteralExpr
8739 //  * ObjCEncodeExpr
8740 //  * AddrLabelExpr
8741 //  * BlockExpr
8742 //  * CallExpr for a MakeStringConstant builtin
8743 // - typeid(T) expressions, as TypeInfoLValues
8744 // - Locals and temporaries
8745 //  * MaterializeTemporaryExpr
8746 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8747 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8748 //    from the AST (FIXME).
8749 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8750 //    CallIndex, for a lifetime-extended temporary.
8751 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8752 //    immediate invocation.
8753 // plus an offset in bytes.
8754 //===----------------------------------------------------------------------===//
8755 namespace {
8756 class LValueExprEvaluator
8757   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8758 public:
8759   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8760     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8761 
8762   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8763   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8764 
8765   bool VisitCallExpr(const CallExpr *E);
8766   bool VisitDeclRefExpr(const DeclRefExpr *E);
8767   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8768   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8769   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8770   bool VisitMemberExpr(const MemberExpr *E);
8771   bool VisitStringLiteral(const StringLiteral *E) {
8772     return Success(APValue::LValueBase(
8773         E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8774   }
8775   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8776   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8777   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8778   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8779   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8780   bool VisitUnaryDeref(const UnaryOperator *E);
8781   bool VisitUnaryReal(const UnaryOperator *E);
8782   bool VisitUnaryImag(const UnaryOperator *E);
8783   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8784     return VisitUnaryPreIncDec(UO);
8785   }
8786   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8787     return VisitUnaryPreIncDec(UO);
8788   }
8789   bool VisitBinAssign(const BinaryOperator *BO);
8790   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8791 
8792   bool VisitCastExpr(const CastExpr *E) {
8793     switch (E->getCastKind()) {
8794     default:
8795       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8796 
8797     case CK_LValueBitCast:
8798       this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8799           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8800       if (!Visit(E->getSubExpr()))
8801         return false;
8802       Result.Designator.setInvalid();
8803       return true;
8804 
8805     case CK_BaseToDerived:
8806       if (!Visit(E->getSubExpr()))
8807         return false;
8808       return HandleBaseToDerivedCast(Info, E, Result);
8809 
8810     case CK_Dynamic:
8811       if (!Visit(E->getSubExpr()))
8812         return false;
8813       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8814     }
8815   }
8816 };
8817 } // end anonymous namespace
8818 
8819 /// Get an lvalue to a field of a lambda's closure type.
8820 static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8821                                 const CXXMethodDecl *MD, const FieldDecl *FD,
8822                                 bool LValueToRValueConversion) {
8823   // Static lambda function call operators can't have captures. We already
8824   // diagnosed this, so bail out here.
8825   if (MD->isStatic()) {
8826     assert(Info.CurrentCall->This == nullptr &&
8827            "This should not be set for a static call operator");
8828     return false;
8829   }
8830 
8831   // Start with 'Result' referring to the complete closure object...
8832   if (MD->isExplicitObjectMemberFunction()) {
8833     // Self may be passed by reference or by value.
8834     const ParmVarDecl *Self = MD->getParamDecl(0);
8835     if (Self->getType()->isReferenceType()) {
8836       APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8837       if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
8838         Result.setFrom(Info.Ctx, *RefValue);
8839     } else {
8840       const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8841       CallStackFrame *Frame =
8842           Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8843               .first;
8844       unsigned Version = Info.CurrentCall->Arguments.Version;
8845       Result.set({VD, Frame->Index, Version});
8846     }
8847   } else
8848     Result = *Info.CurrentCall->This;
8849 
8850   // ... then update it to refer to the field of the closure object
8851   // that represents the capture.
8852   if (!HandleLValueMember(Info, E, Result, FD))
8853     return false;
8854 
8855   // And if the field is of reference type (or if we captured '*this' by
8856   // reference), update 'Result' to refer to what
8857   // the field refers to.
8858   if (LValueToRValueConversion) {
8859     APValue RVal;
8860     if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8861       return false;
8862     Result.setFrom(Info.Ctx, RVal);
8863   }
8864   return true;
8865 }
8866 
8867 /// Evaluate an expression as an lvalue. This can be legitimately called on
8868 /// expressions which are not glvalues, in three cases:
8869 ///  * function designators in C, and
8870 ///  * "extern void" objects
8871 ///  * @selector() expressions in Objective-C
8872 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8873                            bool InvalidBaseOK) {
8874   assert(!E->isValueDependent());
8875   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8876          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8877   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8878 }
8879 
8880 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8881   const NamedDecl *D = E->getDecl();
8882   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8883           UnnamedGlobalConstantDecl>(D))
8884     return Success(cast<ValueDecl>(D));
8885   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8886     return VisitVarDecl(E, VD);
8887   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8888     return Visit(BD->getBinding());
8889   return Error(E);
8890 }
8891 
8892 
8893 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8894   // C++23 [expr.const]p8 If we have a reference type allow unknown references
8895   // and pointers.
8896   bool AllowConstexprUnknown =
8897       Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
8898   // If we are within a lambda's call operator, check whether the 'VD' referred
8899   // to within 'E' actually represents a lambda-capture that maps to a
8900   // data-member/field within the closure object, and if so, evaluate to the
8901   // field or what the field refers to.
8902   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8903       isa<DeclRefExpr>(E) &&
8904       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8905     // We don't always have a complete capture-map when checking or inferring if
8906     // the function call operator meets the requirements of a constexpr function
8907     // - but we don't need to evaluate the captures to determine constexprness
8908     // (dcl.constexpr C++17).
8909     if (Info.checkingPotentialConstantExpression())
8910       return false;
8911 
8912     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8913       const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8914       return HandleLambdaCapture(Info, E, Result, MD, FD,
8915                                  FD->getType()->isReferenceType());
8916     }
8917   }
8918 
8919   CallStackFrame *Frame = nullptr;
8920   unsigned Version = 0;
8921   if (VD->hasLocalStorage()) {
8922     // Only if a local variable was declared in the function currently being
8923     // evaluated, do we expect to be able to find its value in the current
8924     // frame. (Otherwise it was likely declared in an enclosing context and
8925     // could either have a valid evaluatable value (for e.g. a constexpr
8926     // variable) or be ill-formed (and trigger an appropriate evaluation
8927     // diagnostic)).
8928     CallStackFrame *CurrFrame = Info.CurrentCall;
8929     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8930       // Function parameters are stored in some caller's frame. (Usually the
8931       // immediate caller, but for an inherited constructor they may be more
8932       // distant.)
8933       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8934         if (CurrFrame->Arguments) {
8935           VD = CurrFrame->Arguments.getOrigParam(PVD);
8936           Frame =
8937               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8938           Version = CurrFrame->Arguments.Version;
8939         }
8940       } else {
8941         Frame = CurrFrame;
8942         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8943       }
8944     }
8945   }
8946 
8947   if (!VD->getType()->isReferenceType()) {
8948     if (Frame) {
8949       Result.set({VD, Frame->Index, Version});
8950       return true;
8951     }
8952     return Success(VD);
8953   }
8954 
8955   if (!Info.getLangOpts().CPlusPlus11) {
8956     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8957         << VD << VD->getType();
8958     Info.Note(VD->getLocation(), diag::note_declared_at);
8959   }
8960 
8961   APValue *V;
8962   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8963     return false;
8964   if (!V->hasValue()) {
8965     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8966     // adjust the diagnostic to say that.
8967     // C++23 [expr.const]p8 If we have a variable that is unknown reference
8968     // or pointer it may not have a value but still be usable later on so do not
8969     // diagnose.
8970     if (!Info.checkingPotentialConstantExpression() && !AllowConstexprUnknown)
8971       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8972 
8973     // C++23 [expr.const]p8 If we have a variable that is unknown reference or
8974     // pointer try to recover it from the frame and set the result accordingly.
8975     if (VD->getType()->isReferenceType() && AllowConstexprUnknown) {
8976       if (Frame) {
8977         Result.set({VD, Frame->Index, Version});
8978         return true;
8979       }
8980       return Success(VD);
8981     }
8982     return false;
8983   }
8984 
8985   return Success(*V, E);
8986 }
8987 
8988 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8989   if (!IsConstantEvaluatedBuiltinCall(E))
8990     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8991 
8992   switch (E->getBuiltinCallee()) {
8993   default:
8994     return false;
8995   case Builtin::BIas_const:
8996   case Builtin::BIforward:
8997   case Builtin::BIforward_like:
8998   case Builtin::BImove:
8999   case Builtin::BImove_if_noexcept:
9000     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
9001       return Visit(E->getArg(0));
9002     break;
9003   }
9004 
9005   return ExprEvaluatorBaseTy::VisitCallExpr(E);
9006 }
9007 
9008 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9009     const MaterializeTemporaryExpr *E) {
9010   // Walk through the expression to find the materialized temporary itself.
9011   SmallVector<const Expr *, 2> CommaLHSs;
9012   SmallVector<SubobjectAdjustment, 2> Adjustments;
9013   const Expr *Inner =
9014       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9015 
9016   // If we passed any comma operators, evaluate their LHSs.
9017   for (const Expr *E : CommaLHSs)
9018     if (!EvaluateIgnoredValue(Info, E))
9019       return false;
9020 
9021   // A materialized temporary with static storage duration can appear within the
9022   // result of a constant expression evaluation, so we need to preserve its
9023   // value for use outside this evaluation.
9024   APValue *Value;
9025   if (E->getStorageDuration() == SD_Static) {
9026     if (Info.EvalMode == EvalInfo::EM_ConstantFold)
9027       return false;
9028     // FIXME: What about SD_Thread?
9029     Value = E->getOrCreateValue(true);
9030     *Value = APValue();
9031     Result.set(E);
9032   } else {
9033     Value = &Info.CurrentCall->createTemporary(
9034         E, Inner->getType(),
9035         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9036                                                      : ScopeKind::Block,
9037         Result);
9038   }
9039 
9040   QualType Type = Inner->getType();
9041 
9042   // Materialize the temporary itself.
9043   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9044     *Value = APValue();
9045     return false;
9046   }
9047 
9048   // Adjust our lvalue to refer to the desired subobject.
9049   for (unsigned I = Adjustments.size(); I != 0; /**/) {
9050     --I;
9051     switch (Adjustments[I].Kind) {
9052     case SubobjectAdjustment::DerivedToBaseAdjustment:
9053       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9054                                 Type, Result))
9055         return false;
9056       Type = Adjustments[I].DerivedToBase.BasePath->getType();
9057       break;
9058 
9059     case SubobjectAdjustment::FieldAdjustment:
9060       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9061         return false;
9062       Type = Adjustments[I].Field->getType();
9063       break;
9064 
9065     case SubobjectAdjustment::MemberPointerAdjustment:
9066       if (!HandleMemberPointerAccess(this->Info, Type, Result,
9067                                      Adjustments[I].Ptr.RHS))
9068         return false;
9069       Type = Adjustments[I].Ptr.MPT->getPointeeType();
9070       break;
9071     }
9072   }
9073 
9074   return true;
9075 }
9076 
9077 bool
9078 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9079   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9080          "lvalue compound literal in c++?");
9081   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
9082   // only see this when folding in C, so there's no standard to follow here.
9083   return Success(E);
9084 }
9085 
9086 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9087   TypeInfoLValue TypeInfo;
9088 
9089   if (!E->isPotentiallyEvaluated()) {
9090     if (E->isTypeOperand())
9091       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9092     else
9093       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9094   } else {
9095     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9096       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9097         << E->getExprOperand()->getType()
9098         << E->getExprOperand()->getSourceRange();
9099     }
9100 
9101     if (!Visit(E->getExprOperand()))
9102       return false;
9103 
9104     std::optional<DynamicType> DynType =
9105         ComputeDynamicType(Info, E, Result, AK_TypeId);
9106     if (!DynType)
9107       return false;
9108 
9109     TypeInfo =
9110         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
9111   }
9112 
9113   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
9114 }
9115 
9116 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9117   return Success(E->getGuidDecl());
9118 }
9119 
9120 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9121   // Handle static data members.
9122   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9123     VisitIgnoredBaseExpression(E->getBase());
9124     return VisitVarDecl(E, VD);
9125   }
9126 
9127   // Handle static member functions.
9128   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9129     if (MD->isStatic()) {
9130       VisitIgnoredBaseExpression(E->getBase());
9131       return Success(MD);
9132     }
9133   }
9134 
9135   // Handle non-static data members.
9136   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9137 }
9138 
9139 bool LValueExprEvaluator::VisitExtVectorElementExpr(
9140     const ExtVectorElementExpr *E) {
9141   bool Success = true;
9142 
9143   APValue Val;
9144   if (!Evaluate(Val, Info, E->getBase())) {
9145     if (!Info.noteFailure())
9146       return false;
9147     Success = false;
9148   }
9149 
9150   SmallVector<uint32_t, 4> Indices;
9151   E->getEncodedElementAccess(Indices);
9152   // FIXME: support accessing more than one element
9153   if (Indices.size() > 1)
9154     return false;
9155 
9156   if (Success) {
9157     Result.setFrom(Info.Ctx, Val);
9158     const auto *VT = E->getBase()->getType()->castAs<VectorType>();
9159     HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9160                               VT->getNumElements(), Indices[0]);
9161   }
9162 
9163   return Success;
9164 }
9165 
9166 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9167   if (E->getBase()->getType()->isSveVLSBuiltinType())
9168     return Error(E);
9169 
9170   APSInt Index;
9171   bool Success = true;
9172 
9173   if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9174     APValue Val;
9175     if (!Evaluate(Val, Info, E->getBase())) {
9176       if (!Info.noteFailure())
9177         return false;
9178       Success = false;
9179     }
9180 
9181     if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9182       if (!Info.noteFailure())
9183         return false;
9184       Success = false;
9185     }
9186 
9187     if (Success) {
9188       Result.setFrom(Info.Ctx, Val);
9189       HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9190                                 VT->getNumElements(), Index.getExtValue());
9191     }
9192 
9193     return Success;
9194   }
9195 
9196   // C++17's rules require us to evaluate the LHS first, regardless of which
9197   // side is the base.
9198   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9199     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9200                                 : !EvaluateInteger(SubExpr, Index, Info)) {
9201       if (!Info.noteFailure())
9202         return false;
9203       Success = false;
9204     }
9205   }
9206 
9207   return Success &&
9208          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9209 }
9210 
9211 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9212   return evaluatePointer(E->getSubExpr(), Result);
9213 }
9214 
9215 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9216   if (!Visit(E->getSubExpr()))
9217     return false;
9218   // __real is a no-op on scalar lvalues.
9219   if (E->getSubExpr()->getType()->isAnyComplexType())
9220     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9221   return true;
9222 }
9223 
9224 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9225   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9226          "lvalue __imag__ on scalar?");
9227   if (!Visit(E->getSubExpr()))
9228     return false;
9229   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9230   return true;
9231 }
9232 
9233 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9234   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9235     return Error(UO);
9236 
9237   if (!this->Visit(UO->getSubExpr()))
9238     return false;
9239 
9240   return handleIncDec(
9241       this->Info, UO, Result, UO->getSubExpr()->getType(),
9242       UO->isIncrementOp(), nullptr);
9243 }
9244 
9245 bool LValueExprEvaluator::VisitCompoundAssignOperator(
9246     const CompoundAssignOperator *CAO) {
9247   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9248     return Error(CAO);
9249 
9250   bool Success = true;
9251 
9252   // C++17 onwards require that we evaluate the RHS first.
9253   APValue RHS;
9254   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9255     if (!Info.noteFailure())
9256       return false;
9257     Success = false;
9258   }
9259 
9260   // The overall lvalue result is the result of evaluating the LHS.
9261   if (!this->Visit(CAO->getLHS()) || !Success)
9262     return false;
9263 
9264   return handleCompoundAssignment(
9265       this->Info, CAO,
9266       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9267       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9268 }
9269 
9270 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9271   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9272     return Error(E);
9273 
9274   bool Success = true;
9275 
9276   // C++17 onwards require that we evaluate the RHS first.
9277   APValue NewVal;
9278   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9279     if (!Info.noteFailure())
9280       return false;
9281     Success = false;
9282   }
9283 
9284   if (!this->Visit(E->getLHS()) || !Success)
9285     return false;
9286 
9287   if (Info.getLangOpts().CPlusPlus20 &&
9288       !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9289     return false;
9290 
9291   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9292                           NewVal);
9293 }
9294 
9295 //===----------------------------------------------------------------------===//
9296 // Pointer Evaluation
9297 //===----------------------------------------------------------------------===//
9298 
9299 /// Attempts to compute the number of bytes available at the pointer
9300 /// returned by a function with the alloc_size attribute. Returns true if we
9301 /// were successful. Places an unsigned number into `Result`.
9302 ///
9303 /// This expects the given CallExpr to be a call to a function with an
9304 /// alloc_size attribute.
9305 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
9306                                             const CallExpr *Call,
9307                                             llvm::APInt &Result) {
9308   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
9309 
9310   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
9311   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
9312   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
9313   if (Call->getNumArgs() <= SizeArgNo)
9314     return false;
9315 
9316   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
9317     Expr::EvalResult ExprResult;
9318     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
9319       return false;
9320     Into = ExprResult.Val.getInt();
9321     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
9322       return false;
9323     Into = Into.zext(BitsInSizeT);
9324     return true;
9325   };
9326 
9327   APSInt SizeOfElem;
9328   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
9329     return false;
9330 
9331   if (!AllocSize->getNumElemsParam().isValid()) {
9332     Result = std::move(SizeOfElem);
9333     return true;
9334   }
9335 
9336   APSInt NumberOfElems;
9337   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9338   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9339     return false;
9340 
9341   bool Overflow;
9342   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
9343   if (Overflow)
9344     return false;
9345 
9346   Result = std::move(BytesAvailable);
9347   return true;
9348 }
9349 
9350 /// Convenience function. LVal's base must be a call to an alloc_size
9351 /// function.
9352 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
9353                                             const LValue &LVal,
9354                                             llvm::APInt &Result) {
9355   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9356          "Can't get the size of a non alloc_size function");
9357   const auto *Base = LVal.getLValueBase().get<const Expr *>();
9358   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9359   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
9360 }
9361 
9362 /// Attempts to evaluate the given LValueBase as the result of a call to
9363 /// a function with the alloc_size attribute. If it was possible to do so, this
9364 /// function will return true, make Result's Base point to said function call,
9365 /// and mark Result's Base as invalid.
9366 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
9367                                       LValue &Result) {
9368   if (Base.isNull())
9369     return false;
9370 
9371   // Because we do no form of static analysis, we only support const variables.
9372   //
9373   // Additionally, we can't support parameters, nor can we support static
9374   // variables (in the latter case, use-before-assign isn't UB; in the former,
9375   // we have no clue what they'll be assigned to).
9376   const auto *VD =
9377       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9378   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9379     return false;
9380 
9381   const Expr *Init = VD->getAnyInitializer();
9382   if (!Init || Init->getType().isNull())
9383     return false;
9384 
9385   const Expr *E = Init->IgnoreParens();
9386   if (!tryUnwrapAllocSizeCall(E))
9387     return false;
9388 
9389   // Store E instead of E unwrapped so that the type of the LValue's base is
9390   // what the user wanted.
9391   Result.setInvalid(E);
9392 
9393   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9394   Result.addUnsizedArray(Info, E, Pointee);
9395   return true;
9396 }
9397 
9398 namespace {
9399 class PointerExprEvaluator
9400   : public ExprEvaluatorBase<PointerExprEvaluator> {
9401   LValue &Result;
9402   bool InvalidBaseOK;
9403 
9404   bool Success(const Expr *E) {
9405     Result.set(E);
9406     return true;
9407   }
9408 
9409   bool evaluateLValue(const Expr *E, LValue &Result) {
9410     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9411   }
9412 
9413   bool evaluatePointer(const Expr *E, LValue &Result) {
9414     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9415   }
9416 
9417   bool visitNonBuiltinCallExpr(const CallExpr *E);
9418 public:
9419 
9420   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9421       : ExprEvaluatorBaseTy(info), Result(Result),
9422         InvalidBaseOK(InvalidBaseOK) {}
9423 
9424   bool Success(const APValue &V, const Expr *E) {
9425     Result.setFrom(Info.Ctx, V);
9426     return true;
9427   }
9428   bool ZeroInitialization(const Expr *E) {
9429     Result.setNull(Info.Ctx, E->getType());
9430     return true;
9431   }
9432 
9433   bool VisitBinaryOperator(const BinaryOperator *E);
9434   bool VisitCastExpr(const CastExpr* E);
9435   bool VisitUnaryAddrOf(const UnaryOperator *E);
9436   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9437       { return Success(E); }
9438   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9439     if (E->isExpressibleAsConstantInitializer())
9440       return Success(E);
9441     if (Info.noteFailure())
9442       EvaluateIgnoredValue(Info, E->getSubExpr());
9443     return Error(E);
9444   }
9445   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9446       { return Success(E); }
9447   bool VisitCallExpr(const CallExpr *E);
9448   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9449   bool VisitBlockExpr(const BlockExpr *E) {
9450     if (!E->getBlockDecl()->hasCaptures())
9451       return Success(E);
9452     return Error(E);
9453   }
9454   bool VisitCXXThisExpr(const CXXThisExpr *E) {
9455     auto DiagnoseInvalidUseOfThis = [&] {
9456       if (Info.getLangOpts().CPlusPlus11)
9457         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9458       else
9459         Info.FFDiag(E);
9460     };
9461 
9462     // Can't look at 'this' when checking a potential constant expression.
9463     if (Info.checkingPotentialConstantExpression())
9464       return false;
9465 
9466     bool IsExplicitLambda =
9467         isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9468     if (!IsExplicitLambda) {
9469       if (!Info.CurrentCall->This) {
9470         DiagnoseInvalidUseOfThis();
9471         return false;
9472       }
9473 
9474       Result = *Info.CurrentCall->This;
9475     }
9476 
9477     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9478       // Ensure we actually have captured 'this'. If something was wrong with
9479       // 'this' capture, the error would have been previously reported.
9480       // Otherwise we can be inside of a default initialization of an object
9481       // declared by lambda's body, so no need to return false.
9482       if (!Info.CurrentCall->LambdaThisCaptureField) {
9483         if (IsExplicitLambda && !Info.CurrentCall->This) {
9484           DiagnoseInvalidUseOfThis();
9485           return false;
9486         }
9487 
9488         return true;
9489       }
9490 
9491       const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9492       return HandleLambdaCapture(
9493           Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9494           Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9495     }
9496     return true;
9497   }
9498 
9499   bool VisitCXXNewExpr(const CXXNewExpr *E);
9500 
9501   bool VisitSourceLocExpr(const SourceLocExpr *E) {
9502     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9503     APValue LValResult = E->EvaluateInContext(
9504         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9505     Result.setFrom(Info.Ctx, LValResult);
9506     return true;
9507   }
9508 
9509   bool VisitEmbedExpr(const EmbedExpr *E) {
9510     llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9511     return true;
9512   }
9513 
9514   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9515     std::string ResultStr = E->ComputeName(Info.Ctx);
9516 
9517     QualType CharTy = Info.Ctx.CharTy.withConst();
9518     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9519                ResultStr.size() + 1);
9520     QualType ArrayTy = Info.Ctx.getConstantArrayType(
9521         CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9522 
9523     StringLiteral *SL =
9524         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9525                               /*Pascal*/ false, ArrayTy, E->getLocation());
9526 
9527     evaluateLValue(SL, Result);
9528     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9529     return true;
9530   }
9531 
9532   // FIXME: Missing: @protocol, @selector
9533 };
9534 } // end anonymous namespace
9535 
9536 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9537                             bool InvalidBaseOK) {
9538   assert(!E->isValueDependent());
9539   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9540   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9541 }
9542 
9543 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9544   if (E->getOpcode() != BO_Add &&
9545       E->getOpcode() != BO_Sub)
9546     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9547 
9548   const Expr *PExp = E->getLHS();
9549   const Expr *IExp = E->getRHS();
9550   if (IExp->getType()->isPointerType())
9551     std::swap(PExp, IExp);
9552 
9553   bool EvalPtrOK = evaluatePointer(PExp, Result);
9554   if (!EvalPtrOK && !Info.noteFailure())
9555     return false;
9556 
9557   llvm::APSInt Offset;
9558   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9559     return false;
9560 
9561   if (E->getOpcode() == BO_Sub)
9562     negateAsSigned(Offset);
9563 
9564   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9565   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9566 }
9567 
9568 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9569   return evaluateLValue(E->getSubExpr(), Result);
9570 }
9571 
9572 // Is the provided decl 'std::source_location::current'?
9573 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
9574   if (!FD)
9575     return false;
9576   const IdentifierInfo *FnII = FD->getIdentifier();
9577   if (!FnII || !FnII->isStr("current"))
9578     return false;
9579 
9580   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9581   if (!RD)
9582     return false;
9583 
9584   const IdentifierInfo *ClassII = RD->getIdentifier();
9585   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9586 }
9587 
9588 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9589   const Expr *SubExpr = E->getSubExpr();
9590 
9591   switch (E->getCastKind()) {
9592   default:
9593     break;
9594   case CK_BitCast:
9595   case CK_CPointerToObjCPointerCast:
9596   case CK_BlockPointerToObjCPointerCast:
9597   case CK_AnyPointerToBlockPointerCast:
9598   case CK_AddressSpaceConversion:
9599     if (!Visit(SubExpr))
9600       return false;
9601     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9602     // permitted in constant expressions in C++11. Bitcasts from cv void* are
9603     // also static_casts, but we disallow them as a resolution to DR1312.
9604     if (!E->getType()->isVoidPointerType()) {
9605       // In some circumstances, we permit casting from void* to cv1 T*, when the
9606       // actual pointee object is actually a cv2 T.
9607       bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9608                             !Result.IsNullPtr;
9609       bool VoidPtrCastMaybeOK =
9610           Result.IsNullPtr ||
9611           (HasValidResult &&
9612            Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9613                                    E->getType()->getPointeeType()));
9614       // 1. We'll allow it in std::allocator::allocate, and anything which that
9615       //    calls.
9616       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9617       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9618       //    We'll allow it in the body of std::source_location::current.  GCC's
9619       //    implementation had a parameter of type `void*`, and casts from
9620       //    that back to `const __impl*` in its body.
9621       if (VoidPtrCastMaybeOK &&
9622           (Info.getStdAllocatorCaller("allocate") ||
9623            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9624            Info.getLangOpts().CPlusPlus26)) {
9625         // Permitted.
9626       } else {
9627         if (SubExpr->getType()->isVoidPointerType() &&
9628             Info.getLangOpts().CPlusPlus) {
9629           if (HasValidResult)
9630             CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9631                 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9632                 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9633                 << E->getType()->getPointeeType();
9634           else
9635             CCEDiag(E, diag::note_constexpr_invalid_cast)
9636                 << 3 << SubExpr->getType();
9637         } else
9638           CCEDiag(E, diag::note_constexpr_invalid_cast)
9639               << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9640         Result.Designator.setInvalid();
9641       }
9642     }
9643     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9644       ZeroInitialization(E);
9645     return true;
9646 
9647   case CK_DerivedToBase:
9648   case CK_UncheckedDerivedToBase:
9649     if (!evaluatePointer(E->getSubExpr(), Result))
9650       return false;
9651     if (!Result.Base && Result.Offset.isZero())
9652       return true;
9653 
9654     // Now figure out the necessary offset to add to the base LV to get from
9655     // the derived class to the base class.
9656     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9657                                   castAs<PointerType>()->getPointeeType(),
9658                                 Result);
9659 
9660   case CK_BaseToDerived:
9661     if (!Visit(E->getSubExpr()))
9662       return false;
9663     if (!Result.Base && Result.Offset.isZero())
9664       return true;
9665     return HandleBaseToDerivedCast(Info, E, Result);
9666 
9667   case CK_Dynamic:
9668     if (!Visit(E->getSubExpr()))
9669       return false;
9670     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9671 
9672   case CK_NullToPointer:
9673     VisitIgnoredValue(E->getSubExpr());
9674     return ZeroInitialization(E);
9675 
9676   case CK_IntegralToPointer: {
9677     CCEDiag(E, diag::note_constexpr_invalid_cast)
9678         << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9679 
9680     APValue Value;
9681     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9682       break;
9683 
9684     if (Value.isInt()) {
9685       unsigned Size = Info.Ctx.getTypeSize(E->getType());
9686       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9687       Result.Base = (Expr*)nullptr;
9688       Result.InvalidBase = false;
9689       Result.Offset = CharUnits::fromQuantity(N);
9690       Result.Designator.setInvalid();
9691       Result.IsNullPtr = false;
9692       return true;
9693     } else {
9694       // In rare instances, the value isn't an lvalue.
9695       // For example, when the value is the difference between the addresses of
9696       // two labels. We reject that as a constant expression because we can't
9697       // compute a valid offset to convert into a pointer.
9698       if (!Value.isLValue())
9699         return false;
9700 
9701       // Cast is of an lvalue, no need to change value.
9702       Result.setFrom(Info.Ctx, Value);
9703       return true;
9704     }
9705   }
9706 
9707   case CK_ArrayToPointerDecay: {
9708     if (SubExpr->isGLValue()) {
9709       if (!evaluateLValue(SubExpr, Result))
9710         return false;
9711     } else {
9712       APValue &Value = Info.CurrentCall->createTemporary(
9713           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9714       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9715         return false;
9716     }
9717     // The result is a pointer to the first element of the array.
9718     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9719     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9720       Result.addArray(Info, E, CAT);
9721     else
9722       Result.addUnsizedArray(Info, E, AT->getElementType());
9723     return true;
9724   }
9725 
9726   case CK_FunctionToPointerDecay:
9727     return evaluateLValue(SubExpr, Result);
9728 
9729   case CK_LValueToRValue: {
9730     LValue LVal;
9731     if (!evaluateLValue(E->getSubExpr(), LVal))
9732       return false;
9733 
9734     APValue RVal;
9735     // Note, we use the subexpression's type in order to retain cv-qualifiers.
9736     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9737                                         LVal, RVal))
9738       return InvalidBaseOK &&
9739              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9740     return Success(RVal, E);
9741   }
9742   }
9743 
9744   return ExprEvaluatorBaseTy::VisitCastExpr(E);
9745 }
9746 
9747 static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T,
9748                                 UnaryExprOrTypeTrait ExprKind) {
9749   // C++ [expr.alignof]p3:
9750   //     When alignof is applied to a reference type, the result is the
9751   //     alignment of the referenced type.
9752   T = T.getNonReferenceType();
9753 
9754   if (T.getQualifiers().hasUnaligned())
9755     return CharUnits::One();
9756 
9757   const bool AlignOfReturnsPreferred =
9758       Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9759 
9760   // __alignof is defined to return the preferred alignment.
9761   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9762   // as well.
9763   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9764     return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9765   // alignof and _Alignof are defined to return the ABI alignment.
9766   else if (ExprKind == UETT_AlignOf)
9767     return Ctx.getTypeAlignInChars(T.getTypePtr());
9768   else
9769     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9770 }
9771 
9772 CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E,
9773                          UnaryExprOrTypeTrait ExprKind) {
9774   E = E->IgnoreParens();
9775 
9776   // The kinds of expressions that we have special-case logic here for
9777   // should be kept up to date with the special checks for those
9778   // expressions in Sema.
9779 
9780   // alignof decl is always accepted, even if it doesn't make sense: we default
9781   // to 1 in those cases.
9782   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9783     return Ctx.getDeclAlign(DRE->getDecl(),
9784                             /*RefAsPointee*/ true);
9785 
9786   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9787     return Ctx.getDeclAlign(ME->getMemberDecl(),
9788                             /*RefAsPointee*/ true);
9789 
9790   return GetAlignOfType(Ctx, E->getType(), ExprKind);
9791 }
9792 
9793 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9794   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9795     return Info.Ctx.getDeclAlign(VD);
9796   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9797     return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9798   return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9799 }
9800 
9801 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9802 /// __builtin_is_aligned and __builtin_assume_aligned.
9803 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9804                                  EvalInfo &Info, APSInt &Alignment) {
9805   if (!EvaluateInteger(E, Alignment, Info))
9806     return false;
9807   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9808     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9809     return false;
9810   }
9811   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9812   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9813   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9814     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9815         << MaxValue << ForType << Alignment;
9816     return false;
9817   }
9818   // Ensure both alignment and source value have the same bit width so that we
9819   // don't assert when computing the resulting value.
9820   APSInt ExtAlignment =
9821       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9822   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9823          "Alignment should not be changed by ext/trunc");
9824   Alignment = ExtAlignment;
9825   assert(Alignment.getBitWidth() == SrcWidth);
9826   return true;
9827 }
9828 
9829 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9830 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9831   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9832     return true;
9833 
9834   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9835     return false;
9836 
9837   Result.setInvalid(E);
9838   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9839   Result.addUnsizedArray(Info, E, PointeeTy);
9840   return true;
9841 }
9842 
9843 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9844   if (!IsConstantEvaluatedBuiltinCall(E))
9845     return visitNonBuiltinCallExpr(E);
9846   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9847 }
9848 
9849 // Determine if T is a character type for which we guarantee that
9850 // sizeof(T) == 1.
9851 static bool isOneByteCharacterType(QualType T) {
9852   return T->isCharType() || T->isChar8Type();
9853 }
9854 
9855 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9856                                                 unsigned BuiltinOp) {
9857   if (IsOpaqueConstantCall(E))
9858     return Success(E);
9859 
9860   switch (BuiltinOp) {
9861   case Builtin::BIaddressof:
9862   case Builtin::BI__addressof:
9863   case Builtin::BI__builtin_addressof:
9864     return evaluateLValue(E->getArg(0), Result);
9865   case Builtin::BI__builtin_assume_aligned: {
9866     // We need to be very careful here because: if the pointer does not have the
9867     // asserted alignment, then the behavior is undefined, and undefined
9868     // behavior is non-constant.
9869     if (!evaluatePointer(E->getArg(0), Result))
9870       return false;
9871 
9872     LValue OffsetResult(Result);
9873     APSInt Alignment;
9874     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9875                               Alignment))
9876       return false;
9877     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9878 
9879     if (E->getNumArgs() > 2) {
9880       APSInt Offset;
9881       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9882         return false;
9883 
9884       int64_t AdditionalOffset = -Offset.getZExtValue();
9885       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9886     }
9887 
9888     // If there is a base object, then it must have the correct alignment.
9889     if (OffsetResult.Base) {
9890       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9891 
9892       if (BaseAlignment < Align) {
9893         Result.Designator.setInvalid();
9894         CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
9895             << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
9896         return false;
9897       }
9898     }
9899 
9900     // The offset must also have the correct alignment.
9901     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9902       Result.Designator.setInvalid();
9903 
9904       (OffsetResult.Base
9905            ? CCEDiag(E->getArg(0),
9906                      diag::note_constexpr_baa_insufficient_alignment)
9907                  << 1
9908            : CCEDiag(E->getArg(0),
9909                      diag::note_constexpr_baa_value_insufficient_alignment))
9910           << OffsetResult.Offset.getQuantity() << Align.getQuantity();
9911       return false;
9912     }
9913 
9914     return true;
9915   }
9916   case Builtin::BI__builtin_align_up:
9917   case Builtin::BI__builtin_align_down: {
9918     if (!evaluatePointer(E->getArg(0), Result))
9919       return false;
9920     APSInt Alignment;
9921     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9922                               Alignment))
9923       return false;
9924     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9925     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9926     // For align_up/align_down, we can return the same value if the alignment
9927     // is known to be greater or equal to the requested value.
9928     if (PtrAlign.getQuantity() >= Alignment)
9929       return true;
9930 
9931     // The alignment could be greater than the minimum at run-time, so we cannot
9932     // infer much about the resulting pointer value. One case is possible:
9933     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9934     // can infer the correct index if the requested alignment is smaller than
9935     // the base alignment so we can perform the computation on the offset.
9936     if (BaseAlignment.getQuantity() >= Alignment) {
9937       assert(Alignment.getBitWidth() <= 64 &&
9938              "Cannot handle > 64-bit address-space");
9939       uint64_t Alignment64 = Alignment.getZExtValue();
9940       CharUnits NewOffset = CharUnits::fromQuantity(
9941           BuiltinOp == Builtin::BI__builtin_align_down
9942               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9943               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9944       Result.adjustOffset(NewOffset - Result.Offset);
9945       // TODO: diagnose out-of-bounds values/only allow for arrays?
9946       return true;
9947     }
9948     // Otherwise, we cannot constant-evaluate the result.
9949     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9950         << Alignment;
9951     return false;
9952   }
9953   case Builtin::BI__builtin_operator_new:
9954     return HandleOperatorNewCall(Info, E, Result);
9955   case Builtin::BI__builtin_launder:
9956     return evaluatePointer(E->getArg(0), Result);
9957   case Builtin::BIstrchr:
9958   case Builtin::BIwcschr:
9959   case Builtin::BImemchr:
9960   case Builtin::BIwmemchr:
9961     if (Info.getLangOpts().CPlusPlus11)
9962       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9963           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9964           << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
9965     else
9966       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9967     [[fallthrough]];
9968   case Builtin::BI__builtin_strchr:
9969   case Builtin::BI__builtin_wcschr:
9970   case Builtin::BI__builtin_memchr:
9971   case Builtin::BI__builtin_char_memchr:
9972   case Builtin::BI__builtin_wmemchr: {
9973     if (!Visit(E->getArg(0)))
9974       return false;
9975     APSInt Desired;
9976     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9977       return false;
9978     uint64_t MaxLength = uint64_t(-1);
9979     if (BuiltinOp != Builtin::BIstrchr &&
9980         BuiltinOp != Builtin::BIwcschr &&
9981         BuiltinOp != Builtin::BI__builtin_strchr &&
9982         BuiltinOp != Builtin::BI__builtin_wcschr) {
9983       APSInt N;
9984       if (!EvaluateInteger(E->getArg(2), N, Info))
9985         return false;
9986       MaxLength = N.getZExtValue();
9987     }
9988     // We cannot find the value if there are no candidates to match against.
9989     if (MaxLength == 0u)
9990       return ZeroInitialization(E);
9991     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9992         Result.Designator.Invalid)
9993       return false;
9994     QualType CharTy = Result.Designator.getType(Info.Ctx);
9995     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9996                      BuiltinOp == Builtin::BI__builtin_memchr;
9997     assert(IsRawByte ||
9998            Info.Ctx.hasSameUnqualifiedType(
9999                CharTy, E->getArg(0)->getType()->getPointeeType()));
10000     // Pointers to const void may point to objects of incomplete type.
10001     if (IsRawByte && CharTy->isIncompleteType()) {
10002       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10003       return false;
10004     }
10005     // Give up on byte-oriented matching against multibyte elements.
10006     // FIXME: We can compare the bytes in the correct order.
10007     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10008       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10009           << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10010       return false;
10011     }
10012     // Figure out what value we're actually looking for (after converting to
10013     // the corresponding unsigned type if necessary).
10014     uint64_t DesiredVal;
10015     bool StopAtNull = false;
10016     switch (BuiltinOp) {
10017     case Builtin::BIstrchr:
10018     case Builtin::BI__builtin_strchr:
10019       // strchr compares directly to the passed integer, and therefore
10020       // always fails if given an int that is not a char.
10021       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10022                                                   E->getArg(1)->getType(),
10023                                                   Desired),
10024                                Desired))
10025         return ZeroInitialization(E);
10026       StopAtNull = true;
10027       [[fallthrough]];
10028     case Builtin::BImemchr:
10029     case Builtin::BI__builtin_memchr:
10030     case Builtin::BI__builtin_char_memchr:
10031       // memchr compares by converting both sides to unsigned char. That's also
10032       // correct for strchr if we get this far (to cope with plain char being
10033       // unsigned in the strchr case).
10034       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10035       break;
10036 
10037     case Builtin::BIwcschr:
10038     case Builtin::BI__builtin_wcschr:
10039       StopAtNull = true;
10040       [[fallthrough]];
10041     case Builtin::BIwmemchr:
10042     case Builtin::BI__builtin_wmemchr:
10043       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10044       DesiredVal = Desired.getZExtValue();
10045       break;
10046     }
10047 
10048     for (; MaxLength; --MaxLength) {
10049       APValue Char;
10050       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10051           !Char.isInt())
10052         return false;
10053       if (Char.getInt().getZExtValue() == DesiredVal)
10054         return true;
10055       if (StopAtNull && !Char.getInt())
10056         break;
10057       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10058         return false;
10059     }
10060     // Not found: return nullptr.
10061     return ZeroInitialization(E);
10062   }
10063 
10064   case Builtin::BImemcpy:
10065   case Builtin::BImemmove:
10066   case Builtin::BIwmemcpy:
10067   case Builtin::BIwmemmove:
10068     if (Info.getLangOpts().CPlusPlus11)
10069       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10070           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10071           << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10072     else
10073       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10074     [[fallthrough]];
10075   case Builtin::BI__builtin_memcpy:
10076   case Builtin::BI__builtin_memmove:
10077   case Builtin::BI__builtin_wmemcpy:
10078   case Builtin::BI__builtin_wmemmove: {
10079     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10080                  BuiltinOp == Builtin::BIwmemmove ||
10081                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10082                  BuiltinOp == Builtin::BI__builtin_wmemmove;
10083     bool Move = BuiltinOp == Builtin::BImemmove ||
10084                 BuiltinOp == Builtin::BIwmemmove ||
10085                 BuiltinOp == Builtin::BI__builtin_memmove ||
10086                 BuiltinOp == Builtin::BI__builtin_wmemmove;
10087 
10088     // The result of mem* is the first argument.
10089     if (!Visit(E->getArg(0)))
10090       return false;
10091     LValue Dest = Result;
10092 
10093     LValue Src;
10094     if (!EvaluatePointer(E->getArg(1), Src, Info))
10095       return false;
10096 
10097     APSInt N;
10098     if (!EvaluateInteger(E->getArg(2), N, Info))
10099       return false;
10100     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10101 
10102     // If the size is zero, we treat this as always being a valid no-op.
10103     // (Even if one of the src and dest pointers is null.)
10104     if (!N)
10105       return true;
10106 
10107     // Otherwise, if either of the operands is null, we can't proceed. Don't
10108     // try to determine the type of the copied objects, because there aren't
10109     // any.
10110     if (!Src.Base || !Dest.Base) {
10111       APValue Val;
10112       (!Src.Base ? Src : Dest).moveInto(Val);
10113       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10114           << Move << WChar << !!Src.Base
10115           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10116       return false;
10117     }
10118     if (Src.Designator.Invalid || Dest.Designator.Invalid)
10119       return false;
10120 
10121     // We require that Src and Dest are both pointers to arrays of
10122     // trivially-copyable type. (For the wide version, the designator will be
10123     // invalid if the designated object is not a wchar_t.)
10124     QualType T = Dest.Designator.getType(Info.Ctx);
10125     QualType SrcT = Src.Designator.getType(Info.Ctx);
10126     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10127       // FIXME: Consider using our bit_cast implementation to support this.
10128       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10129       return false;
10130     }
10131     if (T->isIncompleteType()) {
10132       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10133       return false;
10134     }
10135     if (!T.isTriviallyCopyableType(Info.Ctx)) {
10136       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10137       return false;
10138     }
10139 
10140     // Figure out how many T's we're copying.
10141     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10142     if (TSize == 0)
10143       return false;
10144     if (!WChar) {
10145       uint64_t Remainder;
10146       llvm::APInt OrigN = N;
10147       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10148       if (Remainder) {
10149         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10150             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10151             << (unsigned)TSize;
10152         return false;
10153       }
10154     }
10155 
10156     // Check that the copying will remain within the arrays, just so that we
10157     // can give a more meaningful diagnostic. This implicitly also checks that
10158     // N fits into 64 bits.
10159     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10160     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10161     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10162       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10163           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10164           << toString(N, 10, /*Signed*/false);
10165       return false;
10166     }
10167     uint64_t NElems = N.getZExtValue();
10168     uint64_t NBytes = NElems * TSize;
10169 
10170     // Check for overlap.
10171     int Direction = 1;
10172     if (HasSameBase(Src, Dest)) {
10173       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10174       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10175       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10176         // Dest is inside the source region.
10177         if (!Move) {
10178           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10179           return false;
10180         }
10181         // For memmove and friends, copy backwards.
10182         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10183             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10184           return false;
10185         Direction = -1;
10186       } else if (!Move && SrcOffset >= DestOffset &&
10187                  SrcOffset - DestOffset < NBytes) {
10188         // Src is inside the destination region for memcpy: invalid.
10189         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10190         return false;
10191       }
10192     }
10193 
10194     while (true) {
10195       APValue Val;
10196       // FIXME: Set WantObjectRepresentation to true if we're copying a
10197       // char-like type?
10198       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10199           !handleAssignment(Info, E, Dest, T, Val))
10200         return false;
10201       // Do not iterate past the last element; if we're copying backwards, that
10202       // might take us off the start of the array.
10203       if (--NElems == 0)
10204         return true;
10205       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10206           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10207         return false;
10208     }
10209   }
10210 
10211   default:
10212     return false;
10213   }
10214 }
10215 
10216 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10217                                      APValue &Result, const InitListExpr *ILE,
10218                                      QualType AllocType);
10219 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10220                                           APValue &Result,
10221                                           const CXXConstructExpr *CCE,
10222                                           QualType AllocType);
10223 
10224 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10225   if (!Info.getLangOpts().CPlusPlus20)
10226     Info.CCEDiag(E, diag::note_constexpr_new);
10227 
10228   // We cannot speculatively evaluate a delete expression.
10229   if (Info.SpeculativeEvaluationDepth)
10230     return false;
10231 
10232   FunctionDecl *OperatorNew = E->getOperatorNew();
10233   QualType AllocType = E->getAllocatedType();
10234   QualType TargetType = AllocType;
10235 
10236   bool IsNothrow = false;
10237   bool IsPlacement = false;
10238 
10239   if (E->getNumPlacementArgs() == 1 &&
10240       E->getPlacementArg(0)->getType()->isNothrowT()) {
10241     // The only new-placement list we support is of the form (std::nothrow).
10242     //
10243     // FIXME: There is no restriction on this, but it's not clear that any
10244     // other form makes any sense. We get here for cases such as:
10245     //
10246     //   new (std::align_val_t{N}) X(int)
10247     //
10248     // (which should presumably be valid only if N is a multiple of
10249     // alignof(int), and in any case can't be deallocated unless N is
10250     // alignof(X) and X has new-extended alignment).
10251     LValue Nothrow;
10252     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10253       return false;
10254     IsNothrow = true;
10255   } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10256     if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10257         (Info.CurrentCall->CanEvalMSConstexpr &&
10258          OperatorNew->hasAttr<MSConstexprAttr>())) {
10259       if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10260         return false;
10261       if (Result.Designator.Invalid)
10262         return false;
10263       TargetType = E->getPlacementArg(0)->getType();
10264       IsPlacement = true;
10265     } else {
10266       Info.FFDiag(E, diag::note_constexpr_new_placement)
10267           << /*C++26 feature*/ 1 << E->getSourceRange();
10268       return false;
10269     }
10270   } else if (E->getNumPlacementArgs()) {
10271     Info.FFDiag(E, diag::note_constexpr_new_placement)
10272         << /*Unsupported*/ 0 << E->getSourceRange();
10273     return false;
10274   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
10275     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10276         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10277     return false;
10278   }
10279 
10280   const Expr *Init = E->getInitializer();
10281   const InitListExpr *ResizedArrayILE = nullptr;
10282   const CXXConstructExpr *ResizedArrayCCE = nullptr;
10283   bool ValueInit = false;
10284 
10285   if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10286     const Expr *Stripped = *ArraySize;
10287     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10288          Stripped = ICE->getSubExpr())
10289       if (ICE->getCastKind() != CK_NoOp &&
10290           ICE->getCastKind() != CK_IntegralCast)
10291         break;
10292 
10293     llvm::APSInt ArrayBound;
10294     if (!EvaluateInteger(Stripped, ArrayBound, Info))
10295       return false;
10296 
10297     // C++ [expr.new]p9:
10298     //   The expression is erroneous if:
10299     //   -- [...] its value before converting to size_t [or] applying the
10300     //      second standard conversion sequence is less than zero
10301     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10302       if (IsNothrow)
10303         return ZeroInitialization(E);
10304 
10305       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10306           << ArrayBound << (*ArraySize)->getSourceRange();
10307       return false;
10308     }
10309 
10310     //   -- its value is such that the size of the allocated object would
10311     //      exceed the implementation-defined limit
10312     if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10313                              ConstantArrayType::getNumAddressingBits(
10314                                  Info.Ctx, AllocType, ArrayBound),
10315                              ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10316       if (IsNothrow)
10317         return ZeroInitialization(E);
10318       return false;
10319     }
10320 
10321     //   -- the new-initializer is a braced-init-list and the number of
10322     //      array elements for which initializers are provided [...]
10323     //      exceeds the number of elements to initialize
10324     if (!Init) {
10325       // No initialization is performed.
10326     } else if (isa<CXXScalarValueInitExpr>(Init) ||
10327                isa<ImplicitValueInitExpr>(Init)) {
10328       ValueInit = true;
10329     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10330       ResizedArrayCCE = CCE;
10331     } else {
10332       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10333       assert(CAT && "unexpected type for array initializer");
10334 
10335       unsigned Bits =
10336           std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10337       llvm::APInt InitBound = CAT->getSize().zext(Bits);
10338       llvm::APInt AllocBound = ArrayBound.zext(Bits);
10339       if (InitBound.ugt(AllocBound)) {
10340         if (IsNothrow)
10341           return ZeroInitialization(E);
10342 
10343         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10344             << toString(AllocBound, 10, /*Signed=*/false)
10345             << toString(InitBound, 10, /*Signed=*/false)
10346             << (*ArraySize)->getSourceRange();
10347         return false;
10348       }
10349 
10350       // If the sizes differ, we must have an initializer list, and we need
10351       // special handling for this case when we initialize.
10352       if (InitBound != AllocBound)
10353         ResizedArrayILE = cast<InitListExpr>(Init);
10354     }
10355 
10356     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10357                                               ArraySizeModifier::Normal, 0);
10358   } else {
10359     assert(!AllocType->isArrayType() &&
10360            "array allocation with non-array new");
10361   }
10362 
10363   APValue *Val;
10364   if (IsPlacement) {
10365     AccessKinds AK = AK_Construct;
10366     struct FindObjectHandler {
10367       EvalInfo &Info;
10368       const Expr *E;
10369       QualType AllocType;
10370       const AccessKinds AccessKind;
10371       APValue *Value;
10372 
10373       typedef bool result_type;
10374       bool failed() { return false; }
10375       bool found(APValue &Subobj, QualType SubobjType) {
10376         // FIXME: Reject the cases where [basic.life]p8 would not permit the
10377         // old name of the object to be used to name the new object.
10378         unsigned SubobjectSize = 1;
10379         unsigned AllocSize = 1;
10380         if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10381           AllocSize = CAT->getZExtSize();
10382         if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10383           SubobjectSize = CAT->getZExtSize();
10384         if (SubobjectSize < AllocSize ||
10385             !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10386                                      Info.Ctx.getBaseElementType(AllocType))) {
10387           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10388               << SubobjType << AllocType;
10389           return false;
10390         }
10391         Value = &Subobj;
10392         return true;
10393       }
10394       bool found(APSInt &Value, QualType SubobjType) {
10395         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10396         return false;
10397       }
10398       bool found(APFloat &Value, QualType SubobjType) {
10399         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10400         return false;
10401       }
10402     } Handler = {Info, E, AllocType, AK, nullptr};
10403 
10404     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10405     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10406       return false;
10407 
10408     Val = Handler.Value;
10409 
10410     // [basic.life]p1:
10411     //   The lifetime of an object o of type T ends when [...] the storage
10412     //   which the object occupies is [...] reused by an object that is not
10413     //   nested within o (6.6.2).
10414     *Val = APValue();
10415   } else {
10416     // Perform the allocation and obtain a pointer to the resulting object.
10417     Val = Info.createHeapAlloc(E, AllocType, Result);
10418     if (!Val)
10419       return false;
10420   }
10421 
10422   if (ValueInit) {
10423     ImplicitValueInitExpr VIE(AllocType);
10424     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10425       return false;
10426   } else if (ResizedArrayILE) {
10427     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10428                                   AllocType))
10429       return false;
10430   } else if (ResizedArrayCCE) {
10431     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10432                                        AllocType))
10433       return false;
10434   } else if (Init) {
10435     if (!EvaluateInPlace(*Val, Info, Result, Init))
10436       return false;
10437   } else if (!handleDefaultInitValue(AllocType, *Val)) {
10438     return false;
10439   }
10440 
10441   // Array new returns a pointer to the first element, not a pointer to the
10442   // array.
10443   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10444     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10445 
10446   return true;
10447 }
10448 //===----------------------------------------------------------------------===//
10449 // Member Pointer Evaluation
10450 //===----------------------------------------------------------------------===//
10451 
10452 namespace {
10453 class MemberPointerExprEvaluator
10454   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10455   MemberPtr &Result;
10456 
10457   bool Success(const ValueDecl *D) {
10458     Result = MemberPtr(D);
10459     return true;
10460   }
10461 public:
10462 
10463   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10464     : ExprEvaluatorBaseTy(Info), Result(Result) {}
10465 
10466   bool Success(const APValue &V, const Expr *E) {
10467     Result.setFrom(V);
10468     return true;
10469   }
10470   bool ZeroInitialization(const Expr *E) {
10471     return Success((const ValueDecl*)nullptr);
10472   }
10473 
10474   bool VisitCastExpr(const CastExpr *E);
10475   bool VisitUnaryAddrOf(const UnaryOperator *E);
10476 };
10477 } // end anonymous namespace
10478 
10479 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10480                                   EvalInfo &Info) {
10481   assert(!E->isValueDependent());
10482   assert(E->isPRValue() && E->getType()->isMemberPointerType());
10483   return MemberPointerExprEvaluator(Info, Result).Visit(E);
10484 }
10485 
10486 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10487   switch (E->getCastKind()) {
10488   default:
10489     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10490 
10491   case CK_NullToMemberPointer:
10492     VisitIgnoredValue(E->getSubExpr());
10493     return ZeroInitialization(E);
10494 
10495   case CK_BaseToDerivedMemberPointer: {
10496     if (!Visit(E->getSubExpr()))
10497       return false;
10498     if (E->path_empty())
10499       return true;
10500     // Base-to-derived member pointer casts store the path in derived-to-base
10501     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10502     // the wrong end of the derived->base arc, so stagger the path by one class.
10503     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10504     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10505          PathI != PathE; ++PathI) {
10506       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10507       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10508       if (!Result.castToDerived(Derived))
10509         return Error(E);
10510     }
10511     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10512     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10513       return Error(E);
10514     return true;
10515   }
10516 
10517   case CK_DerivedToBaseMemberPointer:
10518     if (!Visit(E->getSubExpr()))
10519       return false;
10520     for (CastExpr::path_const_iterator PathI = E->path_begin(),
10521          PathE = E->path_end(); PathI != PathE; ++PathI) {
10522       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10523       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10524       if (!Result.castToBase(Base))
10525         return Error(E);
10526     }
10527     return true;
10528   }
10529 }
10530 
10531 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10532   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10533   // member can be formed.
10534   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10535 }
10536 
10537 //===----------------------------------------------------------------------===//
10538 // Record Evaluation
10539 //===----------------------------------------------------------------------===//
10540 
10541 namespace {
10542   class RecordExprEvaluator
10543   : public ExprEvaluatorBase<RecordExprEvaluator> {
10544     const LValue &This;
10545     APValue &Result;
10546   public:
10547 
10548     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10549       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10550 
10551     bool Success(const APValue &V, const Expr *E) {
10552       Result = V;
10553       return true;
10554     }
10555     bool ZeroInitialization(const Expr *E) {
10556       return ZeroInitialization(E, E->getType());
10557     }
10558     bool ZeroInitialization(const Expr *E, QualType T);
10559 
10560     bool VisitCallExpr(const CallExpr *E) {
10561       return handleCallExpr(E, Result, &This);
10562     }
10563     bool VisitCastExpr(const CastExpr *E);
10564     bool VisitInitListExpr(const InitListExpr *E);
10565     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10566       return VisitCXXConstructExpr(E, E->getType());
10567     }
10568     bool VisitLambdaExpr(const LambdaExpr *E);
10569     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10570     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10571     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10572     bool VisitBinCmp(const BinaryOperator *E);
10573     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10574     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10575                                          ArrayRef<Expr *> Args);
10576   };
10577 }
10578 
10579 /// Perform zero-initialization on an object of non-union class type.
10580 /// C++11 [dcl.init]p5:
10581 ///  To zero-initialize an object or reference of type T means:
10582 ///    [...]
10583 ///    -- if T is a (possibly cv-qualified) non-union class type,
10584 ///       each non-static data member and each base-class subobject is
10585 ///       zero-initialized
10586 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10587                                           const RecordDecl *RD,
10588                                           const LValue &This, APValue &Result) {
10589   assert(!RD->isUnion() && "Expected non-union class type");
10590   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10591   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10592                    std::distance(RD->field_begin(), RD->field_end()));
10593 
10594   if (RD->isInvalidDecl()) return false;
10595   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10596 
10597   if (CD) {
10598     unsigned Index = 0;
10599     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
10600            End = CD->bases_end(); I != End; ++I, ++Index) {
10601       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10602       LValue Subobject = This;
10603       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10604         return false;
10605       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10606                                          Result.getStructBase(Index)))
10607         return false;
10608     }
10609   }
10610 
10611   for (const auto *I : RD->fields()) {
10612     // -- if T is a reference type, no initialization is performed.
10613     if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10614       continue;
10615 
10616     LValue Subobject = This;
10617     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10618       return false;
10619 
10620     ImplicitValueInitExpr VIE(I->getType());
10621     if (!EvaluateInPlace(
10622           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10623       return false;
10624   }
10625 
10626   return true;
10627 }
10628 
10629 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10630   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10631   if (RD->isInvalidDecl()) return false;
10632   if (RD->isUnion()) {
10633     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10634     // object's first non-static named data member is zero-initialized
10635     RecordDecl::field_iterator I = RD->field_begin();
10636     while (I != RD->field_end() && (*I)->isUnnamedBitField())
10637       ++I;
10638     if (I == RD->field_end()) {
10639       Result = APValue((const FieldDecl*)nullptr);
10640       return true;
10641     }
10642 
10643     LValue Subobject = This;
10644     if (!HandleLValueMember(Info, E, Subobject, *I))
10645       return false;
10646     Result = APValue(*I);
10647     ImplicitValueInitExpr VIE(I->getType());
10648     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10649   }
10650 
10651   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10652     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10653     return false;
10654   }
10655 
10656   return HandleClassZeroInitialization(Info, E, RD, This, Result);
10657 }
10658 
10659 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10660   switch (E->getCastKind()) {
10661   default:
10662     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10663 
10664   case CK_ConstructorConversion:
10665     return Visit(E->getSubExpr());
10666 
10667   case CK_DerivedToBase:
10668   case CK_UncheckedDerivedToBase: {
10669     APValue DerivedObject;
10670     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10671       return false;
10672     if (!DerivedObject.isStruct())
10673       return Error(E->getSubExpr());
10674 
10675     // Derived-to-base rvalue conversion: just slice off the derived part.
10676     APValue *Value = &DerivedObject;
10677     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10678     for (CastExpr::path_const_iterator PathI = E->path_begin(),
10679          PathE = E->path_end(); PathI != PathE; ++PathI) {
10680       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10681       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10682       Value = &Value->getStructBase(getBaseIndex(RD, Base));
10683       RD = Base;
10684     }
10685     Result = *Value;
10686     return true;
10687   }
10688   }
10689 }
10690 
10691 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10692   if (E->isTransparent())
10693     return Visit(E->getInit(0));
10694   return VisitCXXParenListOrInitListExpr(E, E->inits());
10695 }
10696 
10697 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10698     const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10699   const RecordDecl *RD =
10700       ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10701   if (RD->isInvalidDecl()) return false;
10702   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10703   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10704 
10705   EvalInfo::EvaluatingConstructorRAII EvalObj(
10706       Info,
10707       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10708       CXXRD && CXXRD->getNumBases());
10709 
10710   if (RD->isUnion()) {
10711     const FieldDecl *Field;
10712     if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10713       Field = ILE->getInitializedFieldInUnion();
10714     } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10715       Field = PLIE->getInitializedFieldInUnion();
10716     } else {
10717       llvm_unreachable(
10718           "Expression is neither an init list nor a C++ paren list");
10719     }
10720 
10721     Result = APValue(Field);
10722     if (!Field)
10723       return true;
10724 
10725     // If the initializer list for a union does not contain any elements, the
10726     // first element of the union is value-initialized.
10727     // FIXME: The element should be initialized from an initializer list.
10728     //        Is this difference ever observable for initializer lists which
10729     //        we don't build?
10730     ImplicitValueInitExpr VIE(Field->getType());
10731     const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10732 
10733     LValue Subobject = This;
10734     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10735       return false;
10736 
10737     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10738     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10739                                   isa<CXXDefaultInitExpr>(InitExpr));
10740 
10741     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10742       if (Field->isBitField())
10743         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10744                                      Field);
10745       return true;
10746     }
10747 
10748     return false;
10749   }
10750 
10751   if (!Result.hasValue())
10752     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10753                      std::distance(RD->field_begin(), RD->field_end()));
10754   unsigned ElementNo = 0;
10755   bool Success = true;
10756 
10757   // Initialize base classes.
10758   if (CXXRD && CXXRD->getNumBases()) {
10759     for (const auto &Base : CXXRD->bases()) {
10760       assert(ElementNo < Args.size() && "missing init for base class");
10761       const Expr *Init = Args[ElementNo];
10762 
10763       LValue Subobject = This;
10764       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10765         return false;
10766 
10767       APValue &FieldVal = Result.getStructBase(ElementNo);
10768       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10769         if (!Info.noteFailure())
10770           return false;
10771         Success = false;
10772       }
10773       ++ElementNo;
10774     }
10775 
10776     EvalObj.finishedConstructingBases();
10777   }
10778 
10779   // Initialize members.
10780   for (const auto *Field : RD->fields()) {
10781     // Anonymous bit-fields are not considered members of the class for
10782     // purposes of aggregate initialization.
10783     if (Field->isUnnamedBitField())
10784       continue;
10785 
10786     LValue Subobject = This;
10787 
10788     bool HaveInit = ElementNo < Args.size();
10789 
10790     // FIXME: Diagnostics here should point to the end of the initializer
10791     // list, not the start.
10792     if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10793                             Subobject, Field, &Layout))
10794       return false;
10795 
10796     // Perform an implicit value-initialization for members beyond the end of
10797     // the initializer list.
10798     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10799     const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10800 
10801     if (Field->getType()->isIncompleteArrayType()) {
10802       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10803         if (!CAT->isZeroSize()) {
10804           // Bail out for now. This might sort of "work", but the rest of the
10805           // code isn't really prepared to handle it.
10806           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10807           return false;
10808         }
10809       }
10810     }
10811 
10812     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10813     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10814                                   isa<CXXDefaultInitExpr>(Init));
10815 
10816     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10817     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10818         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10819                                                        FieldVal, Field))) {
10820       if (!Info.noteFailure())
10821         return false;
10822       Success = false;
10823     }
10824   }
10825 
10826   EvalObj.finishedConstructingFields();
10827 
10828   return Success;
10829 }
10830 
10831 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10832                                                 QualType T) {
10833   // Note that E's type is not necessarily the type of our class here; we might
10834   // be initializing an array element instead.
10835   const CXXConstructorDecl *FD = E->getConstructor();
10836   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10837 
10838   bool ZeroInit = E->requiresZeroInitialization();
10839   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10840     // If we've already performed zero-initialization, we're already done.
10841     if (Result.hasValue())
10842       return true;
10843 
10844     if (ZeroInit)
10845       return ZeroInitialization(E, T);
10846 
10847     return handleDefaultInitValue(T, Result);
10848   }
10849 
10850   const FunctionDecl *Definition = nullptr;
10851   auto Body = FD->getBody(Definition);
10852 
10853   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10854     return false;
10855 
10856   // Avoid materializing a temporary for an elidable copy/move constructor.
10857   if (E->isElidable() && !ZeroInit) {
10858     // FIXME: This only handles the simplest case, where the source object
10859     //        is passed directly as the first argument to the constructor.
10860     //        This should also handle stepping though implicit casts and
10861     //        and conversion sequences which involve two steps, with a
10862     //        conversion operator followed by a converting constructor.
10863     const Expr *SrcObj = E->getArg(0);
10864     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10865     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10866     if (const MaterializeTemporaryExpr *ME =
10867             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10868       return Visit(ME->getSubExpr());
10869   }
10870 
10871   if (ZeroInit && !ZeroInitialization(E, T))
10872     return false;
10873 
10874   auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10875   return HandleConstructorCall(E, This, Args,
10876                                cast<CXXConstructorDecl>(Definition), Info,
10877                                Result);
10878 }
10879 
10880 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10881     const CXXInheritedCtorInitExpr *E) {
10882   if (!Info.CurrentCall) {
10883     assert(Info.checkingPotentialConstantExpression());
10884     return false;
10885   }
10886 
10887   const CXXConstructorDecl *FD = E->getConstructor();
10888   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10889     return false;
10890 
10891   const FunctionDecl *Definition = nullptr;
10892   auto Body = FD->getBody(Definition);
10893 
10894   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10895     return false;
10896 
10897   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10898                                cast<CXXConstructorDecl>(Definition), Info,
10899                                Result);
10900 }
10901 
10902 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10903     const CXXStdInitializerListExpr *E) {
10904   const ConstantArrayType *ArrayType =
10905       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10906 
10907   LValue Array;
10908   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10909     return false;
10910 
10911   assert(ArrayType && "unexpected type for array initializer");
10912 
10913   // Get a pointer to the first element of the array.
10914   Array.addArray(Info, E, ArrayType);
10915 
10916   // FIXME: What if the initializer_list type has base classes, etc?
10917   Result = APValue(APValue::UninitStruct(), 0, 2);
10918   Array.moveInto(Result.getStructField(0));
10919 
10920   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10921   RecordDecl::field_iterator Field = Record->field_begin();
10922   assert(Field != Record->field_end() &&
10923          Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10924                               ArrayType->getElementType()) &&
10925          "Expected std::initializer_list first field to be const E *");
10926   ++Field;
10927   assert(Field != Record->field_end() &&
10928          "Expected std::initializer_list to have two fields");
10929 
10930   if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
10931     // Length.
10932     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10933   } else {
10934     // End pointer.
10935     assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10936                                 ArrayType->getElementType()) &&
10937            "Expected std::initializer_list second field to be const E *");
10938     if (!HandleLValueArrayAdjustment(Info, E, Array,
10939                                      ArrayType->getElementType(),
10940                                      ArrayType->getZExtSize()))
10941       return false;
10942     Array.moveInto(Result.getStructField(1));
10943   }
10944 
10945   assert(++Field == Record->field_end() &&
10946          "Expected std::initializer_list to only have two fields");
10947 
10948   return true;
10949 }
10950 
10951 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10952   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10953   if (ClosureClass->isInvalidDecl())
10954     return false;
10955 
10956   const size_t NumFields =
10957       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10958 
10959   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10960                                             E->capture_init_end()) &&
10961          "The number of lambda capture initializers should equal the number of "
10962          "fields within the closure type");
10963 
10964   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10965   // Iterate through all the lambda's closure object's fields and initialize
10966   // them.
10967   auto *CaptureInitIt = E->capture_init_begin();
10968   bool Success = true;
10969   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10970   for (const auto *Field : ClosureClass->fields()) {
10971     assert(CaptureInitIt != E->capture_init_end());
10972     // Get the initializer for this field
10973     Expr *const CurFieldInit = *CaptureInitIt++;
10974 
10975     // If there is no initializer, either this is a VLA or an error has
10976     // occurred.
10977     if (!CurFieldInit)
10978       return Error(E);
10979 
10980     LValue Subobject = This;
10981 
10982     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10983       return false;
10984 
10985     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10986     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10987       if (!Info.keepEvaluatingAfterFailure())
10988         return false;
10989       Success = false;
10990     }
10991   }
10992   return Success;
10993 }
10994 
10995 static bool EvaluateRecord(const Expr *E, const LValue &This,
10996                            APValue &Result, EvalInfo &Info) {
10997   assert(!E->isValueDependent());
10998   assert(E->isPRValue() && E->getType()->isRecordType() &&
10999          "can't evaluate expression as a record rvalue");
11000   return RecordExprEvaluator(Info, This, Result).Visit(E);
11001 }
11002 
11003 //===----------------------------------------------------------------------===//
11004 // Temporary Evaluation
11005 //
11006 // Temporaries are represented in the AST as rvalues, but generally behave like
11007 // lvalues. The full-object of which the temporary is a subobject is implicitly
11008 // materialized so that a reference can bind to it.
11009 //===----------------------------------------------------------------------===//
11010 namespace {
11011 class TemporaryExprEvaluator
11012   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11013 public:
11014   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11015     LValueExprEvaluatorBaseTy(Info, Result, false) {}
11016 
11017   /// Visit an expression which constructs the value of this temporary.
11018   bool VisitConstructExpr(const Expr *E) {
11019     APValue &Value = Info.CurrentCall->createTemporary(
11020         E, E->getType(), ScopeKind::FullExpression, Result);
11021     return EvaluateInPlace(Value, Info, Result, E);
11022   }
11023 
11024   bool VisitCastExpr(const CastExpr *E) {
11025     switch (E->getCastKind()) {
11026     default:
11027       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11028 
11029     case CK_ConstructorConversion:
11030       return VisitConstructExpr(E->getSubExpr());
11031     }
11032   }
11033   bool VisitInitListExpr(const InitListExpr *E) {
11034     return VisitConstructExpr(E);
11035   }
11036   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11037     return VisitConstructExpr(E);
11038   }
11039   bool VisitCallExpr(const CallExpr *E) {
11040     return VisitConstructExpr(E);
11041   }
11042   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11043     return VisitConstructExpr(E);
11044   }
11045   bool VisitLambdaExpr(const LambdaExpr *E) {
11046     return VisitConstructExpr(E);
11047   }
11048 };
11049 } // end anonymous namespace
11050 
11051 /// Evaluate an expression of record type as a temporary.
11052 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11053   assert(!E->isValueDependent());
11054   assert(E->isPRValue() && E->getType()->isRecordType());
11055   return TemporaryExprEvaluator(Info, Result).Visit(E);
11056 }
11057 
11058 //===----------------------------------------------------------------------===//
11059 // Vector Evaluation
11060 //===----------------------------------------------------------------------===//
11061 
11062 namespace {
11063   class VectorExprEvaluator
11064   : public ExprEvaluatorBase<VectorExprEvaluator> {
11065     APValue &Result;
11066   public:
11067 
11068     VectorExprEvaluator(EvalInfo &info, APValue &Result)
11069       : ExprEvaluatorBaseTy(info), Result(Result) {}
11070 
11071     bool Success(ArrayRef<APValue> V, const Expr *E) {
11072       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11073       // FIXME: remove this APValue copy.
11074       Result = APValue(V.data(), V.size());
11075       return true;
11076     }
11077     bool Success(const APValue &V, const Expr *E) {
11078       assert(V.isVector());
11079       Result = V;
11080       return true;
11081     }
11082     bool ZeroInitialization(const Expr *E);
11083 
11084     bool VisitUnaryReal(const UnaryOperator *E)
11085       { return Visit(E->getSubExpr()); }
11086     bool VisitCastExpr(const CastExpr* E);
11087     bool VisitInitListExpr(const InitListExpr *E);
11088     bool VisitUnaryImag(const UnaryOperator *E);
11089     bool VisitBinaryOperator(const BinaryOperator *E);
11090     bool VisitUnaryOperator(const UnaryOperator *E);
11091     bool VisitCallExpr(const CallExpr *E);
11092     bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11093     bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11094 
11095     // FIXME: Missing: conditional operator (for GNU
11096     //                 conditional select), ExtVectorElementExpr
11097   };
11098 } // end anonymous namespace
11099 
11100 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11101   assert(E->isPRValue() && E->getType()->isVectorType() &&
11102          "not a vector prvalue");
11103   return VectorExprEvaluator(Info, Result).Visit(E);
11104 }
11105 
11106 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11107   const VectorType *VTy = E->getType()->castAs<VectorType>();
11108   unsigned NElts = VTy->getNumElements();
11109 
11110   const Expr *SE = E->getSubExpr();
11111   QualType SETy = SE->getType();
11112 
11113   switch (E->getCastKind()) {
11114   case CK_VectorSplat: {
11115     APValue Val = APValue();
11116     if (SETy->isIntegerType()) {
11117       APSInt IntResult;
11118       if (!EvaluateInteger(SE, IntResult, Info))
11119         return false;
11120       Val = APValue(std::move(IntResult));
11121     } else if (SETy->isRealFloatingType()) {
11122       APFloat FloatResult(0.0);
11123       if (!EvaluateFloat(SE, FloatResult, Info))
11124         return false;
11125       Val = APValue(std::move(FloatResult));
11126     } else {
11127       return Error(E);
11128     }
11129 
11130     // Splat and create vector APValue.
11131     SmallVector<APValue, 4> Elts(NElts, Val);
11132     return Success(Elts, E);
11133   }
11134   case CK_BitCast: {
11135     APValue SVal;
11136     if (!Evaluate(SVal, Info, SE))
11137       return false;
11138 
11139     if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11140       // Give up if the input isn't an int, float, or vector.  For example, we
11141       // reject "(v4i16)(intptr_t)&a".
11142       Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11143           << 2 << Info.Ctx.getLangOpts().CPlusPlus;
11144       return false;
11145     }
11146 
11147     if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11148       return false;
11149 
11150     return true;
11151   }
11152   case CK_HLSLVectorTruncation: {
11153     APValue Val;
11154     SmallVector<APValue, 4> Elements;
11155     if (!EvaluateVector(SE, Val, Info))
11156       return Error(E);
11157     for (unsigned I = 0; I < NElts; I++)
11158       Elements.push_back(Val.getVectorElt(I));
11159     return Success(Elements, E);
11160   }
11161   default:
11162     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11163   }
11164 }
11165 
11166 bool
11167 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11168   const VectorType *VT = E->getType()->castAs<VectorType>();
11169   unsigned NumInits = E->getNumInits();
11170   unsigned NumElements = VT->getNumElements();
11171 
11172   QualType EltTy = VT->getElementType();
11173   SmallVector<APValue, 4> Elements;
11174 
11175   // The number of initializers can be less than the number of
11176   // vector elements. For OpenCL, this can be due to nested vector
11177   // initialization. For GCC compatibility, missing trailing elements
11178   // should be initialized with zeroes.
11179   unsigned CountInits = 0, CountElts = 0;
11180   while (CountElts < NumElements) {
11181     // Handle nested vector initialization.
11182     if (CountInits < NumInits
11183         && E->getInit(CountInits)->getType()->isVectorType()) {
11184       APValue v;
11185       if (!EvaluateVector(E->getInit(CountInits), v, Info))
11186         return Error(E);
11187       unsigned vlen = v.getVectorLength();
11188       for (unsigned j = 0; j < vlen; j++)
11189         Elements.push_back(v.getVectorElt(j));
11190       CountElts += vlen;
11191     } else if (EltTy->isIntegerType()) {
11192       llvm::APSInt sInt(32);
11193       if (CountInits < NumInits) {
11194         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11195           return false;
11196       } else // trailing integer zero.
11197         sInt = Info.Ctx.MakeIntValue(0, EltTy);
11198       Elements.push_back(APValue(sInt));
11199       CountElts++;
11200     } else {
11201       llvm::APFloat f(0.0);
11202       if (CountInits < NumInits) {
11203         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11204           return false;
11205       } else // trailing float zero.
11206         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11207       Elements.push_back(APValue(f));
11208       CountElts++;
11209     }
11210     CountInits++;
11211   }
11212   return Success(Elements, E);
11213 }
11214 
11215 bool
11216 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11217   const auto *VT = E->getType()->castAs<VectorType>();
11218   QualType EltTy = VT->getElementType();
11219   APValue ZeroElement;
11220   if (EltTy->isIntegerType())
11221     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11222   else
11223     ZeroElement =
11224         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11225 
11226   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11227   return Success(Elements, E);
11228 }
11229 
11230 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11231   VisitIgnoredValue(E->getSubExpr());
11232   return ZeroInitialization(E);
11233 }
11234 
11235 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11236   BinaryOperatorKind Op = E->getOpcode();
11237   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11238          "Operation not supported on vector types");
11239 
11240   if (Op == BO_Comma)
11241     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11242 
11243   Expr *LHS = E->getLHS();
11244   Expr *RHS = E->getRHS();
11245 
11246   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11247          "Must both be vector types");
11248   // Checking JUST the types are the same would be fine, except shifts don't
11249   // need to have their types be the same (since you always shift by an int).
11250   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11251              E->getType()->castAs<VectorType>()->getNumElements() &&
11252          RHS->getType()->castAs<VectorType>()->getNumElements() ==
11253              E->getType()->castAs<VectorType>()->getNumElements() &&
11254          "All operands must be the same size.");
11255 
11256   APValue LHSValue;
11257   APValue RHSValue;
11258   bool LHSOK = Evaluate(LHSValue, Info, LHS);
11259   if (!LHSOK && !Info.noteFailure())
11260     return false;
11261   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11262     return false;
11263 
11264   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11265     return false;
11266 
11267   return Success(LHSValue, E);
11268 }
11269 
11270 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11271                                                         QualType ResultTy,
11272                                                         UnaryOperatorKind Op,
11273                                                         APValue Elt) {
11274   switch (Op) {
11275   case UO_Plus:
11276     // Nothing to do here.
11277     return Elt;
11278   case UO_Minus:
11279     if (Elt.getKind() == APValue::Int) {
11280       Elt.getInt().negate();
11281     } else {
11282       assert(Elt.getKind() == APValue::Float &&
11283              "Vector can only be int or float type");
11284       Elt.getFloat().changeSign();
11285     }
11286     return Elt;
11287   case UO_Not:
11288     // This is only valid for integral types anyway, so we don't have to handle
11289     // float here.
11290     assert(Elt.getKind() == APValue::Int &&
11291            "Vector operator ~ can only be int");
11292     Elt.getInt().flipAllBits();
11293     return Elt;
11294   case UO_LNot: {
11295     if (Elt.getKind() == APValue::Int) {
11296       Elt.getInt() = !Elt.getInt();
11297       // operator ! on vectors returns -1 for 'truth', so negate it.
11298       Elt.getInt().negate();
11299       return Elt;
11300     }
11301     assert(Elt.getKind() == APValue::Float &&
11302            "Vector can only be int or float type");
11303     // Float types result in an int of the same size, but -1 for true, or 0 for
11304     // false.
11305     APSInt EltResult{Ctx.getIntWidth(ResultTy),
11306                      ResultTy->isUnsignedIntegerType()};
11307     if (Elt.getFloat().isZero())
11308       EltResult.setAllBits();
11309     else
11310       EltResult.clearAllBits();
11311 
11312     return APValue{EltResult};
11313   }
11314   default:
11315     // FIXME: Implement the rest of the unary operators.
11316     return std::nullopt;
11317   }
11318 }
11319 
11320 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11321   Expr *SubExpr = E->getSubExpr();
11322   const auto *VD = SubExpr->getType()->castAs<VectorType>();
11323   // This result element type differs in the case of negating a floating point
11324   // vector, since the result type is the a vector of the equivilant sized
11325   // integer.
11326   const QualType ResultEltTy = VD->getElementType();
11327   UnaryOperatorKind Op = E->getOpcode();
11328 
11329   APValue SubExprValue;
11330   if (!Evaluate(SubExprValue, Info, SubExpr))
11331     return false;
11332 
11333   // FIXME: This vector evaluator someday needs to be changed to be LValue
11334   // aware/keep LValue information around, rather than dealing with just vector
11335   // types directly. Until then, we cannot handle cases where the operand to
11336   // these unary operators is an LValue. The only case I've been able to see
11337   // cause this is operator++ assigning to a member expression (only valid in
11338   // altivec compilations) in C mode, so this shouldn't limit us too much.
11339   if (SubExprValue.isLValue())
11340     return false;
11341 
11342   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11343          "Vector length doesn't match type?");
11344 
11345   SmallVector<APValue, 4> ResultElements;
11346   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11347     std::optional<APValue> Elt = handleVectorUnaryOperator(
11348         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11349     if (!Elt)
11350       return false;
11351     ResultElements.push_back(*Elt);
11352   }
11353   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11354 }
11355 
11356 static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11357                                     const Expr *E, QualType SourceTy,
11358                                     QualType DestTy, APValue const &Original,
11359                                     APValue &Result) {
11360   if (SourceTy->isIntegerType()) {
11361     if (DestTy->isRealFloatingType()) {
11362       Result = APValue(APFloat(0.0));
11363       return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11364                                   DestTy, Result.getFloat());
11365     }
11366     if (DestTy->isIntegerType()) {
11367       Result = APValue(
11368           HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11369       return true;
11370     }
11371   } else if (SourceTy->isRealFloatingType()) {
11372     if (DestTy->isRealFloatingType()) {
11373       Result = Original;
11374       return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11375                                     Result.getFloat());
11376     }
11377     if (DestTy->isIntegerType()) {
11378       Result = APValue(APSInt());
11379       return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11380                                   DestTy, Result.getInt());
11381     }
11382   }
11383 
11384   Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11385       << SourceTy << DestTy;
11386   return false;
11387 }
11388 
11389 bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11390   if (!IsConstantEvaluatedBuiltinCall(E))
11391     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11392 
11393   switch (E->getBuiltinCallee()) {
11394   default:
11395     return false;
11396   case Builtin::BI__builtin_elementwise_popcount:
11397   case Builtin::BI__builtin_elementwise_bitreverse: {
11398     APValue Source;
11399     if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11400       return false;
11401 
11402     QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11403     unsigned SourceLen = Source.getVectorLength();
11404     SmallVector<APValue, 4> ResultElements;
11405     ResultElements.reserve(SourceLen);
11406 
11407     for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11408       APSInt Elt = Source.getVectorElt(EltNum).getInt();
11409       switch (E->getBuiltinCallee()) {
11410       case Builtin::BI__builtin_elementwise_popcount:
11411         ResultElements.push_back(APValue(
11412             APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11413                    DestEltTy->isUnsignedIntegerOrEnumerationType())));
11414         break;
11415       case Builtin::BI__builtin_elementwise_bitreverse:
11416         ResultElements.push_back(
11417             APValue(APSInt(Elt.reverseBits(),
11418                            DestEltTy->isUnsignedIntegerOrEnumerationType())));
11419         break;
11420       }
11421     }
11422 
11423     return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11424   }
11425   case Builtin::BI__builtin_elementwise_add_sat:
11426   case Builtin::BI__builtin_elementwise_sub_sat: {
11427     APValue SourceLHS, SourceRHS;
11428     if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11429         !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11430       return false;
11431 
11432     QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11433     unsigned SourceLen = SourceLHS.getVectorLength();
11434     SmallVector<APValue, 4> ResultElements;
11435     ResultElements.reserve(SourceLen);
11436 
11437     for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11438       APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11439       APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11440       switch (E->getBuiltinCallee()) {
11441       case Builtin::BI__builtin_elementwise_add_sat:
11442         ResultElements.push_back(APValue(
11443             APSInt(LHS.isSigned() ? LHS.sadd_sat(RHS) : RHS.uadd_sat(RHS),
11444                    DestEltTy->isUnsignedIntegerOrEnumerationType())));
11445         break;
11446       case Builtin::BI__builtin_elementwise_sub_sat:
11447         ResultElements.push_back(APValue(
11448             APSInt(LHS.isSigned() ? LHS.ssub_sat(RHS) : RHS.usub_sat(RHS),
11449                    DestEltTy->isUnsignedIntegerOrEnumerationType())));
11450         break;
11451       }
11452     }
11453 
11454     return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11455   }
11456   }
11457 }
11458 
11459 bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11460   APValue Source;
11461   QualType SourceVecType = E->getSrcExpr()->getType();
11462   if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11463     return false;
11464 
11465   QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11466   QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11467 
11468   const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11469 
11470   auto SourceLen = Source.getVectorLength();
11471   SmallVector<APValue, 4> ResultElements;
11472   ResultElements.reserve(SourceLen);
11473   for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11474     APValue Elt;
11475     if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11476                                  Source.getVectorElt(EltNum), Elt))
11477       return false;
11478     ResultElements.push_back(std::move(Elt));
11479   }
11480 
11481   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11482 }
11483 
11484 static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11485                                 QualType ElemType, APValue const &VecVal1,
11486                                 APValue const &VecVal2, unsigned EltNum,
11487                                 APValue &Result) {
11488   unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11489   unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11490 
11491   APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11492   int64_t index = IndexVal.getExtValue();
11493   // The spec says that -1 should be treated as undef for optimizations,
11494   // but in constexpr we'd have to produce an APValue::Indeterminate,
11495   // which is prohibited from being a top-level constant value. Emit a
11496   // diagnostic instead.
11497   if (index == -1) {
11498     Info.FFDiag(
11499         E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11500         << EltNum;
11501     return false;
11502   }
11503 
11504   if (index < 0 ||
11505       index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11506     llvm_unreachable("Out of bounds shuffle index");
11507 
11508   if (index >= TotalElementsInInputVector1)
11509     Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11510   else
11511     Result = VecVal1.getVectorElt(index);
11512   return true;
11513 }
11514 
11515 bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11516   APValue VecVal1;
11517   const Expr *Vec1 = E->getExpr(0);
11518   if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11519     return false;
11520   APValue VecVal2;
11521   const Expr *Vec2 = E->getExpr(1);
11522   if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11523     return false;
11524 
11525   VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11526   QualType DestElTy = DestVecTy->getElementType();
11527 
11528   auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11529 
11530   SmallVector<APValue, 4> ResultElements;
11531   ResultElements.reserve(TotalElementsInOutputVector);
11532   for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11533     APValue Elt;
11534     if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11535       return false;
11536     ResultElements.push_back(std::move(Elt));
11537   }
11538 
11539   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11540 }
11541 
11542 //===----------------------------------------------------------------------===//
11543 // Array Evaluation
11544 //===----------------------------------------------------------------------===//
11545 
11546 namespace {
11547   class ArrayExprEvaluator
11548   : public ExprEvaluatorBase<ArrayExprEvaluator> {
11549     const LValue &This;
11550     APValue &Result;
11551   public:
11552 
11553     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11554       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11555 
11556     bool Success(const APValue &V, const Expr *E) {
11557       assert(V.isArray() && "expected array");
11558       Result = V;
11559       return true;
11560     }
11561 
11562     bool ZeroInitialization(const Expr *E) {
11563       const ConstantArrayType *CAT =
11564           Info.Ctx.getAsConstantArrayType(E->getType());
11565       if (!CAT) {
11566         if (E->getType()->isIncompleteArrayType()) {
11567           // We can be asked to zero-initialize a flexible array member; this
11568           // is represented as an ImplicitValueInitExpr of incomplete array
11569           // type. In this case, the array has zero elements.
11570           Result = APValue(APValue::UninitArray(), 0, 0);
11571           return true;
11572         }
11573         // FIXME: We could handle VLAs here.
11574         return Error(E);
11575       }
11576 
11577       Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11578       if (!Result.hasArrayFiller())
11579         return true;
11580 
11581       // Zero-initialize all elements.
11582       LValue Subobject = This;
11583       Subobject.addArray(Info, E, CAT);
11584       ImplicitValueInitExpr VIE(CAT->getElementType());
11585       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11586     }
11587 
11588     bool VisitCallExpr(const CallExpr *E) {
11589       return handleCallExpr(E, Result, &This);
11590     }
11591     bool VisitInitListExpr(const InitListExpr *E,
11592                            QualType AllocType = QualType());
11593     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11594     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11595     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11596                                const LValue &Subobject,
11597                                APValue *Value, QualType Type);
11598     bool VisitStringLiteral(const StringLiteral *E,
11599                             QualType AllocType = QualType()) {
11600       expandStringLiteral(Info, E, Result, AllocType);
11601       return true;
11602     }
11603     bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11604     bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11605                                          ArrayRef<Expr *> Args,
11606                                          const Expr *ArrayFiller,
11607                                          QualType AllocType = QualType());
11608   };
11609 } // end anonymous namespace
11610 
11611 static bool EvaluateArray(const Expr *E, const LValue &This,
11612                           APValue &Result, EvalInfo &Info) {
11613   assert(!E->isValueDependent());
11614   assert(E->isPRValue() && E->getType()->isArrayType() &&
11615          "not an array prvalue");
11616   return ArrayExprEvaluator(Info, This, Result).Visit(E);
11617 }
11618 
11619 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11620                                      APValue &Result, const InitListExpr *ILE,
11621                                      QualType AllocType) {
11622   assert(!ILE->isValueDependent());
11623   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11624          "not an array prvalue");
11625   return ArrayExprEvaluator(Info, This, Result)
11626       .VisitInitListExpr(ILE, AllocType);
11627 }
11628 
11629 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11630                                           APValue &Result,
11631                                           const CXXConstructExpr *CCE,
11632                                           QualType AllocType) {
11633   assert(!CCE->isValueDependent());
11634   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11635          "not an array prvalue");
11636   return ArrayExprEvaluator(Info, This, Result)
11637       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11638 }
11639 
11640 // Return true iff the given array filler may depend on the element index.
11641 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11642   // For now, just allow non-class value-initialization and initialization
11643   // lists comprised of them.
11644   if (isa<ImplicitValueInitExpr>(FillerExpr))
11645     return false;
11646   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11647     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11648       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11649         return true;
11650     }
11651 
11652     if (ILE->hasArrayFiller() &&
11653         MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11654       return true;
11655 
11656     return false;
11657   }
11658   return true;
11659 }
11660 
11661 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11662                                            QualType AllocType) {
11663   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11664       AllocType.isNull() ? E->getType() : AllocType);
11665   if (!CAT)
11666     return Error(E);
11667 
11668   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11669   // an appropriately-typed string literal enclosed in braces.
11670   if (E->isStringLiteralInit()) {
11671     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11672     // FIXME: Support ObjCEncodeExpr here once we support it in
11673     // ArrayExprEvaluator generally.
11674     if (!SL)
11675       return Error(E);
11676     return VisitStringLiteral(SL, AllocType);
11677   }
11678   // Any other transparent list init will need proper handling of the
11679   // AllocType; we can't just recurse to the inner initializer.
11680   assert(!E->isTransparent() &&
11681          "transparent array list initialization is not string literal init?");
11682 
11683   return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11684                                          AllocType);
11685 }
11686 
11687 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11688     const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11689     QualType AllocType) {
11690   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11691       AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11692 
11693   bool Success = true;
11694 
11695   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11696          "zero-initialized array shouldn't have any initialized elts");
11697   APValue Filler;
11698   if (Result.isArray() && Result.hasArrayFiller())
11699     Filler = Result.getArrayFiller();
11700 
11701   unsigned NumEltsToInit = Args.size();
11702   unsigned NumElts = CAT->getZExtSize();
11703 
11704   // If the initializer might depend on the array index, run it for each
11705   // array element.
11706   if (NumEltsToInit != NumElts &&
11707       MaybeElementDependentArrayFiller(ArrayFiller)) {
11708     NumEltsToInit = NumElts;
11709   } else {
11710     for (auto *Init : Args) {
11711       if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11712         NumEltsToInit += EmbedS->getDataElementCount() - 1;
11713     }
11714     if (NumEltsToInit > NumElts)
11715       NumEltsToInit = NumElts;
11716   }
11717 
11718   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11719                           << NumEltsToInit << ".\n");
11720 
11721   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11722 
11723   // If the array was previously zero-initialized, preserve the
11724   // zero-initialized values.
11725   if (Filler.hasValue()) {
11726     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11727       Result.getArrayInitializedElt(I) = Filler;
11728     if (Result.hasArrayFiller())
11729       Result.getArrayFiller() = Filler;
11730   }
11731 
11732   LValue Subobject = This;
11733   Subobject.addArray(Info, ExprToVisit, CAT);
11734   auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11735     if (Init->isValueDependent())
11736       return EvaluateDependentExpr(Init, Info);
11737 
11738     if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
11739                          Subobject, Init) ||
11740         !HandleLValueArrayAdjustment(Info, Init, Subobject,
11741                                      CAT->getElementType(), 1)) {
11742       if (!Info.noteFailure())
11743         return false;
11744       Success = false;
11745     }
11746     return true;
11747   };
11748   unsigned ArrayIndex = 0;
11749   QualType DestTy = CAT->getElementType();
11750   APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11751   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11752     const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11753     if (ArrayIndex >= NumEltsToInit)
11754       break;
11755     if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11756       StringLiteral *SL = EmbedS->getDataStringLiteral();
11757       for (unsigned I = EmbedS->getStartingElementPos(),
11758                     N = EmbedS->getDataElementCount();
11759            I != EmbedS->getStartingElementPos() + N; ++I) {
11760         Value = SL->getCodeUnit(I);
11761         if (DestTy->isIntegerType()) {
11762           Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
11763         } else {
11764           assert(DestTy->isFloatingType() && "unexpected type");
11765           const FPOptions FPO =
11766               Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11767           APFloat FValue(0.0);
11768           if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11769                                     DestTy, FValue))
11770             return false;
11771           Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
11772         }
11773         ArrayIndex++;
11774       }
11775     } else {
11776       if (!Eval(Init, ArrayIndex))
11777         return false;
11778       ++ArrayIndex;
11779     }
11780   }
11781 
11782   if (!Result.hasArrayFiller())
11783     return Success;
11784 
11785   // If we get here, we have a trivial filler, which we can just evaluate
11786   // once and splat over the rest of the array elements.
11787   assert(ArrayFiller && "no array filler for incomplete init list");
11788   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11789                          ArrayFiller) &&
11790          Success;
11791 }
11792 
11793 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11794   LValue CommonLV;
11795   if (E->getCommonExpr() &&
11796       !Evaluate(Info.CurrentCall->createTemporary(
11797                     E->getCommonExpr(),
11798                     getStorageType(Info.Ctx, E->getCommonExpr()),
11799                     ScopeKind::FullExpression, CommonLV),
11800                 Info, E->getCommonExpr()->getSourceExpr()))
11801     return false;
11802 
11803   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11804 
11805   uint64_t Elements = CAT->getZExtSize();
11806   Result = APValue(APValue::UninitArray(), Elements, Elements);
11807 
11808   LValue Subobject = This;
11809   Subobject.addArray(Info, E, CAT);
11810 
11811   bool Success = true;
11812   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11813     // C++ [class.temporary]/5
11814     // There are four contexts in which temporaries are destroyed at a different
11815     // point than the end of the full-expression. [...] The second context is
11816     // when a copy constructor is called to copy an element of an array while
11817     // the entire array is copied [...]. In either case, if the constructor has
11818     // one or more default arguments, the destruction of every temporary created
11819     // in a default argument is sequenced before the construction of the next
11820     // array element, if any.
11821     FullExpressionRAII Scope(Info);
11822 
11823     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11824                          Info, Subobject, E->getSubExpr()) ||
11825         !HandleLValueArrayAdjustment(Info, E, Subobject,
11826                                      CAT->getElementType(), 1)) {
11827       if (!Info.noteFailure())
11828         return false;
11829       Success = false;
11830     }
11831 
11832     // Make sure we run the destructors too.
11833     Scope.destroy();
11834   }
11835 
11836   return Success;
11837 }
11838 
11839 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11840   return VisitCXXConstructExpr(E, This, &Result, E->getType());
11841 }
11842 
11843 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11844                                                const LValue &Subobject,
11845                                                APValue *Value,
11846                                                QualType Type) {
11847   bool HadZeroInit = Value->hasValue();
11848 
11849   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11850     unsigned FinalSize = CAT->getZExtSize();
11851 
11852     // Preserve the array filler if we had prior zero-initialization.
11853     APValue Filler =
11854       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11855                                              : APValue();
11856 
11857     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11858     if (FinalSize == 0)
11859       return true;
11860 
11861     bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11862         Info, E->getExprLoc(), E->getConstructor(),
11863         E->requiresZeroInitialization());
11864     LValue ArrayElt = Subobject;
11865     ArrayElt.addArray(Info, E, CAT);
11866     // We do the whole initialization in two passes, first for just one element,
11867     // then for the whole array. It's possible we may find out we can't do const
11868     // init in the first pass, in which case we avoid allocating a potentially
11869     // large array. We don't do more passes because expanding array requires
11870     // copying the data, which is wasteful.
11871     for (const unsigned N : {1u, FinalSize}) {
11872       unsigned OldElts = Value->getArrayInitializedElts();
11873       if (OldElts == N)
11874         break;
11875 
11876       // Expand the array to appropriate size.
11877       APValue NewValue(APValue::UninitArray(), N, FinalSize);
11878       for (unsigned I = 0; I < OldElts; ++I)
11879         NewValue.getArrayInitializedElt(I).swap(
11880             Value->getArrayInitializedElt(I));
11881       Value->swap(NewValue);
11882 
11883       if (HadZeroInit)
11884         for (unsigned I = OldElts; I < N; ++I)
11885           Value->getArrayInitializedElt(I) = Filler;
11886 
11887       if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11888         // If we have a trivial constructor, only evaluate it once and copy
11889         // the result into all the array elements.
11890         APValue &FirstResult = Value->getArrayInitializedElt(0);
11891         for (unsigned I = OldElts; I < FinalSize; ++I)
11892           Value->getArrayInitializedElt(I) = FirstResult;
11893       } else {
11894         for (unsigned I = OldElts; I < N; ++I) {
11895           if (!VisitCXXConstructExpr(E, ArrayElt,
11896                                      &Value->getArrayInitializedElt(I),
11897                                      CAT->getElementType()) ||
11898               !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11899                                            CAT->getElementType(), 1))
11900             return false;
11901           // When checking for const initilization any diagnostic is considered
11902           // an error.
11903           if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11904               !Info.keepEvaluatingAfterFailure())
11905             return false;
11906         }
11907       }
11908     }
11909 
11910     return true;
11911   }
11912 
11913   if (!Type->isRecordType())
11914     return Error(E);
11915 
11916   return RecordExprEvaluator(Info, Subobject, *Value)
11917              .VisitCXXConstructExpr(E, Type);
11918 }
11919 
11920 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11921     const CXXParenListInitExpr *E) {
11922   assert(E->getType()->isConstantArrayType() &&
11923          "Expression result is not a constant array type");
11924 
11925   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11926                                          E->getArrayFiller());
11927 }
11928 
11929 //===----------------------------------------------------------------------===//
11930 // Integer Evaluation
11931 //
11932 // As a GNU extension, we support casting pointers to sufficiently-wide integer
11933 // types and back in constant folding. Integer values are thus represented
11934 // either as an integer-valued APValue, or as an lvalue-valued APValue.
11935 //===----------------------------------------------------------------------===//
11936 
11937 namespace {
11938 class IntExprEvaluator
11939         : public ExprEvaluatorBase<IntExprEvaluator> {
11940   APValue &Result;
11941 public:
11942   IntExprEvaluator(EvalInfo &info, APValue &result)
11943       : ExprEvaluatorBaseTy(info), Result(result) {}
11944 
11945   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11946     assert(E->getType()->isIntegralOrEnumerationType() &&
11947            "Invalid evaluation result.");
11948     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11949            "Invalid evaluation result.");
11950     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11951            "Invalid evaluation result.");
11952     Result = APValue(SI);
11953     return true;
11954   }
11955   bool Success(const llvm::APSInt &SI, const Expr *E) {
11956     return Success(SI, E, Result);
11957   }
11958 
11959   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11960     assert(E->getType()->isIntegralOrEnumerationType() &&
11961            "Invalid evaluation result.");
11962     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11963            "Invalid evaluation result.");
11964     Result = APValue(APSInt(I));
11965     Result.getInt().setIsUnsigned(
11966                             E->getType()->isUnsignedIntegerOrEnumerationType());
11967     return true;
11968   }
11969   bool Success(const llvm::APInt &I, const Expr *E) {
11970     return Success(I, E, Result);
11971   }
11972 
11973   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11974     assert(E->getType()->isIntegralOrEnumerationType() &&
11975            "Invalid evaluation result.");
11976     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11977     return true;
11978   }
11979   bool Success(uint64_t Value, const Expr *E) {
11980     return Success(Value, E, Result);
11981   }
11982 
11983   bool Success(CharUnits Size, const Expr *E) {
11984     return Success(Size.getQuantity(), E);
11985   }
11986 
11987   bool Success(const APValue &V, const Expr *E) {
11988     // C++23 [expr.const]p8 If we have a variable that is unknown reference or
11989     // pointer allow further evaluation of the value.
11990     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
11991         V.allowConstexprUnknown()) {
11992       Result = V;
11993       return true;
11994     }
11995     return Success(V.getInt(), E);
11996   }
11997 
11998   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11999 
12000   friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
12001                                                              const CallExpr *);
12002 
12003   //===--------------------------------------------------------------------===//
12004   //                            Visitor Methods
12005   //===--------------------------------------------------------------------===//
12006 
12007   bool VisitIntegerLiteral(const IntegerLiteral *E) {
12008     return Success(E->getValue(), E);
12009   }
12010   bool VisitCharacterLiteral(const CharacterLiteral *E) {
12011     return Success(E->getValue(), E);
12012   }
12013 
12014   bool CheckReferencedDecl(const Expr *E, const Decl *D);
12015   bool VisitDeclRefExpr(const DeclRefExpr *E) {
12016     if (CheckReferencedDecl(E, E->getDecl()))
12017       return true;
12018 
12019     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
12020   }
12021   bool VisitMemberExpr(const MemberExpr *E) {
12022     if (CheckReferencedDecl(E, E->getMemberDecl())) {
12023       VisitIgnoredBaseExpression(E->getBase());
12024       return true;
12025     }
12026 
12027     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
12028   }
12029 
12030   bool VisitCallExpr(const CallExpr *E);
12031   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
12032   bool VisitBinaryOperator(const BinaryOperator *E);
12033   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
12034   bool VisitUnaryOperator(const UnaryOperator *E);
12035 
12036   bool VisitCastExpr(const CastExpr* E);
12037   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
12038 
12039   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
12040     return Success(E->getValue(), E);
12041   }
12042 
12043   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
12044     return Success(E->getValue(), E);
12045   }
12046 
12047   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
12048     if (Info.ArrayInitIndex == uint64_t(-1)) {
12049       // We were asked to evaluate this subexpression independent of the
12050       // enclosing ArrayInitLoopExpr. We can't do that.
12051       Info.FFDiag(E);
12052       return false;
12053     }
12054     return Success(Info.ArrayInitIndex, E);
12055   }
12056 
12057   // Note, GNU defines __null as an integer, not a pointer.
12058   bool VisitGNUNullExpr(const GNUNullExpr *E) {
12059     return ZeroInitialization(E);
12060   }
12061 
12062   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
12063     return Success(E->getValue(), E);
12064   }
12065 
12066   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
12067     return Success(E->getValue(), E);
12068   }
12069 
12070   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
12071     return Success(E->getValue(), E);
12072   }
12073 
12074   bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
12075     // This should not be evaluated during constant expr evaluation, as it
12076     // should always be in an unevaluated context (the args list of a 'gang' or
12077     // 'tile' clause).
12078     return Error(E);
12079   }
12080 
12081   bool VisitUnaryReal(const UnaryOperator *E);
12082   bool VisitUnaryImag(const UnaryOperator *E);
12083 
12084   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
12085   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
12086   bool VisitSourceLocExpr(const SourceLocExpr *E);
12087   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
12088   bool VisitRequiresExpr(const RequiresExpr *E);
12089   // FIXME: Missing: array subscript of vector, member of vector
12090 };
12091 
12092 class FixedPointExprEvaluator
12093     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
12094   APValue &Result;
12095 
12096  public:
12097   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
12098       : ExprEvaluatorBaseTy(info), Result(result) {}
12099 
12100   bool Success(const llvm::APInt &I, const Expr *E) {
12101     return Success(
12102         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12103   }
12104 
12105   bool Success(uint64_t Value, const Expr *E) {
12106     return Success(
12107         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12108   }
12109 
12110   bool Success(const APValue &V, const Expr *E) {
12111     return Success(V.getFixedPoint(), E);
12112   }
12113 
12114   bool Success(const APFixedPoint &V, const Expr *E) {
12115     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12116     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12117            "Invalid evaluation result.");
12118     Result = APValue(V);
12119     return true;
12120   }
12121 
12122   bool ZeroInitialization(const Expr *E) {
12123     return Success(0, E);
12124   }
12125 
12126   //===--------------------------------------------------------------------===//
12127   //                            Visitor Methods
12128   //===--------------------------------------------------------------------===//
12129 
12130   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12131     return Success(E->getValue(), E);
12132   }
12133 
12134   bool VisitCastExpr(const CastExpr *E);
12135   bool VisitUnaryOperator(const UnaryOperator *E);
12136   bool VisitBinaryOperator(const BinaryOperator *E);
12137 };
12138 } // end anonymous namespace
12139 
12140 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12141 /// produce either the integer value or a pointer.
12142 ///
12143 /// GCC has a heinous extension which folds casts between pointer types and
12144 /// pointer-sized integral types. We support this by allowing the evaluation of
12145 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12146 /// Some simple arithmetic on such values is supported (they are treated much
12147 /// like char*).
12148 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12149                                     EvalInfo &Info) {
12150   assert(!E->isValueDependent());
12151   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12152   return IntExprEvaluator(Info, Result).Visit(E);
12153 }
12154 
12155 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12156   assert(!E->isValueDependent());
12157   APValue Val;
12158   if (!EvaluateIntegerOrLValue(E, Val, Info))
12159     return false;
12160   if (!Val.isInt()) {
12161     // FIXME: It would be better to produce the diagnostic for casting
12162     //        a pointer to an integer.
12163     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12164     return false;
12165   }
12166   Result = Val.getInt();
12167   return true;
12168 }
12169 
12170 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12171   APValue Evaluated = E->EvaluateInContext(
12172       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12173   return Success(Evaluated, E);
12174 }
12175 
12176 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12177                                EvalInfo &Info) {
12178   assert(!E->isValueDependent());
12179   if (E->getType()->isFixedPointType()) {
12180     APValue Val;
12181     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12182       return false;
12183     if (!Val.isFixedPoint())
12184       return false;
12185 
12186     Result = Val.getFixedPoint();
12187     return true;
12188   }
12189   return false;
12190 }
12191 
12192 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12193                                         EvalInfo &Info) {
12194   assert(!E->isValueDependent());
12195   if (E->getType()->isIntegerType()) {
12196     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12197     APSInt Val;
12198     if (!EvaluateInteger(E, Val, Info))
12199       return false;
12200     Result = APFixedPoint(Val, FXSema);
12201     return true;
12202   } else if (E->getType()->isFixedPointType()) {
12203     return EvaluateFixedPoint(E, Result, Info);
12204   }
12205   return false;
12206 }
12207 
12208 /// Check whether the given declaration can be directly converted to an integral
12209 /// rvalue. If not, no diagnostic is produced; there are other things we can
12210 /// try.
12211 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12212   // Enums are integer constant exprs.
12213   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12214     // Check for signedness/width mismatches between E type and ECD value.
12215     bool SameSign = (ECD->getInitVal().isSigned()
12216                      == E->getType()->isSignedIntegerOrEnumerationType());
12217     bool SameWidth = (ECD->getInitVal().getBitWidth()
12218                       == Info.Ctx.getIntWidth(E->getType()));
12219     if (SameSign && SameWidth)
12220       return Success(ECD->getInitVal(), E);
12221     else {
12222       // Get rid of mismatch (otherwise Success assertions will fail)
12223       // by computing a new value matching the type of E.
12224       llvm::APSInt Val = ECD->getInitVal();
12225       if (!SameSign)
12226         Val.setIsSigned(!ECD->getInitVal().isSigned());
12227       if (!SameWidth)
12228         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12229       return Success(Val, E);
12230     }
12231   }
12232   return false;
12233 }
12234 
12235 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12236 /// as GCC.
12237 GCCTypeClass EvaluateBuiltinClassifyType(QualType T,
12238                                          const LangOptions &LangOpts) {
12239   assert(!T->isDependentType() && "unexpected dependent type");
12240 
12241   QualType CanTy = T.getCanonicalType();
12242 
12243   switch (CanTy->getTypeClass()) {
12244 #define TYPE(ID, BASE)
12245 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12246 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12247 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12248 #include "clang/AST/TypeNodes.inc"
12249   case Type::Auto:
12250   case Type::DeducedTemplateSpecialization:
12251       llvm_unreachable("unexpected non-canonical or dependent type");
12252 
12253   case Type::Builtin:
12254       switch (cast<BuiltinType>(CanTy)->getKind()) {
12255 #define BUILTIN_TYPE(ID, SINGLETON_ID)
12256 #define SIGNED_TYPE(ID, SINGLETON_ID) \
12257     case BuiltinType::ID: return GCCTypeClass::Integer;
12258 #define FLOATING_TYPE(ID, SINGLETON_ID) \
12259     case BuiltinType::ID: return GCCTypeClass::RealFloat;
12260 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12261     case BuiltinType::ID: break;
12262 #include "clang/AST/BuiltinTypes.def"
12263     case BuiltinType::Void:
12264       return GCCTypeClass::Void;
12265 
12266     case BuiltinType::Bool:
12267       return GCCTypeClass::Bool;
12268 
12269     case BuiltinType::Char_U:
12270     case BuiltinType::UChar:
12271     case BuiltinType::WChar_U:
12272     case BuiltinType::Char8:
12273     case BuiltinType::Char16:
12274     case BuiltinType::Char32:
12275     case BuiltinType::UShort:
12276     case BuiltinType::UInt:
12277     case BuiltinType::ULong:
12278     case BuiltinType::ULongLong:
12279     case BuiltinType::UInt128:
12280       return GCCTypeClass::Integer;
12281 
12282     case BuiltinType::UShortAccum:
12283     case BuiltinType::UAccum:
12284     case BuiltinType::ULongAccum:
12285     case BuiltinType::UShortFract:
12286     case BuiltinType::UFract:
12287     case BuiltinType::ULongFract:
12288     case BuiltinType::SatUShortAccum:
12289     case BuiltinType::SatUAccum:
12290     case BuiltinType::SatULongAccum:
12291     case BuiltinType::SatUShortFract:
12292     case BuiltinType::SatUFract:
12293     case BuiltinType::SatULongFract:
12294       return GCCTypeClass::None;
12295 
12296     case BuiltinType::NullPtr:
12297 
12298     case BuiltinType::ObjCId:
12299     case BuiltinType::ObjCClass:
12300     case BuiltinType::ObjCSel:
12301 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
12302     case BuiltinType::Id:
12303 #include "clang/Basic/OpenCLImageTypes.def"
12304 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
12305     case BuiltinType::Id:
12306 #include "clang/Basic/OpenCLExtensionTypes.def"
12307     case BuiltinType::OCLSampler:
12308     case BuiltinType::OCLEvent:
12309     case BuiltinType::OCLClkEvent:
12310     case BuiltinType::OCLQueue:
12311     case BuiltinType::OCLReserveID:
12312 #define SVE_TYPE(Name, Id, SingletonId) \
12313     case BuiltinType::Id:
12314 #include "clang/Basic/AArch64SVEACLETypes.def"
12315 #define PPC_VECTOR_TYPE(Name, Id, Size) \
12316     case BuiltinType::Id:
12317 #include "clang/Basic/PPCTypes.def"
12318 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12319 #include "clang/Basic/RISCVVTypes.def"
12320 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12321 #include "clang/Basic/WebAssemblyReferenceTypes.def"
12322 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
12323 #include "clang/Basic/AMDGPUTypes.def"
12324 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12325 #include "clang/Basic/HLSLIntangibleTypes.def"
12326       return GCCTypeClass::None;
12327 
12328     case BuiltinType::Dependent:
12329       llvm_unreachable("unexpected dependent type");
12330     };
12331     llvm_unreachable("unexpected placeholder type");
12332 
12333   case Type::Enum:
12334     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
12335 
12336   case Type::Pointer:
12337   case Type::ConstantArray:
12338   case Type::VariableArray:
12339   case Type::IncompleteArray:
12340   case Type::FunctionNoProto:
12341   case Type::FunctionProto:
12342   case Type::ArrayParameter:
12343     return GCCTypeClass::Pointer;
12344 
12345   case Type::MemberPointer:
12346     return CanTy->isMemberDataPointerType()
12347                ? GCCTypeClass::PointerToDataMember
12348                : GCCTypeClass::PointerToMemberFunction;
12349 
12350   case Type::Complex:
12351     return GCCTypeClass::Complex;
12352 
12353   case Type::Record:
12354     return CanTy->isUnionType() ? GCCTypeClass::Union
12355                                 : GCCTypeClass::ClassOrStruct;
12356 
12357   case Type::Atomic:
12358     // GCC classifies _Atomic T the same as T.
12359     return EvaluateBuiltinClassifyType(
12360         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
12361 
12362   case Type::Vector:
12363   case Type::ExtVector:
12364     return GCCTypeClass::Vector;
12365 
12366   case Type::BlockPointer:
12367   case Type::ConstantMatrix:
12368   case Type::ObjCObject:
12369   case Type::ObjCInterface:
12370   case Type::ObjCObjectPointer:
12371   case Type::Pipe:
12372   case Type::HLSLAttributedResource:
12373     // Classify all other types that don't fit into the regular
12374     // classification the same way.
12375     return GCCTypeClass::None;
12376 
12377   case Type::BitInt:
12378     return GCCTypeClass::BitInt;
12379 
12380   case Type::LValueReference:
12381   case Type::RValueReference:
12382     llvm_unreachable("invalid type for expression");
12383   }
12384 
12385   llvm_unreachable("unexpected type class");
12386 }
12387 
12388 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12389 /// as GCC.
12390 static GCCTypeClass
12391 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
12392   // If no argument was supplied, default to None. This isn't
12393   // ideal, however it is what gcc does.
12394   if (E->getNumArgs() == 0)
12395     return GCCTypeClass::None;
12396 
12397   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
12398   // being an ICE, but still folds it to a constant using the type of the first
12399   // argument.
12400   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
12401 }
12402 
12403 /// EvaluateBuiltinConstantPForLValue - Determine the result of
12404 /// __builtin_constant_p when applied to the given pointer.
12405 ///
12406 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
12407 /// or it points to the first character of a string literal.
12408 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
12409   APValue::LValueBase Base = LV.getLValueBase();
12410   if (Base.isNull()) {
12411     // A null base is acceptable.
12412     return true;
12413   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
12414     if (!isa<StringLiteral>(E))
12415       return false;
12416     return LV.getLValueOffset().isZero();
12417   } else if (Base.is<TypeInfoLValue>()) {
12418     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
12419     // evaluate to true.
12420     return true;
12421   } else {
12422     // Any other base is not constant enough for GCC.
12423     return false;
12424   }
12425 }
12426 
12427 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
12428 /// GCC as we can manage.
12429 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
12430   // This evaluation is not permitted to have side-effects, so evaluate it in
12431   // a speculative evaluation context.
12432   SpeculativeEvaluationRAII SpeculativeEval(Info);
12433 
12434   // Constant-folding is always enabled for the operand of __builtin_constant_p
12435   // (even when the enclosing evaluation context otherwise requires a strict
12436   // language-specific constant expression).
12437   FoldConstant Fold(Info, true);
12438 
12439   QualType ArgType = Arg->getType();
12440 
12441   // __builtin_constant_p always has one operand. The rules which gcc follows
12442   // are not precisely documented, but are as follows:
12443   //
12444   //  - If the operand is of integral, floating, complex or enumeration type,
12445   //    and can be folded to a known value of that type, it returns 1.
12446   //  - If the operand can be folded to a pointer to the first character
12447   //    of a string literal (or such a pointer cast to an integral type)
12448   //    or to a null pointer or an integer cast to a pointer, it returns 1.
12449   //
12450   // Otherwise, it returns 0.
12451   //
12452   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12453   // its support for this did not work prior to GCC 9 and is not yet well
12454   // understood.
12455   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12456       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12457       ArgType->isNullPtrType()) {
12458     APValue V;
12459     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12460       Fold.keepDiagnostics();
12461       return false;
12462     }
12463 
12464     // For a pointer (possibly cast to integer), there are special rules.
12465     if (V.getKind() == APValue::LValue)
12466       return EvaluateBuiltinConstantPForLValue(V);
12467 
12468     // Otherwise, any constant value is good enough.
12469     return V.hasValue();
12470   }
12471 
12472   // Anything else isn't considered to be sufficiently constant.
12473   return false;
12474 }
12475 
12476 /// Retrieves the "underlying object type" of the given expression,
12477 /// as used by __builtin_object_size.
12478 static QualType getObjectType(APValue::LValueBase B) {
12479   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12480     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
12481       return VD->getType();
12482   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12483     if (isa<CompoundLiteralExpr>(E))
12484       return E->getType();
12485   } else if (B.is<TypeInfoLValue>()) {
12486     return B.getTypeInfoType();
12487   } else if (B.is<DynamicAllocLValue>()) {
12488     return B.getDynamicAllocType();
12489   }
12490 
12491   return QualType();
12492 }
12493 
12494 /// A more selective version of E->IgnoreParenCasts for
12495 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12496 /// to change the type of E.
12497 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12498 ///
12499 /// Always returns an RValue with a pointer representation.
12500 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
12501   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12502 
12503   const Expr *NoParens = E->IgnoreParens();
12504   const auto *Cast = dyn_cast<CastExpr>(NoParens);
12505   if (Cast == nullptr)
12506     return NoParens;
12507 
12508   // We only conservatively allow a few kinds of casts, because this code is
12509   // inherently a simple solution that seeks to support the common case.
12510   auto CastKind = Cast->getCastKind();
12511   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12512       CastKind != CK_AddressSpaceConversion)
12513     return NoParens;
12514 
12515   const auto *SubExpr = Cast->getSubExpr();
12516   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12517     return NoParens;
12518   return ignorePointerCastsAndParens(SubExpr);
12519 }
12520 
12521 /// Checks to see if the given LValue's Designator is at the end of the LValue's
12522 /// record layout. e.g.
12523 ///   struct { struct { int a, b; } fst, snd; } obj;
12524 ///   obj.fst   // no
12525 ///   obj.snd   // yes
12526 ///   obj.fst.a // no
12527 ///   obj.fst.b // no
12528 ///   obj.snd.a // no
12529 ///   obj.snd.b // yes
12530 ///
12531 /// Please note: this function is specialized for how __builtin_object_size
12532 /// views "objects".
12533 ///
12534 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
12535 /// correct result, it will always return true.
12536 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12537   assert(!LVal.Designator.Invalid);
12538 
12539   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12540     const RecordDecl *Parent = FD->getParent();
12541     Invalid = Parent->isInvalidDecl();
12542     if (Invalid || Parent->isUnion())
12543       return true;
12544     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12545     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12546   };
12547 
12548   auto &Base = LVal.getLValueBase();
12549   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12550     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12551       bool Invalid;
12552       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12553         return Invalid;
12554     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12555       for (auto *FD : IFD->chain()) {
12556         bool Invalid;
12557         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
12558           return Invalid;
12559       }
12560     }
12561   }
12562 
12563   unsigned I = 0;
12564   QualType BaseType = getType(Base);
12565   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12566     // If we don't know the array bound, conservatively assume we're looking at
12567     // the final array element.
12568     ++I;
12569     if (BaseType->isIncompleteArrayType())
12570       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12571     else
12572       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12573   }
12574 
12575   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12576     const auto &Entry = LVal.Designator.Entries[I];
12577     if (BaseType->isArrayType()) {
12578       // Because __builtin_object_size treats arrays as objects, we can ignore
12579       // the index iff this is the last array in the Designator.
12580       if (I + 1 == E)
12581         return true;
12582       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12583       uint64_t Index = Entry.getAsArrayIndex();
12584       if (Index + 1 != CAT->getZExtSize())
12585         return false;
12586       BaseType = CAT->getElementType();
12587     } else if (BaseType->isAnyComplexType()) {
12588       const auto *CT = BaseType->castAs<ComplexType>();
12589       uint64_t Index = Entry.getAsArrayIndex();
12590       if (Index != 1)
12591         return false;
12592       BaseType = CT->getElementType();
12593     } else if (auto *FD = getAsField(Entry)) {
12594       bool Invalid;
12595       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12596         return Invalid;
12597       BaseType = FD->getType();
12598     } else {
12599       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12600       return false;
12601     }
12602   }
12603   return true;
12604 }
12605 
12606 /// Tests to see if the LValue has a user-specified designator (that isn't
12607 /// necessarily valid). Note that this always returns 'true' if the LValue has
12608 /// an unsized array as its first designator entry, because there's currently no
12609 /// way to tell if the user typed *foo or foo[0].
12610 static bool refersToCompleteObject(const LValue &LVal) {
12611   if (LVal.Designator.Invalid)
12612     return false;
12613 
12614   if (!LVal.Designator.Entries.empty())
12615     return LVal.Designator.isMostDerivedAnUnsizedArray();
12616 
12617   if (!LVal.InvalidBase)
12618     return true;
12619 
12620   // If `E` is a MemberExpr, then the first part of the designator is hiding in
12621   // the LValueBase.
12622   const auto *E = LVal.Base.dyn_cast<const Expr *>();
12623   return !E || !isa<MemberExpr>(E);
12624 }
12625 
12626 /// Attempts to detect a user writing into a piece of memory that's impossible
12627 /// to figure out the size of by just using types.
12628 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12629   const SubobjectDesignator &Designator = LVal.Designator;
12630   // Notes:
12631   // - Users can only write off of the end when we have an invalid base. Invalid
12632   //   bases imply we don't know where the memory came from.
12633   // - We used to be a bit more aggressive here; we'd only be conservative if
12634   //   the array at the end was flexible, or if it had 0 or 1 elements. This
12635   //   broke some common standard library extensions (PR30346), but was
12636   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
12637   //   with some sort of list. OTOH, it seems that GCC is always
12638   //   conservative with the last element in structs (if it's an array), so our
12639   //   current behavior is more compatible than an explicit list approach would
12640   //   be.
12641   auto isFlexibleArrayMember = [&] {
12642     using FAMKind = LangOptions::StrictFlexArraysLevelKind;
12643     FAMKind StrictFlexArraysLevel =
12644         Ctx.getLangOpts().getStrictFlexArraysLevel();
12645 
12646     if (Designator.isMostDerivedAnUnsizedArray())
12647       return true;
12648 
12649     if (StrictFlexArraysLevel == FAMKind::Default)
12650       return true;
12651 
12652     if (Designator.getMostDerivedArraySize() == 0 &&
12653         StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12654       return true;
12655 
12656     if (Designator.getMostDerivedArraySize() == 1 &&
12657         StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12658       return true;
12659 
12660     return false;
12661   };
12662 
12663   return LVal.InvalidBase &&
12664          Designator.Entries.size() == Designator.MostDerivedPathLength &&
12665          Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12666          isDesignatorAtObjectEnd(Ctx, LVal);
12667 }
12668 
12669 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12670 /// Fails if the conversion would cause loss of precision.
12671 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12672                                             CharUnits &Result) {
12673   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12674   if (Int.ugt(CharUnitsMax))
12675     return false;
12676   Result = CharUnits::fromQuantity(Int.getZExtValue());
12677   return true;
12678 }
12679 
12680 /// If we're evaluating the object size of an instance of a struct that
12681 /// contains a flexible array member, add the size of the initializer.
12682 static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12683                                            const LValue &LV, CharUnits &Size) {
12684   if (!T.isNull() && T->isStructureType() &&
12685       T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
12686     if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12687       if (const auto *VD = dyn_cast<VarDecl>(V))
12688         if (VD->hasInit())
12689           Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12690 }
12691 
12692 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12693 /// determine how many bytes exist from the beginning of the object to either
12694 /// the end of the current subobject, or the end of the object itself, depending
12695 /// on what the LValue looks like + the value of Type.
12696 ///
12697 /// If this returns false, the value of Result is undefined.
12698 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12699                                unsigned Type, const LValue &LVal,
12700                                CharUnits &EndOffset) {
12701   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12702 
12703   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12704     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12705       return false;
12706 
12707     if (Ty->isReferenceType())
12708       Ty = Ty.getNonReferenceType();
12709 
12710     return HandleSizeof(Info, ExprLoc, Ty, Result);
12711   };
12712 
12713   // We want to evaluate the size of the entire object. This is a valid fallback
12714   // for when Type=1 and the designator is invalid, because we're asked for an
12715   // upper-bound.
12716   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12717     // Type=3 wants a lower bound, so we can't fall back to this.
12718     if (Type == 3 && !DetermineForCompleteObject)
12719       return false;
12720 
12721     llvm::APInt APEndOffset;
12722     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12723         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12724       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12725 
12726     if (LVal.InvalidBase)
12727       return false;
12728 
12729     QualType BaseTy = getObjectType(LVal.getLValueBase());
12730     const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12731     addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12732     return Ret;
12733   }
12734 
12735   // We want to evaluate the size of a subobject.
12736   const SubobjectDesignator &Designator = LVal.Designator;
12737 
12738   // The following is a moderately common idiom in C:
12739   //
12740   // struct Foo { int a; char c[1]; };
12741   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12742   // strcpy(&F->c[0], Bar);
12743   //
12744   // In order to not break too much legacy code, we need to support it.
12745   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12746     // If we can resolve this to an alloc_size call, we can hand that back,
12747     // because we know for certain how many bytes there are to write to.
12748     llvm::APInt APEndOffset;
12749     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12750         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12751       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12752 
12753     // If we cannot determine the size of the initial allocation, then we can't
12754     // given an accurate upper-bound. However, we are still able to give
12755     // conservative lower-bounds for Type=3.
12756     if (Type == 1)
12757       return false;
12758   }
12759 
12760   CharUnits BytesPerElem;
12761   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12762     return false;
12763 
12764   // According to the GCC documentation, we want the size of the subobject
12765   // denoted by the pointer. But that's not quite right -- what we actually
12766   // want is the size of the immediately-enclosing array, if there is one.
12767   int64_t ElemsRemaining;
12768   if (Designator.MostDerivedIsArrayElement &&
12769       Designator.Entries.size() == Designator.MostDerivedPathLength) {
12770     uint64_t ArraySize = Designator.getMostDerivedArraySize();
12771     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12772     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12773   } else {
12774     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12775   }
12776 
12777   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12778   return true;
12779 }
12780 
12781 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
12782 /// returns true and stores the result in @p Size.
12783 ///
12784 /// If @p WasError is non-null, this will report whether the failure to evaluate
12785 /// is to be treated as an Error in IntExprEvaluator.
12786 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12787                                          EvalInfo &Info, uint64_t &Size) {
12788   // Determine the denoted object.
12789   LValue LVal;
12790   {
12791     // The operand of __builtin_object_size is never evaluated for side-effects.
12792     // If there are any, but we can determine the pointed-to object anyway, then
12793     // ignore the side-effects.
12794     SpeculativeEvaluationRAII SpeculativeEval(Info);
12795     IgnoreSideEffectsRAII Fold(Info);
12796 
12797     if (E->isGLValue()) {
12798       // It's possible for us to be given GLValues if we're called via
12799       // Expr::tryEvaluateObjectSize.
12800       APValue RVal;
12801       if (!EvaluateAsRValue(Info, E, RVal))
12802         return false;
12803       LVal.setFrom(Info.Ctx, RVal);
12804     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12805                                 /*InvalidBaseOK=*/true))
12806       return false;
12807   }
12808 
12809   // If we point to before the start of the object, there are no accessible
12810   // bytes.
12811   if (LVal.getLValueOffset().isNegative()) {
12812     Size = 0;
12813     return true;
12814   }
12815 
12816   CharUnits EndOffset;
12817   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12818     return false;
12819 
12820   // If we've fallen outside of the end offset, just pretend there's nothing to
12821   // write to/read from.
12822   if (EndOffset <= LVal.getLValueOffset())
12823     Size = 0;
12824   else
12825     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12826   return true;
12827 }
12828 
12829 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12830   if (!IsConstantEvaluatedBuiltinCall(E))
12831     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12832   return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12833 }
12834 
12835 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12836                                      APValue &Val, APSInt &Alignment) {
12837   QualType SrcTy = E->getArg(0)->getType();
12838   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12839     return false;
12840   // Even though we are evaluating integer expressions we could get a pointer
12841   // argument for the __builtin_is_aligned() case.
12842   if (SrcTy->isPointerType()) {
12843     LValue Ptr;
12844     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12845       return false;
12846     Ptr.moveInto(Val);
12847   } else if (!SrcTy->isIntegralOrEnumerationType()) {
12848     Info.FFDiag(E->getArg(0));
12849     return false;
12850   } else {
12851     APSInt SrcInt;
12852     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12853       return false;
12854     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12855            "Bit widths must be the same");
12856     Val = APValue(SrcInt);
12857   }
12858   assert(Val.hasValue());
12859   return true;
12860 }
12861 
12862 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12863                                             unsigned BuiltinOp) {
12864   switch (BuiltinOp) {
12865   default:
12866     return false;
12867 
12868   case Builtin::BI__builtin_dynamic_object_size:
12869   case Builtin::BI__builtin_object_size: {
12870     // The type was checked when we built the expression.
12871     unsigned Type =
12872         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12873     assert(Type <= 3 && "unexpected type");
12874 
12875     uint64_t Size;
12876     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12877       return Success(Size, E);
12878 
12879     if (E->getArg(0)->HasSideEffects(Info.Ctx))
12880       return Success((Type & 2) ? 0 : -1, E);
12881 
12882     // Expression had no side effects, but we couldn't statically determine the
12883     // size of the referenced object.
12884     switch (Info.EvalMode) {
12885     case EvalInfo::EM_ConstantExpression:
12886     case EvalInfo::EM_ConstantFold:
12887     case EvalInfo::EM_IgnoreSideEffects:
12888       // Leave it to IR generation.
12889       return Error(E);
12890     case EvalInfo::EM_ConstantExpressionUnevaluated:
12891       // Reduce it to a constant now.
12892       return Success((Type & 2) ? 0 : -1, E);
12893     }
12894 
12895     llvm_unreachable("unexpected EvalMode");
12896   }
12897 
12898   case Builtin::BI__builtin_os_log_format_buffer_size: {
12899     analyze_os_log::OSLogBufferLayout Layout;
12900     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
12901     return Success(Layout.size().getQuantity(), E);
12902   }
12903 
12904   case Builtin::BI__builtin_is_aligned: {
12905     APValue Src;
12906     APSInt Alignment;
12907     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12908       return false;
12909     if (Src.isLValue()) {
12910       // If we evaluated a pointer, check the minimum known alignment.
12911       LValue Ptr;
12912       Ptr.setFrom(Info.Ctx, Src);
12913       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12914       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12915       // We can return true if the known alignment at the computed offset is
12916       // greater than the requested alignment.
12917       assert(PtrAlign.isPowerOfTwo());
12918       assert(Alignment.isPowerOf2());
12919       if (PtrAlign.getQuantity() >= Alignment)
12920         return Success(1, E);
12921       // If the alignment is not known to be sufficient, some cases could still
12922       // be aligned at run time. However, if the requested alignment is less or
12923       // equal to the base alignment and the offset is not aligned, we know that
12924       // the run-time value can never be aligned.
12925       if (BaseAlignment.getQuantity() >= Alignment &&
12926           PtrAlign.getQuantity() < Alignment)
12927         return Success(0, E);
12928       // Otherwise we can't infer whether the value is sufficiently aligned.
12929       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12930       //  in cases where we can't fully evaluate the pointer.
12931       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12932           << Alignment;
12933       return false;
12934     }
12935     assert(Src.isInt());
12936     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12937   }
12938   case Builtin::BI__builtin_align_up: {
12939     APValue Src;
12940     APSInt Alignment;
12941     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12942       return false;
12943     if (!Src.isInt())
12944       return Error(E);
12945     APSInt AlignedVal =
12946         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12947                Src.getInt().isUnsigned());
12948     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12949     return Success(AlignedVal, E);
12950   }
12951   case Builtin::BI__builtin_align_down: {
12952     APValue Src;
12953     APSInt Alignment;
12954     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12955       return false;
12956     if (!Src.isInt())
12957       return Error(E);
12958     APSInt AlignedVal =
12959         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12960     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12961     return Success(AlignedVal, E);
12962   }
12963 
12964   case Builtin::BI__builtin_bitreverse8:
12965   case Builtin::BI__builtin_bitreverse16:
12966   case Builtin::BI__builtin_bitreverse32:
12967   case Builtin::BI__builtin_bitreverse64:
12968   case Builtin::BI__builtin_elementwise_bitreverse: {
12969     APSInt Val;
12970     if (!EvaluateInteger(E->getArg(0), Val, Info))
12971       return false;
12972 
12973     return Success(Val.reverseBits(), E);
12974   }
12975 
12976   case Builtin::BI__builtin_bswap16:
12977   case Builtin::BI__builtin_bswap32:
12978   case Builtin::BI__builtin_bswap64: {
12979     APSInt Val;
12980     if (!EvaluateInteger(E->getArg(0), Val, Info))
12981       return false;
12982 
12983     return Success(Val.byteSwap(), E);
12984   }
12985 
12986   case Builtin::BI__builtin_classify_type:
12987     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12988 
12989   case Builtin::BI__builtin_clrsb:
12990   case Builtin::BI__builtin_clrsbl:
12991   case Builtin::BI__builtin_clrsbll: {
12992     APSInt Val;
12993     if (!EvaluateInteger(E->getArg(0), Val, Info))
12994       return false;
12995 
12996     return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12997   }
12998 
12999   case Builtin::BI__builtin_clz:
13000   case Builtin::BI__builtin_clzl:
13001   case Builtin::BI__builtin_clzll:
13002   case Builtin::BI__builtin_clzs:
13003   case Builtin::BI__builtin_clzg:
13004   case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
13005   case Builtin::BI__lzcnt:
13006   case Builtin::BI__lzcnt64: {
13007     APSInt Val;
13008     if (!EvaluateInteger(E->getArg(0), Val, Info))
13009       return false;
13010 
13011     std::optional<APSInt> Fallback;
13012     if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
13013       APSInt FallbackTemp;
13014       if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13015         return false;
13016       Fallback = FallbackTemp;
13017     }
13018 
13019     if (!Val) {
13020       if (Fallback)
13021         return Success(*Fallback, E);
13022 
13023       // When the argument is 0, the result of GCC builtins is undefined,
13024       // whereas for Microsoft intrinsics, the result is the bit-width of the
13025       // argument.
13026       bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
13027                              BuiltinOp != Builtin::BI__lzcnt &&
13028                              BuiltinOp != Builtin::BI__lzcnt64;
13029 
13030       if (ZeroIsUndefined)
13031         return Error(E);
13032     }
13033 
13034     return Success(Val.countl_zero(), E);
13035   }
13036 
13037   case Builtin::BI__builtin_constant_p: {
13038     const Expr *Arg = E->getArg(0);
13039     if (EvaluateBuiltinConstantP(Info, Arg))
13040       return Success(true, E);
13041     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
13042       // Outside a constant context, eagerly evaluate to false in the presence
13043       // of side-effects in order to avoid -Wunsequenced false-positives in
13044       // a branch on __builtin_constant_p(expr).
13045       return Success(false, E);
13046     }
13047     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13048     return false;
13049   }
13050 
13051   case Builtin::BI__noop:
13052     // __noop always evaluates successfully and returns 0.
13053     return Success(0, E);
13054 
13055   case Builtin::BI__builtin_is_constant_evaluated: {
13056     const auto *Callee = Info.CurrentCall->getCallee();
13057     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
13058         (Info.CallStackDepth == 1 ||
13059          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
13060           Callee->getIdentifier() &&
13061           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
13062       // FIXME: Find a better way to avoid duplicated diagnostics.
13063       if (Info.EvalStatus.Diag)
13064         Info.report((Info.CallStackDepth == 1)
13065                         ? E->getExprLoc()
13066                         : Info.CurrentCall->getCallRange().getBegin(),
13067                     diag::warn_is_constant_evaluated_always_true_constexpr)
13068             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
13069                                          : "std::is_constant_evaluated");
13070     }
13071 
13072     return Success(Info.InConstantContext, E);
13073   }
13074 
13075   case Builtin::BI__builtin_is_within_lifetime:
13076     if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
13077       return Success(*result, E);
13078     return false;
13079 
13080   case Builtin::BI__builtin_ctz:
13081   case Builtin::BI__builtin_ctzl:
13082   case Builtin::BI__builtin_ctzll:
13083   case Builtin::BI__builtin_ctzs:
13084   case Builtin::BI__builtin_ctzg: {
13085     APSInt Val;
13086     if (!EvaluateInteger(E->getArg(0), Val, Info))
13087       return false;
13088 
13089     std::optional<APSInt> Fallback;
13090     if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
13091       APSInt FallbackTemp;
13092       if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13093         return false;
13094       Fallback = FallbackTemp;
13095     }
13096 
13097     if (!Val) {
13098       if (Fallback)
13099         return Success(*Fallback, E);
13100 
13101       return Error(E);
13102     }
13103 
13104     return Success(Val.countr_zero(), E);
13105   }
13106 
13107   case Builtin::BI__builtin_eh_return_data_regno: {
13108     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13109     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13110     return Success(Operand, E);
13111   }
13112 
13113   case Builtin::BI__builtin_expect:
13114   case Builtin::BI__builtin_expect_with_probability:
13115     return Visit(E->getArg(0));
13116 
13117   case Builtin::BI__builtin_ptrauth_string_discriminator: {
13118     const auto *Literal =
13119         cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
13120     uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13121     return Success(Result, E);
13122   }
13123 
13124   case Builtin::BI__builtin_ffs:
13125   case Builtin::BI__builtin_ffsl:
13126   case Builtin::BI__builtin_ffsll: {
13127     APSInt Val;
13128     if (!EvaluateInteger(E->getArg(0), Val, Info))
13129       return false;
13130 
13131     unsigned N = Val.countr_zero();
13132     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13133   }
13134 
13135   case Builtin::BI__builtin_fpclassify: {
13136     APFloat Val(0.0);
13137     if (!EvaluateFloat(E->getArg(5), Val, Info))
13138       return false;
13139     unsigned Arg;
13140     switch (Val.getCategory()) {
13141     case APFloat::fcNaN: Arg = 0; break;
13142     case APFloat::fcInfinity: Arg = 1; break;
13143     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13144     case APFloat::fcZero: Arg = 4; break;
13145     }
13146     return Visit(E->getArg(Arg));
13147   }
13148 
13149   case Builtin::BI__builtin_isinf_sign: {
13150     APFloat Val(0.0);
13151     return EvaluateFloat(E->getArg(0), Val, Info) &&
13152            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13153   }
13154 
13155   case Builtin::BI__builtin_isinf: {
13156     APFloat Val(0.0);
13157     return EvaluateFloat(E->getArg(0), Val, Info) &&
13158            Success(Val.isInfinity() ? 1 : 0, E);
13159   }
13160 
13161   case Builtin::BI__builtin_isfinite: {
13162     APFloat Val(0.0);
13163     return EvaluateFloat(E->getArg(0), Val, Info) &&
13164            Success(Val.isFinite() ? 1 : 0, E);
13165   }
13166 
13167   case Builtin::BI__builtin_isnan: {
13168     APFloat Val(0.0);
13169     return EvaluateFloat(E->getArg(0), Val, Info) &&
13170            Success(Val.isNaN() ? 1 : 0, E);
13171   }
13172 
13173   case Builtin::BI__builtin_isnormal: {
13174     APFloat Val(0.0);
13175     return EvaluateFloat(E->getArg(0), Val, Info) &&
13176            Success(Val.isNormal() ? 1 : 0, E);
13177   }
13178 
13179   case Builtin::BI__builtin_issubnormal: {
13180     APFloat Val(0.0);
13181     return EvaluateFloat(E->getArg(0), Val, Info) &&
13182            Success(Val.isDenormal() ? 1 : 0, E);
13183   }
13184 
13185   case Builtin::BI__builtin_iszero: {
13186     APFloat Val(0.0);
13187     return EvaluateFloat(E->getArg(0), Val, Info) &&
13188            Success(Val.isZero() ? 1 : 0, E);
13189   }
13190 
13191   case Builtin::BI__builtin_signbit:
13192   case Builtin::BI__builtin_signbitf:
13193   case Builtin::BI__builtin_signbitl: {
13194     APFloat Val(0.0);
13195     return EvaluateFloat(E->getArg(0), Val, Info) &&
13196            Success(Val.isNegative() ? 1 : 0, E);
13197   }
13198 
13199   case Builtin::BI__builtin_isgreater:
13200   case Builtin::BI__builtin_isgreaterequal:
13201   case Builtin::BI__builtin_isless:
13202   case Builtin::BI__builtin_islessequal:
13203   case Builtin::BI__builtin_islessgreater:
13204   case Builtin::BI__builtin_isunordered: {
13205     APFloat LHS(0.0);
13206     APFloat RHS(0.0);
13207     if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13208         !EvaluateFloat(E->getArg(1), RHS, Info))
13209       return false;
13210 
13211     return Success(
13212         [&] {
13213           switch (BuiltinOp) {
13214           case Builtin::BI__builtin_isgreater:
13215             return LHS > RHS;
13216           case Builtin::BI__builtin_isgreaterequal:
13217             return LHS >= RHS;
13218           case Builtin::BI__builtin_isless:
13219             return LHS < RHS;
13220           case Builtin::BI__builtin_islessequal:
13221             return LHS <= RHS;
13222           case Builtin::BI__builtin_islessgreater: {
13223             APFloat::cmpResult cmp = LHS.compare(RHS);
13224             return cmp == APFloat::cmpResult::cmpLessThan ||
13225                    cmp == APFloat::cmpResult::cmpGreaterThan;
13226           }
13227           case Builtin::BI__builtin_isunordered:
13228             return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13229           default:
13230             llvm_unreachable("Unexpected builtin ID: Should be a floating "
13231                              "point comparison function");
13232           }
13233         }()
13234             ? 1
13235             : 0,
13236         E);
13237   }
13238 
13239   case Builtin::BI__builtin_issignaling: {
13240     APFloat Val(0.0);
13241     return EvaluateFloat(E->getArg(0), Val, Info) &&
13242            Success(Val.isSignaling() ? 1 : 0, E);
13243   }
13244 
13245   case Builtin::BI__builtin_isfpclass: {
13246     APSInt MaskVal;
13247     if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
13248       return false;
13249     unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
13250     APFloat Val(0.0);
13251     return EvaluateFloat(E->getArg(0), Val, Info) &&
13252            Success((Val.classify() & Test) ? 1 : 0, E);
13253   }
13254 
13255   case Builtin::BI__builtin_parity:
13256   case Builtin::BI__builtin_parityl:
13257   case Builtin::BI__builtin_parityll: {
13258     APSInt Val;
13259     if (!EvaluateInteger(E->getArg(0), Val, Info))
13260       return false;
13261 
13262     return Success(Val.popcount() % 2, E);
13263   }
13264 
13265   case Builtin::BI__builtin_abs:
13266   case Builtin::BI__builtin_labs:
13267   case Builtin::BI__builtin_llabs: {
13268     APSInt Val;
13269     if (!EvaluateInteger(E->getArg(0), Val, Info))
13270       return false;
13271     if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
13272                       /*IsUnsigned=*/false))
13273       return false;
13274     if (Val.isNegative())
13275       Val.negate();
13276     return Success(Val, E);
13277   }
13278 
13279   case Builtin::BI__builtin_popcount:
13280   case Builtin::BI__builtin_popcountl:
13281   case Builtin::BI__builtin_popcountll:
13282   case Builtin::BI__builtin_popcountg:
13283   case Builtin::BI__builtin_elementwise_popcount:
13284   case Builtin::BI__popcnt16: // Microsoft variants of popcount
13285   case Builtin::BI__popcnt:
13286   case Builtin::BI__popcnt64: {
13287     APSInt Val;
13288     if (!EvaluateInteger(E->getArg(0), Val, Info))
13289       return false;
13290 
13291     return Success(Val.popcount(), E);
13292   }
13293 
13294   case Builtin::BI__builtin_rotateleft8:
13295   case Builtin::BI__builtin_rotateleft16:
13296   case Builtin::BI__builtin_rotateleft32:
13297   case Builtin::BI__builtin_rotateleft64:
13298   case Builtin::BI_rotl8: // Microsoft variants of rotate right
13299   case Builtin::BI_rotl16:
13300   case Builtin::BI_rotl:
13301   case Builtin::BI_lrotl:
13302   case Builtin::BI_rotl64: {
13303     APSInt Val, Amt;
13304     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13305         !EvaluateInteger(E->getArg(1), Amt, Info))
13306       return false;
13307 
13308     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
13309   }
13310 
13311   case Builtin::BI__builtin_rotateright8:
13312   case Builtin::BI__builtin_rotateright16:
13313   case Builtin::BI__builtin_rotateright32:
13314   case Builtin::BI__builtin_rotateright64:
13315   case Builtin::BI_rotr8: // Microsoft variants of rotate right
13316   case Builtin::BI_rotr16:
13317   case Builtin::BI_rotr:
13318   case Builtin::BI_lrotr:
13319   case Builtin::BI_rotr64: {
13320     APSInt Val, Amt;
13321     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13322         !EvaluateInteger(E->getArg(1), Amt, Info))
13323       return false;
13324 
13325     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
13326   }
13327 
13328   case Builtin::BI__builtin_elementwise_add_sat: {
13329     APSInt LHS, RHS;
13330     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13331         !EvaluateInteger(E->getArg(1), RHS, Info))
13332       return false;
13333 
13334     APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
13335     return Success(APSInt(Result, !LHS.isSigned()), E);
13336   }
13337   case Builtin::BI__builtin_elementwise_sub_sat: {
13338     APSInt LHS, RHS;
13339     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13340         !EvaluateInteger(E->getArg(1), RHS, Info))
13341       return false;
13342 
13343     APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
13344     return Success(APSInt(Result, !LHS.isSigned()), E);
13345   }
13346 
13347   case Builtin::BIstrlen:
13348   case Builtin::BIwcslen:
13349     // A call to strlen is not a constant expression.
13350     if (Info.getLangOpts().CPlusPlus11)
13351       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13352           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13353           << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13354     else
13355       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13356     [[fallthrough]];
13357   case Builtin::BI__builtin_strlen:
13358   case Builtin::BI__builtin_wcslen: {
13359     // As an extension, we support __builtin_strlen() as a constant expression,
13360     // and support folding strlen() to a constant.
13361     uint64_t StrLen;
13362     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
13363       return Success(StrLen, E);
13364     return false;
13365   }
13366 
13367   case Builtin::BIstrcmp:
13368   case Builtin::BIwcscmp:
13369   case Builtin::BIstrncmp:
13370   case Builtin::BIwcsncmp:
13371   case Builtin::BImemcmp:
13372   case Builtin::BIbcmp:
13373   case Builtin::BIwmemcmp:
13374     // A call to strlen is not a constant expression.
13375     if (Info.getLangOpts().CPlusPlus11)
13376       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13377           << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13378           << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13379     else
13380       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13381     [[fallthrough]];
13382   case Builtin::BI__builtin_strcmp:
13383   case Builtin::BI__builtin_wcscmp:
13384   case Builtin::BI__builtin_strncmp:
13385   case Builtin::BI__builtin_wcsncmp:
13386   case Builtin::BI__builtin_memcmp:
13387   case Builtin::BI__builtin_bcmp:
13388   case Builtin::BI__builtin_wmemcmp: {
13389     LValue String1, String2;
13390     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
13391         !EvaluatePointer(E->getArg(1), String2, Info))
13392       return false;
13393 
13394     uint64_t MaxLength = uint64_t(-1);
13395     if (BuiltinOp != Builtin::BIstrcmp &&
13396         BuiltinOp != Builtin::BIwcscmp &&
13397         BuiltinOp != Builtin::BI__builtin_strcmp &&
13398         BuiltinOp != Builtin::BI__builtin_wcscmp) {
13399       APSInt N;
13400       if (!EvaluateInteger(E->getArg(2), N, Info))
13401         return false;
13402       MaxLength = N.getZExtValue();
13403     }
13404 
13405     // Empty substrings compare equal by definition.
13406     if (MaxLength == 0u)
13407       return Success(0, E);
13408 
13409     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13410         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13411         String1.Designator.Invalid || String2.Designator.Invalid)
13412       return false;
13413 
13414     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
13415     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
13416 
13417     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
13418                      BuiltinOp == Builtin::BIbcmp ||
13419                      BuiltinOp == Builtin::BI__builtin_memcmp ||
13420                      BuiltinOp == Builtin::BI__builtin_bcmp;
13421 
13422     assert(IsRawByte ||
13423            (Info.Ctx.hasSameUnqualifiedType(
13424                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
13425             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
13426 
13427     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
13428     // 'char8_t', but no other types.
13429     if (IsRawByte &&
13430         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
13431       // FIXME: Consider using our bit_cast implementation to support this.
13432       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
13433           << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
13434           << CharTy2;
13435       return false;
13436     }
13437 
13438     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
13439       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
13440              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
13441              Char1.isInt() && Char2.isInt();
13442     };
13443     const auto &AdvanceElems = [&] {
13444       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
13445              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
13446     };
13447 
13448     bool StopAtNull =
13449         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
13450          BuiltinOp != Builtin::BIwmemcmp &&
13451          BuiltinOp != Builtin::BI__builtin_memcmp &&
13452          BuiltinOp != Builtin::BI__builtin_bcmp &&
13453          BuiltinOp != Builtin::BI__builtin_wmemcmp);
13454     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
13455                   BuiltinOp == Builtin::BIwcsncmp ||
13456                   BuiltinOp == Builtin::BIwmemcmp ||
13457                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
13458                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
13459                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
13460 
13461     for (; MaxLength; --MaxLength) {
13462       APValue Char1, Char2;
13463       if (!ReadCurElems(Char1, Char2))
13464         return false;
13465       if (Char1.getInt().ne(Char2.getInt())) {
13466         if (IsWide) // wmemcmp compares with wchar_t signedness.
13467           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
13468         // memcmp always compares unsigned chars.
13469         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
13470       }
13471       if (StopAtNull && !Char1.getInt())
13472         return Success(0, E);
13473       assert(!(StopAtNull && !Char2.getInt()));
13474       if (!AdvanceElems())
13475         return false;
13476     }
13477     // We hit the strncmp / memcmp limit.
13478     return Success(0, E);
13479   }
13480 
13481   case Builtin::BI__atomic_always_lock_free:
13482   case Builtin::BI__atomic_is_lock_free:
13483   case Builtin::BI__c11_atomic_is_lock_free: {
13484     APSInt SizeVal;
13485     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
13486       return false;
13487 
13488     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
13489     // of two less than or equal to the maximum inline atomic width, we know it
13490     // is lock-free.  If the size isn't a power of two, or greater than the
13491     // maximum alignment where we promote atomics, we know it is not lock-free
13492     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
13493     // the answer can only be determined at runtime; for example, 16-byte
13494     // atomics have lock-free implementations on some, but not all,
13495     // x86-64 processors.
13496 
13497     // Check power-of-two.
13498     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
13499     if (Size.isPowerOfTwo()) {
13500       // Check against inlining width.
13501       unsigned InlineWidthBits =
13502           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
13503       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
13504         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
13505             Size == CharUnits::One())
13506           return Success(1, E);
13507 
13508         // If the pointer argument can be evaluated to a compile-time constant
13509         // integer (or nullptr), check if that value is appropriately aligned.
13510         const Expr *PtrArg = E->getArg(1);
13511         Expr::EvalResult ExprResult;
13512         APSInt IntResult;
13513         if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
13514             ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
13515                                               Info.Ctx) &&
13516             IntResult.isAligned(Size.getAsAlign()))
13517           return Success(1, E);
13518 
13519         // Otherwise, check if the type's alignment against Size.
13520         if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
13521           // Drop the potential implicit-cast to 'const volatile void*', getting
13522           // the underlying type.
13523           if (ICE->getCastKind() == CK_BitCast)
13524             PtrArg = ICE->getSubExpr();
13525         }
13526 
13527         if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
13528           QualType PointeeType = PtrTy->getPointeeType();
13529           if (!PointeeType->isIncompleteType() &&
13530               Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
13531             // OK, we will inline operations on this object.
13532             return Success(1, E);
13533           }
13534         }
13535       }
13536     }
13537 
13538     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
13539         Success(0, E) : Error(E);
13540   }
13541   case Builtin::BI__builtin_addcb:
13542   case Builtin::BI__builtin_addcs:
13543   case Builtin::BI__builtin_addc:
13544   case Builtin::BI__builtin_addcl:
13545   case Builtin::BI__builtin_addcll:
13546   case Builtin::BI__builtin_subcb:
13547   case Builtin::BI__builtin_subcs:
13548   case Builtin::BI__builtin_subc:
13549   case Builtin::BI__builtin_subcl:
13550   case Builtin::BI__builtin_subcll: {
13551     LValue CarryOutLValue;
13552     APSInt LHS, RHS, CarryIn, CarryOut, Result;
13553     QualType ResultType = E->getArg(0)->getType();
13554     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13555         !EvaluateInteger(E->getArg(1), RHS, Info) ||
13556         !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13557         !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13558       return false;
13559     // Copy the number of bits and sign.
13560     Result = LHS;
13561     CarryOut = LHS;
13562 
13563     bool FirstOverflowed = false;
13564     bool SecondOverflowed = false;
13565     switch (BuiltinOp) {
13566     default:
13567       llvm_unreachable("Invalid value for BuiltinOp");
13568     case Builtin::BI__builtin_addcb:
13569     case Builtin::BI__builtin_addcs:
13570     case Builtin::BI__builtin_addc:
13571     case Builtin::BI__builtin_addcl:
13572     case Builtin::BI__builtin_addcll:
13573       Result =
13574           LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
13575       break;
13576     case Builtin::BI__builtin_subcb:
13577     case Builtin::BI__builtin_subcs:
13578     case Builtin::BI__builtin_subc:
13579     case Builtin::BI__builtin_subcl:
13580     case Builtin::BI__builtin_subcll:
13581       Result =
13582           LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
13583       break;
13584     }
13585 
13586     // It is possible for both overflows to happen but CGBuiltin uses an OR so
13587     // this is consistent.
13588     CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13589     APValue APV{CarryOut};
13590     if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
13591       return false;
13592     return Success(Result, E);
13593   }
13594   case Builtin::BI__builtin_add_overflow:
13595   case Builtin::BI__builtin_sub_overflow:
13596   case Builtin::BI__builtin_mul_overflow:
13597   case Builtin::BI__builtin_sadd_overflow:
13598   case Builtin::BI__builtin_uadd_overflow:
13599   case Builtin::BI__builtin_uaddl_overflow:
13600   case Builtin::BI__builtin_uaddll_overflow:
13601   case Builtin::BI__builtin_usub_overflow:
13602   case Builtin::BI__builtin_usubl_overflow:
13603   case Builtin::BI__builtin_usubll_overflow:
13604   case Builtin::BI__builtin_umul_overflow:
13605   case Builtin::BI__builtin_umull_overflow:
13606   case Builtin::BI__builtin_umulll_overflow:
13607   case Builtin::BI__builtin_saddl_overflow:
13608   case Builtin::BI__builtin_saddll_overflow:
13609   case Builtin::BI__builtin_ssub_overflow:
13610   case Builtin::BI__builtin_ssubl_overflow:
13611   case Builtin::BI__builtin_ssubll_overflow:
13612   case Builtin::BI__builtin_smul_overflow:
13613   case Builtin::BI__builtin_smull_overflow:
13614   case Builtin::BI__builtin_smulll_overflow: {
13615     LValue ResultLValue;
13616     APSInt LHS, RHS;
13617 
13618     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13619     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13620         !EvaluateInteger(E->getArg(1), RHS, Info) ||
13621         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13622       return false;
13623 
13624     APSInt Result;
13625     bool DidOverflow = false;
13626 
13627     // If the types don't have to match, enlarge all 3 to the largest of them.
13628     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13629         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13630         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13631       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13632                       ResultType->isSignedIntegerOrEnumerationType();
13633       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13634                       ResultType->isSignedIntegerOrEnumerationType();
13635       uint64_t LHSSize = LHS.getBitWidth();
13636       uint64_t RHSSize = RHS.getBitWidth();
13637       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13638       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13639 
13640       // Add an additional bit if the signedness isn't uniformly agreed to. We
13641       // could do this ONLY if there is a signed and an unsigned that both have
13642       // MaxBits, but the code to check that is pretty nasty.  The issue will be
13643       // caught in the shrink-to-result later anyway.
13644       if (IsSigned && !AllSigned)
13645         ++MaxBits;
13646 
13647       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13648       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13649       Result = APSInt(MaxBits, !IsSigned);
13650     }
13651 
13652     // Find largest int.
13653     switch (BuiltinOp) {
13654     default:
13655       llvm_unreachable("Invalid value for BuiltinOp");
13656     case Builtin::BI__builtin_add_overflow:
13657     case Builtin::BI__builtin_sadd_overflow:
13658     case Builtin::BI__builtin_saddl_overflow:
13659     case Builtin::BI__builtin_saddll_overflow:
13660     case Builtin::BI__builtin_uadd_overflow:
13661     case Builtin::BI__builtin_uaddl_overflow:
13662     case Builtin::BI__builtin_uaddll_overflow:
13663       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13664                               : LHS.uadd_ov(RHS, DidOverflow);
13665       break;
13666     case Builtin::BI__builtin_sub_overflow:
13667     case Builtin::BI__builtin_ssub_overflow:
13668     case Builtin::BI__builtin_ssubl_overflow:
13669     case Builtin::BI__builtin_ssubll_overflow:
13670     case Builtin::BI__builtin_usub_overflow:
13671     case Builtin::BI__builtin_usubl_overflow:
13672     case Builtin::BI__builtin_usubll_overflow:
13673       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13674                               : LHS.usub_ov(RHS, DidOverflow);
13675       break;
13676     case Builtin::BI__builtin_mul_overflow:
13677     case Builtin::BI__builtin_smul_overflow:
13678     case Builtin::BI__builtin_smull_overflow:
13679     case Builtin::BI__builtin_smulll_overflow:
13680     case Builtin::BI__builtin_umul_overflow:
13681     case Builtin::BI__builtin_umull_overflow:
13682     case Builtin::BI__builtin_umulll_overflow:
13683       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13684                               : LHS.umul_ov(RHS, DidOverflow);
13685       break;
13686     }
13687 
13688     // In the case where multiple sizes are allowed, truncate and see if
13689     // the values are the same.
13690     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13691         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13692         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13693       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13694       // since it will give us the behavior of a TruncOrSelf in the case where
13695       // its parameter <= its size.  We previously set Result to be at least the
13696       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13697       // will work exactly like TruncOrSelf.
13698       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13699       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13700 
13701       if (!APSInt::isSameValue(Temp, Result))
13702         DidOverflow = true;
13703       Result = Temp;
13704     }
13705 
13706     APValue APV{Result};
13707     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13708       return false;
13709     return Success(DidOverflow, E);
13710   }
13711 
13712   case Builtin::BI__builtin_reduce_add:
13713   case Builtin::BI__builtin_reduce_mul:
13714   case Builtin::BI__builtin_reduce_and:
13715   case Builtin::BI__builtin_reduce_or:
13716   case Builtin::BI__builtin_reduce_xor:
13717   case Builtin::BI__builtin_reduce_min:
13718   case Builtin::BI__builtin_reduce_max: {
13719     APValue Source;
13720     if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13721       return false;
13722 
13723     unsigned SourceLen = Source.getVectorLength();
13724     APSInt Reduced = Source.getVectorElt(0).getInt();
13725     for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
13726       switch (BuiltinOp) {
13727       default:
13728         return false;
13729       case Builtin::BI__builtin_reduce_add: {
13730         if (!CheckedIntArithmetic(
13731                 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13732                 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
13733           return false;
13734         break;
13735       }
13736       case Builtin::BI__builtin_reduce_mul: {
13737         if (!CheckedIntArithmetic(
13738                 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13739                 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
13740           return false;
13741         break;
13742       }
13743       case Builtin::BI__builtin_reduce_and: {
13744         Reduced &= Source.getVectorElt(EltNum).getInt();
13745         break;
13746       }
13747       case Builtin::BI__builtin_reduce_or: {
13748         Reduced |= Source.getVectorElt(EltNum).getInt();
13749         break;
13750       }
13751       case Builtin::BI__builtin_reduce_xor: {
13752         Reduced ^= Source.getVectorElt(EltNum).getInt();
13753         break;
13754       }
13755       case Builtin::BI__builtin_reduce_min: {
13756         Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
13757         break;
13758       }
13759       case Builtin::BI__builtin_reduce_max: {
13760         Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
13761         break;
13762       }
13763       }
13764     }
13765 
13766     return Success(Reduced, E);
13767   }
13768 
13769   case clang::X86::BI__builtin_ia32_addcarryx_u32:
13770   case clang::X86::BI__builtin_ia32_addcarryx_u64:
13771   case clang::X86::BI__builtin_ia32_subborrow_u32:
13772   case clang::X86::BI__builtin_ia32_subborrow_u64: {
13773     LValue ResultLValue;
13774     APSInt CarryIn, LHS, RHS;
13775     QualType ResultType = E->getArg(3)->getType()->getPointeeType();
13776     if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
13777         !EvaluateInteger(E->getArg(1), LHS, Info) ||
13778         !EvaluateInteger(E->getArg(2), RHS, Info) ||
13779         !EvaluatePointer(E->getArg(3), ResultLValue, Info))
13780       return false;
13781 
13782     bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
13783                  BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
13784 
13785     unsigned BitWidth = LHS.getBitWidth();
13786     unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
13787     APInt ExResult =
13788         IsAdd
13789             ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
13790             : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
13791 
13792     APInt Result = ExResult.extractBits(BitWidth, 0);
13793     uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
13794 
13795     APValue APV{APSInt(Result, /*isUnsigned=*/true)};
13796     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13797       return false;
13798     return Success(CarryOut, E);
13799   }
13800 
13801   case clang::X86::BI__builtin_ia32_bextr_u32:
13802   case clang::X86::BI__builtin_ia32_bextr_u64:
13803   case clang::X86::BI__builtin_ia32_bextri_u32:
13804   case clang::X86::BI__builtin_ia32_bextri_u64: {
13805     APSInt Val, Idx;
13806     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13807         !EvaluateInteger(E->getArg(1), Idx, Info))
13808       return false;
13809 
13810     unsigned BitWidth = Val.getBitWidth();
13811     uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
13812     uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
13813     Length = Length > BitWidth ? BitWidth : Length;
13814 
13815     // Handle out of bounds cases.
13816     if (Length == 0 || Shift >= BitWidth)
13817       return Success(0, E);
13818 
13819     uint64_t Result = Val.getZExtValue() >> Shift;
13820     Result &= llvm::maskTrailingOnes<uint64_t>(Length);
13821     return Success(Result, E);
13822   }
13823 
13824   case clang::X86::BI__builtin_ia32_bzhi_si:
13825   case clang::X86::BI__builtin_ia32_bzhi_di: {
13826     APSInt Val, Idx;
13827     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13828         !EvaluateInteger(E->getArg(1), Idx, Info))
13829       return false;
13830 
13831     unsigned BitWidth = Val.getBitWidth();
13832     unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
13833     if (Index < BitWidth)
13834       Val.clearHighBits(BitWidth - Index);
13835     return Success(Val, E);
13836   }
13837 
13838   case clang::X86::BI__builtin_ia32_lzcnt_u16:
13839   case clang::X86::BI__builtin_ia32_lzcnt_u32:
13840   case clang::X86::BI__builtin_ia32_lzcnt_u64: {
13841     APSInt Val;
13842     if (!EvaluateInteger(E->getArg(0), Val, Info))
13843       return false;
13844     return Success(Val.countLeadingZeros(), E);
13845   }
13846 
13847   case clang::X86::BI__builtin_ia32_tzcnt_u16:
13848   case clang::X86::BI__builtin_ia32_tzcnt_u32:
13849   case clang::X86::BI__builtin_ia32_tzcnt_u64: {
13850     APSInt Val;
13851     if (!EvaluateInteger(E->getArg(0), Val, Info))
13852       return false;
13853     return Success(Val.countTrailingZeros(), E);
13854   }
13855 
13856   case clang::X86::BI__builtin_ia32_pdep_si:
13857   case clang::X86::BI__builtin_ia32_pdep_di: {
13858     APSInt Val, Msk;
13859     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13860         !EvaluateInteger(E->getArg(1), Msk, Info))
13861       return false;
13862 
13863     unsigned BitWidth = Val.getBitWidth();
13864     APInt Result = APInt::getZero(BitWidth);
13865     for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13866       if (Msk[I])
13867         Result.setBitVal(I, Val[P++]);
13868     return Success(Result, E);
13869   }
13870 
13871   case clang::X86::BI__builtin_ia32_pext_si:
13872   case clang::X86::BI__builtin_ia32_pext_di: {
13873     APSInt Val, Msk;
13874     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13875         !EvaluateInteger(E->getArg(1), Msk, Info))
13876       return false;
13877 
13878     unsigned BitWidth = Val.getBitWidth();
13879     APInt Result = APInt::getZero(BitWidth);
13880     for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13881       if (Msk[I])
13882         Result.setBitVal(P++, Val[I]);
13883     return Success(Result, E);
13884   }
13885   }
13886 }
13887 
13888 /// Determine whether this is a pointer past the end of the complete
13889 /// object referred to by the lvalue.
13890 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
13891                                             const LValue &LV) {
13892   // A null pointer can be viewed as being "past the end" but we don't
13893   // choose to look at it that way here.
13894   if (!LV.getLValueBase())
13895     return false;
13896 
13897   // If the designator is valid and refers to a subobject, we're not pointing
13898   // past the end.
13899   if (!LV.getLValueDesignator().Invalid &&
13900       !LV.getLValueDesignator().isOnePastTheEnd())
13901     return false;
13902 
13903   // A pointer to an incomplete type might be past-the-end if the type's size is
13904   // zero.  We cannot tell because the type is incomplete.
13905   QualType Ty = getType(LV.getLValueBase());
13906   if (Ty->isIncompleteType())
13907     return true;
13908 
13909   // Can't be past the end of an invalid object.
13910   if (LV.getLValueDesignator().Invalid)
13911     return false;
13912 
13913   // We're a past-the-end pointer if we point to the byte after the object,
13914   // no matter what our type or path is.
13915   auto Size = Ctx.getTypeSizeInChars(Ty);
13916   return LV.getLValueOffset() == Size;
13917 }
13918 
13919 namespace {
13920 
13921 /// Data recursive integer evaluator of certain binary operators.
13922 ///
13923 /// We use a data recursive algorithm for binary operators so that we are able
13924 /// to handle extreme cases of chained binary operators without causing stack
13925 /// overflow.
13926 class DataRecursiveIntBinOpEvaluator {
13927   struct EvalResult {
13928     APValue Val;
13929     bool Failed = false;
13930 
13931     EvalResult() = default;
13932 
13933     void swap(EvalResult &RHS) {
13934       Val.swap(RHS.Val);
13935       Failed = RHS.Failed;
13936       RHS.Failed = false;
13937     }
13938   };
13939 
13940   struct Job {
13941     const Expr *E;
13942     EvalResult LHSResult; // meaningful only for binary operator expression.
13943     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13944 
13945     Job() = default;
13946     Job(Job &&) = default;
13947 
13948     void startSpeculativeEval(EvalInfo &Info) {
13949       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13950     }
13951 
13952   private:
13953     SpeculativeEvaluationRAII SpecEvalRAII;
13954   };
13955 
13956   SmallVector<Job, 16> Queue;
13957 
13958   IntExprEvaluator &IntEval;
13959   EvalInfo &Info;
13960   APValue &FinalResult;
13961 
13962 public:
13963   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13964     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13965 
13966   /// True if \param E is a binary operator that we are going to handle
13967   /// data recursively.
13968   /// We handle binary operators that are comma, logical, or that have operands
13969   /// with integral or enumeration type.
13970   static bool shouldEnqueue(const BinaryOperator *E) {
13971     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13972            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
13973             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13974             E->getRHS()->getType()->isIntegralOrEnumerationType());
13975   }
13976 
13977   bool Traverse(const BinaryOperator *E) {
13978     enqueue(E);
13979     EvalResult PrevResult;
13980     while (!Queue.empty())
13981       process(PrevResult);
13982 
13983     if (PrevResult.Failed) return false;
13984 
13985     FinalResult.swap(PrevResult.Val);
13986     return true;
13987   }
13988 
13989 private:
13990   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13991     return IntEval.Success(Value, E, Result);
13992   }
13993   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13994     return IntEval.Success(Value, E, Result);
13995   }
13996   bool Error(const Expr *E) {
13997     return IntEval.Error(E);
13998   }
13999   bool Error(const Expr *E, diag::kind D) {
14000     return IntEval.Error(E, D);
14001   }
14002 
14003   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
14004     return Info.CCEDiag(E, D);
14005   }
14006 
14007   // Returns true if visiting the RHS is necessary, false otherwise.
14008   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14009                          bool &SuppressRHSDiags);
14010 
14011   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14012                   const BinaryOperator *E, APValue &Result);
14013 
14014   void EvaluateExpr(const Expr *E, EvalResult &Result) {
14015     Result.Failed = !Evaluate(Result.Val, Info, E);
14016     if (Result.Failed)
14017       Result.Val = APValue();
14018   }
14019 
14020   void process(EvalResult &Result);
14021 
14022   void enqueue(const Expr *E) {
14023     E = E->IgnoreParens();
14024     Queue.resize(Queue.size()+1);
14025     Queue.back().E = E;
14026     Queue.back().Kind = Job::AnyExprKind;
14027   }
14028 };
14029 
14030 }
14031 
14032 bool DataRecursiveIntBinOpEvaluator::
14033        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14034                          bool &SuppressRHSDiags) {
14035   if (E->getOpcode() == BO_Comma) {
14036     // Ignore LHS but note if we could not evaluate it.
14037     if (LHSResult.Failed)
14038       return Info.noteSideEffect();
14039     return true;
14040   }
14041 
14042   if (E->isLogicalOp()) {
14043     bool LHSAsBool;
14044     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
14045       // We were able to evaluate the LHS, see if we can get away with not
14046       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
14047       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
14048         Success(LHSAsBool, E, LHSResult.Val);
14049         return false; // Ignore RHS
14050       }
14051     } else {
14052       LHSResult.Failed = true;
14053 
14054       // Since we weren't able to evaluate the left hand side, it
14055       // might have had side effects.
14056       if (!Info.noteSideEffect())
14057         return false;
14058 
14059       // We can't evaluate the LHS; however, sometimes the result
14060       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14061       // Don't ignore RHS and suppress diagnostics from this arm.
14062       SuppressRHSDiags = true;
14063     }
14064 
14065     return true;
14066   }
14067 
14068   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14069          E->getRHS()->getType()->isIntegralOrEnumerationType());
14070 
14071   if (LHSResult.Failed && !Info.noteFailure())
14072     return false; // Ignore RHS;
14073 
14074   return true;
14075 }
14076 
14077 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
14078                                     bool IsSub) {
14079   // Compute the new offset in the appropriate width, wrapping at 64 bits.
14080   // FIXME: When compiling for a 32-bit target, we should use 32-bit
14081   // offsets.
14082   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
14083   CharUnits &Offset = LVal.getLValueOffset();
14084   uint64_t Offset64 = Offset.getQuantity();
14085   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
14086   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
14087                                          : Offset64 + Index64);
14088 }
14089 
14090 bool DataRecursiveIntBinOpEvaluator::
14091        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14092                   const BinaryOperator *E, APValue &Result) {
14093   if (E->getOpcode() == BO_Comma) {
14094     if (RHSResult.Failed)
14095       return false;
14096     Result = RHSResult.Val;
14097     return true;
14098   }
14099 
14100   if (E->isLogicalOp()) {
14101     bool lhsResult, rhsResult;
14102     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
14103     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
14104 
14105     if (LHSIsOK) {
14106       if (RHSIsOK) {
14107         if (E->getOpcode() == BO_LOr)
14108           return Success(lhsResult || rhsResult, E, Result);
14109         else
14110           return Success(lhsResult && rhsResult, E, Result);
14111       }
14112     } else {
14113       if (RHSIsOK) {
14114         // We can't evaluate the LHS; however, sometimes the result
14115         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14116         if (rhsResult == (E->getOpcode() == BO_LOr))
14117           return Success(rhsResult, E, Result);
14118       }
14119     }
14120 
14121     return false;
14122   }
14123 
14124   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14125          E->getRHS()->getType()->isIntegralOrEnumerationType());
14126 
14127   if (LHSResult.Failed || RHSResult.Failed)
14128     return false;
14129 
14130   const APValue &LHSVal = LHSResult.Val;
14131   const APValue &RHSVal = RHSResult.Val;
14132 
14133   // Handle cases like (unsigned long)&a + 4.
14134   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
14135     Result = LHSVal;
14136     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
14137     return true;
14138   }
14139 
14140   // Handle cases like 4 + (unsigned long)&a
14141   if (E->getOpcode() == BO_Add &&
14142       RHSVal.isLValue() && LHSVal.isInt()) {
14143     Result = RHSVal;
14144     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
14145     return true;
14146   }
14147 
14148   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
14149     // Handle (intptr_t)&&A - (intptr_t)&&B.
14150     if (!LHSVal.getLValueOffset().isZero() ||
14151         !RHSVal.getLValueOffset().isZero())
14152       return false;
14153     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
14154     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
14155     if (!LHSExpr || !RHSExpr)
14156       return false;
14157     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14158     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14159     if (!LHSAddrExpr || !RHSAddrExpr)
14160       return false;
14161     // Make sure both labels come from the same function.
14162     if (LHSAddrExpr->getLabel()->getDeclContext() !=
14163         RHSAddrExpr->getLabel()->getDeclContext())
14164       return false;
14165     Result = APValue(LHSAddrExpr, RHSAddrExpr);
14166     return true;
14167   }
14168 
14169   // All the remaining cases expect both operands to be an integer
14170   if (!LHSVal.isInt() || !RHSVal.isInt())
14171     return Error(E);
14172 
14173   // Set up the width and signedness manually, in case it can't be deduced
14174   // from the operation we're performing.
14175   // FIXME: Don't do this in the cases where we can deduce it.
14176   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
14177                E->getType()->isUnsignedIntegerOrEnumerationType());
14178   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
14179                          RHSVal.getInt(), Value))
14180     return false;
14181   return Success(Value, E, Result);
14182 }
14183 
14184 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
14185   Job &job = Queue.back();
14186 
14187   switch (job.Kind) {
14188     case Job::AnyExprKind: {
14189       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
14190         if (shouldEnqueue(Bop)) {
14191           job.Kind = Job::BinOpKind;
14192           enqueue(Bop->getLHS());
14193           return;
14194         }
14195       }
14196 
14197       EvaluateExpr(job.E, Result);
14198       Queue.pop_back();
14199       return;
14200     }
14201 
14202     case Job::BinOpKind: {
14203       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14204       bool SuppressRHSDiags = false;
14205       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
14206         Queue.pop_back();
14207         return;
14208       }
14209       if (SuppressRHSDiags)
14210         job.startSpeculativeEval(Info);
14211       job.LHSResult.swap(Result);
14212       job.Kind = Job::BinOpVisitedLHSKind;
14213       enqueue(Bop->getRHS());
14214       return;
14215     }
14216 
14217     case Job::BinOpVisitedLHSKind: {
14218       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14219       EvalResult RHS;
14220       RHS.swap(Result);
14221       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
14222       Queue.pop_back();
14223       return;
14224     }
14225   }
14226 
14227   llvm_unreachable("Invalid Job::Kind!");
14228 }
14229 
14230 namespace {
14231 enum class CmpResult {
14232   Unequal,
14233   Less,
14234   Equal,
14235   Greater,
14236   Unordered,
14237 };
14238 }
14239 
14240 template <class SuccessCB, class AfterCB>
14241 static bool
14242 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
14243                                  SuccessCB &&Success, AfterCB &&DoAfter) {
14244   assert(!E->isValueDependent());
14245   assert(E->isComparisonOp() && "expected comparison operator");
14246   assert((E->getOpcode() == BO_Cmp ||
14247           E->getType()->isIntegralOrEnumerationType()) &&
14248          "unsupported binary expression evaluation");
14249   auto Error = [&](const Expr *E) {
14250     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14251     return false;
14252   };
14253 
14254   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
14255   bool IsEquality = E->isEqualityOp();
14256 
14257   QualType LHSTy = E->getLHS()->getType();
14258   QualType RHSTy = E->getRHS()->getType();
14259 
14260   if (LHSTy->isIntegralOrEnumerationType() &&
14261       RHSTy->isIntegralOrEnumerationType()) {
14262     APSInt LHS, RHS;
14263     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
14264     if (!LHSOK && !Info.noteFailure())
14265       return false;
14266     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
14267       return false;
14268     if (LHS < RHS)
14269       return Success(CmpResult::Less, E);
14270     if (LHS > RHS)
14271       return Success(CmpResult::Greater, E);
14272     return Success(CmpResult::Equal, E);
14273   }
14274 
14275   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
14276     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
14277     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
14278 
14279     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
14280     if (!LHSOK && !Info.noteFailure())
14281       return false;
14282     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
14283       return false;
14284     if (LHSFX < RHSFX)
14285       return Success(CmpResult::Less, E);
14286     if (LHSFX > RHSFX)
14287       return Success(CmpResult::Greater, E);
14288     return Success(CmpResult::Equal, E);
14289   }
14290 
14291   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
14292     ComplexValue LHS, RHS;
14293     bool LHSOK;
14294     if (E->isAssignmentOp()) {
14295       LValue LV;
14296       EvaluateLValue(E->getLHS(), LV, Info);
14297       LHSOK = false;
14298     } else if (LHSTy->isRealFloatingType()) {
14299       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
14300       if (LHSOK) {
14301         LHS.makeComplexFloat();
14302         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
14303       }
14304     } else {
14305       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
14306     }
14307     if (!LHSOK && !Info.noteFailure())
14308       return false;
14309 
14310     if (E->getRHS()->getType()->isRealFloatingType()) {
14311       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
14312         return false;
14313       RHS.makeComplexFloat();
14314       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
14315     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14316       return false;
14317 
14318     if (LHS.isComplexFloat()) {
14319       APFloat::cmpResult CR_r =
14320         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
14321       APFloat::cmpResult CR_i =
14322         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
14323       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
14324       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14325     } else {
14326       assert(IsEquality && "invalid complex comparison");
14327       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
14328                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
14329       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14330     }
14331   }
14332 
14333   if (LHSTy->isRealFloatingType() &&
14334       RHSTy->isRealFloatingType()) {
14335     APFloat RHS(0.0), LHS(0.0);
14336 
14337     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
14338     if (!LHSOK && !Info.noteFailure())
14339       return false;
14340 
14341     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
14342       return false;
14343 
14344     assert(E->isComparisonOp() && "Invalid binary operator!");
14345     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
14346     if (!Info.InConstantContext &&
14347         APFloatCmpResult == APFloat::cmpUnordered &&
14348         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
14349       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
14350       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
14351       return false;
14352     }
14353     auto GetCmpRes = [&]() {
14354       switch (APFloatCmpResult) {
14355       case APFloat::cmpEqual:
14356         return CmpResult::Equal;
14357       case APFloat::cmpLessThan:
14358         return CmpResult::Less;
14359       case APFloat::cmpGreaterThan:
14360         return CmpResult::Greater;
14361       case APFloat::cmpUnordered:
14362         return CmpResult::Unordered;
14363       }
14364       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
14365     };
14366     return Success(GetCmpRes(), E);
14367   }
14368 
14369   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
14370     LValue LHSValue, RHSValue;
14371 
14372     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14373     if (!LHSOK && !Info.noteFailure())
14374       return false;
14375 
14376     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14377       return false;
14378 
14379     // If we have Unknown pointers we should fail if they are not global values.
14380     if (!(IsGlobalLValue(LHSValue.getLValueBase()) &&
14381           IsGlobalLValue(RHSValue.getLValueBase())) &&
14382         (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
14383       return false;
14384 
14385     // Reject differing bases from the normal codepath; we special-case
14386     // comparisons to null.
14387     if (!HasSameBase(LHSValue, RHSValue)) {
14388       auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
14389         std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14390         std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14391         Info.FFDiag(E, DiagID)
14392             << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
14393         return false;
14394       };
14395       // Inequalities and subtractions between unrelated pointers have
14396       // unspecified or undefined behavior.
14397       if (!IsEquality)
14398         return DiagComparison(
14399             diag::note_constexpr_pointer_comparison_unspecified);
14400       // A constant address may compare equal to the address of a symbol.
14401       // The one exception is that address of an object cannot compare equal
14402       // to a null pointer constant.
14403       // TODO: Should we restrict this to actual null pointers, and exclude the
14404       // case of zero cast to pointer type?
14405       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
14406           (!RHSValue.Base && !RHSValue.Offset.isZero()))
14407         return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
14408                               !RHSValue.Base);
14409       // C++2c [intro.object]/10:
14410       //   Two objects [...] may have the same address if [...] they are both
14411       //   potentially non-unique objects.
14412       // C++2c [intro.object]/9:
14413       //   An object is potentially non-unique if it is a string literal object,
14414       //   the backing array of an initializer list, or a subobject thereof.
14415       //
14416       // This makes the comparison result unspecified, so it's not a constant
14417       // expression.
14418       //
14419       // TODO: Do we need to handle the initializer list case here?
14420       if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14421         return DiagComparison(diag::note_constexpr_literal_comparison);
14422       if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
14423         return DiagComparison(diag::note_constexpr_opaque_call_comparison,
14424                               !IsOpaqueConstantCall(LHSValue));
14425       // We can't tell whether weak symbols will end up pointing to the same
14426       // object.
14427       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
14428         return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
14429                               !IsWeakLValue(LHSValue));
14430       // We can't compare the address of the start of one object with the
14431       // past-the-end address of another object, per C++ DR1652.
14432       if (LHSValue.Base && LHSValue.Offset.isZero() &&
14433           isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
14434         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14435                               true);
14436       if (RHSValue.Base && RHSValue.Offset.isZero() &&
14437            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
14438         return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14439                               false);
14440       // We can't tell whether an object is at the same address as another
14441       // zero sized object.
14442       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
14443           (LHSValue.Base && isZeroSized(RHSValue)))
14444         return DiagComparison(
14445             diag::note_constexpr_pointer_comparison_zero_sized);
14446       return Success(CmpResult::Unequal, E);
14447     }
14448 
14449     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14450     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14451 
14452     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14453     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14454 
14455     // C++11 [expr.rel]p2:
14456     // - If two pointers point to non-static data members of the same object,
14457     //   or to subobjects or array elements fo such members, recursively, the
14458     //   pointer to the later declared member compares greater provided the
14459     //   two members have the same access control and provided their class is
14460     //   not a union.
14461     //   [...]
14462     // - Otherwise pointer comparisons are unspecified.
14463     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
14464       bool WasArrayIndex;
14465       unsigned Mismatch = FindDesignatorMismatch(
14466           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
14467       // At the point where the designators diverge, the comparison has a
14468       // specified value if:
14469       //  - we are comparing array indices
14470       //  - we are comparing fields of a union, or fields with the same access
14471       // Otherwise, the result is unspecified and thus the comparison is not a
14472       // constant expression.
14473       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
14474           Mismatch < RHSDesignator.Entries.size()) {
14475         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
14476         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
14477         if (!LF && !RF)
14478           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
14479         else if (!LF)
14480           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14481               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
14482               << RF->getParent() << RF;
14483         else if (!RF)
14484           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14485               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
14486               << LF->getParent() << LF;
14487         else if (!LF->getParent()->isUnion() &&
14488                  LF->getAccess() != RF->getAccess())
14489           Info.CCEDiag(E,
14490                        diag::note_constexpr_pointer_comparison_differing_access)
14491               << LF << LF->getAccess() << RF << RF->getAccess()
14492               << LF->getParent();
14493       }
14494     }
14495 
14496     // The comparison here must be unsigned, and performed with the same
14497     // width as the pointer.
14498     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
14499     uint64_t CompareLHS = LHSOffset.getQuantity();
14500     uint64_t CompareRHS = RHSOffset.getQuantity();
14501     assert(PtrSize <= 64 && "Unexpected pointer width");
14502     uint64_t Mask = ~0ULL >> (64 - PtrSize);
14503     CompareLHS &= Mask;
14504     CompareRHS &= Mask;
14505 
14506     // If there is a base and this is a relational operator, we can only
14507     // compare pointers within the object in question; otherwise, the result
14508     // depends on where the object is located in memory.
14509     if (!LHSValue.Base.isNull() && IsRelational) {
14510       QualType BaseTy = getType(LHSValue.Base);
14511       if (BaseTy->isIncompleteType())
14512         return Error(E);
14513       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
14514       uint64_t OffsetLimit = Size.getQuantity();
14515       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
14516         return Error(E);
14517     }
14518 
14519     if (CompareLHS < CompareRHS)
14520       return Success(CmpResult::Less, E);
14521     if (CompareLHS > CompareRHS)
14522       return Success(CmpResult::Greater, E);
14523     return Success(CmpResult::Equal, E);
14524   }
14525 
14526   if (LHSTy->isMemberPointerType()) {
14527     assert(IsEquality && "unexpected member pointer operation");
14528     assert(RHSTy->isMemberPointerType() && "invalid comparison");
14529 
14530     MemberPtr LHSValue, RHSValue;
14531 
14532     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
14533     if (!LHSOK && !Info.noteFailure())
14534       return false;
14535 
14536     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14537       return false;
14538 
14539     // If either operand is a pointer to a weak function, the comparison is not
14540     // constant.
14541     if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
14542       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14543           << LHSValue.getDecl();
14544       return false;
14545     }
14546     if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
14547       Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14548           << RHSValue.getDecl();
14549       return false;
14550     }
14551 
14552     // C++11 [expr.eq]p2:
14553     //   If both operands are null, they compare equal. Otherwise if only one is
14554     //   null, they compare unequal.
14555     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
14556       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
14557       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14558     }
14559 
14560     //   Otherwise if either is a pointer to a virtual member function, the
14561     //   result is unspecified.
14562     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
14563       if (MD->isVirtual())
14564         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14565     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
14566       if (MD->isVirtual())
14567         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14568 
14569     //   Otherwise they compare equal if and only if they would refer to the
14570     //   same member of the same most derived object or the same subobject if
14571     //   they were dereferenced with a hypothetical object of the associated
14572     //   class type.
14573     bool Equal = LHSValue == RHSValue;
14574     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14575   }
14576 
14577   if (LHSTy->isNullPtrType()) {
14578     assert(E->isComparisonOp() && "unexpected nullptr operation");
14579     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
14580     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
14581     // are compared, the result is true of the operator is <=, >= or ==, and
14582     // false otherwise.
14583     LValue Res;
14584     if (!EvaluatePointer(E->getLHS(), Res, Info) ||
14585         !EvaluatePointer(E->getRHS(), Res, Info))
14586       return false;
14587     return Success(CmpResult::Equal, E);
14588   }
14589 
14590   return DoAfter();
14591 }
14592 
14593 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
14594   if (!CheckLiteralType(Info, E))
14595     return false;
14596 
14597   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14598     ComparisonCategoryResult CCR;
14599     switch (CR) {
14600     case CmpResult::Unequal:
14601       llvm_unreachable("should never produce Unequal for three-way comparison");
14602     case CmpResult::Less:
14603       CCR = ComparisonCategoryResult::Less;
14604       break;
14605     case CmpResult::Equal:
14606       CCR = ComparisonCategoryResult::Equal;
14607       break;
14608     case CmpResult::Greater:
14609       CCR = ComparisonCategoryResult::Greater;
14610       break;
14611     case CmpResult::Unordered:
14612       CCR = ComparisonCategoryResult::Unordered;
14613       break;
14614     }
14615     // Evaluation succeeded. Lookup the information for the comparison category
14616     // type and fetch the VarDecl for the result.
14617     const ComparisonCategoryInfo &CmpInfo =
14618         Info.Ctx.CompCategories.getInfoForType(E->getType());
14619     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
14620     // Check and evaluate the result as a constant expression.
14621     LValue LV;
14622     LV.set(VD);
14623     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14624       return false;
14625     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14626                                    ConstantExprKind::Normal);
14627   };
14628   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14629     return ExprEvaluatorBaseTy::VisitBinCmp(E);
14630   });
14631 }
14632 
14633 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
14634     const CXXParenListInitExpr *E) {
14635   return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
14636 }
14637 
14638 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14639   // We don't support assignment in C. C++ assignments don't get here because
14640   // assignment is an lvalue in C++.
14641   if (E->isAssignmentOp()) {
14642     Error(E);
14643     if (!Info.noteFailure())
14644       return false;
14645   }
14646 
14647   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
14648     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
14649 
14650   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
14651           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
14652          "DataRecursiveIntBinOpEvaluator should have handled integral types");
14653 
14654   if (E->isComparisonOp()) {
14655     // Evaluate builtin binary comparisons by evaluating them as three-way
14656     // comparisons and then translating the result.
14657     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14658       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
14659              "should only produce Unequal for equality comparisons");
14660       bool IsEqual   = CR == CmpResult::Equal,
14661            IsLess    = CR == CmpResult::Less,
14662            IsGreater = CR == CmpResult::Greater;
14663       auto Op = E->getOpcode();
14664       switch (Op) {
14665       default:
14666         llvm_unreachable("unsupported binary operator");
14667       case BO_EQ:
14668       case BO_NE:
14669         return Success(IsEqual == (Op == BO_EQ), E);
14670       case BO_LT:
14671         return Success(IsLess, E);
14672       case BO_GT:
14673         return Success(IsGreater, E);
14674       case BO_LE:
14675         return Success(IsEqual || IsLess, E);
14676       case BO_GE:
14677         return Success(IsEqual || IsGreater, E);
14678       }
14679     };
14680     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14681       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14682     });
14683   }
14684 
14685   QualType LHSTy = E->getLHS()->getType();
14686   QualType RHSTy = E->getRHS()->getType();
14687 
14688   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
14689       E->getOpcode() == BO_Sub) {
14690     LValue LHSValue, RHSValue;
14691 
14692     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14693     if (!LHSOK && !Info.noteFailure())
14694       return false;
14695 
14696     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14697       return false;
14698 
14699     // Reject differing bases from the normal codepath; we special-case
14700     // comparisons to null.
14701     if (!HasSameBase(LHSValue, RHSValue)) {
14702       // Handle &&A - &&B.
14703       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
14704         return Error(E);
14705       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
14706       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
14707 
14708       auto DiagArith = [&](unsigned DiagID) {
14709         std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14710         std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14711         Info.FFDiag(E, DiagID) << LHS << RHS;
14712         if (LHSExpr && LHSExpr == RHSExpr)
14713           Info.Note(LHSExpr->getExprLoc(),
14714                     diag::note_constexpr_repeated_literal_eval)
14715               << LHSExpr->getSourceRange();
14716         return false;
14717       };
14718 
14719       if (!LHSExpr || !RHSExpr)
14720         return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
14721 
14722       if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14723         return DiagArith(diag::note_constexpr_literal_arith);
14724 
14725       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14726       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14727       if (!LHSAddrExpr || !RHSAddrExpr)
14728         return Error(E);
14729       // Make sure both labels come from the same function.
14730       if (LHSAddrExpr->getLabel()->getDeclContext() !=
14731           RHSAddrExpr->getLabel()->getDeclContext())
14732         return Error(E);
14733       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
14734     }
14735     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14736     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14737 
14738     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14739     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14740 
14741     // C++11 [expr.add]p6:
14742     //   Unless both pointers point to elements of the same array object, or
14743     //   one past the last element of the array object, the behavior is
14744     //   undefined.
14745     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14746         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
14747                                 RHSDesignator))
14748       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
14749 
14750     QualType Type = E->getLHS()->getType();
14751     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14752 
14753     CharUnits ElementSize;
14754     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14755       return false;
14756 
14757     // As an extension, a type may have zero size (empty struct or union in
14758     // C, array of zero length). Pointer subtraction in such cases has
14759     // undefined behavior, so is not constant.
14760     if (ElementSize.isZero()) {
14761       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
14762           << ElementType;
14763       return false;
14764     }
14765 
14766     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14767     // and produce incorrect results when it overflows. Such behavior
14768     // appears to be non-conforming, but is common, so perhaps we should
14769     // assume the standard intended for such cases to be undefined behavior
14770     // and check for them.
14771 
14772     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14773     // overflow in the final conversion to ptrdiff_t.
14774     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14775     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14776     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14777                     false);
14778     APSInt TrueResult = (LHS - RHS) / ElemSize;
14779     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14780 
14781     if (Result.extend(65) != TrueResult &&
14782         !HandleOverflow(Info, E, TrueResult, E->getType()))
14783       return false;
14784     return Success(Result, E);
14785   }
14786 
14787   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14788 }
14789 
14790 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14791 /// a result as the expression's type.
14792 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14793                                     const UnaryExprOrTypeTraitExpr *E) {
14794   switch(E->getKind()) {
14795   case UETT_PreferredAlignOf:
14796   case UETT_AlignOf: {
14797     if (E->isArgumentType())
14798       return Success(
14799           GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
14800     else
14801       return Success(
14802           GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
14803   }
14804 
14805   case UETT_PtrAuthTypeDiscriminator: {
14806     if (E->getArgumentType()->isDependentType())
14807       return false;
14808     return Success(
14809         Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14810   }
14811   case UETT_VecStep: {
14812     QualType Ty = E->getTypeOfArgument();
14813 
14814     if (Ty->isVectorType()) {
14815       unsigned n = Ty->castAs<VectorType>()->getNumElements();
14816 
14817       // The vec_step built-in functions that take a 3-component
14818       // vector return 4. (OpenCL 1.1 spec 6.11.12)
14819       if (n == 3)
14820         n = 4;
14821 
14822       return Success(n, E);
14823     } else
14824       return Success(1, E);
14825   }
14826 
14827   case UETT_DataSizeOf:
14828   case UETT_SizeOf: {
14829     QualType SrcTy = E->getTypeOfArgument();
14830     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14831     //   the result is the size of the referenced type."
14832     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14833       SrcTy = Ref->getPointeeType();
14834 
14835     CharUnits Sizeof;
14836     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14837                       E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14838                                                       : SizeOfType::SizeOf)) {
14839       return false;
14840     }
14841     return Success(Sizeof, E);
14842   }
14843   case UETT_OpenMPRequiredSimdAlign:
14844     assert(E->isArgumentType());
14845     return Success(
14846         Info.Ctx.toCharUnitsFromBits(
14847                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14848             .getQuantity(),
14849         E);
14850   case UETT_VectorElements: {
14851     QualType Ty = E->getTypeOfArgument();
14852     // If the vector has a fixed size, we can determine the number of elements
14853     // at compile time.
14854     if (const auto *VT = Ty->getAs<VectorType>())
14855       return Success(VT->getNumElements(), E);
14856 
14857     assert(Ty->isSizelessVectorType());
14858     if (Info.InConstantContext)
14859       Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14860           << E->getSourceRange();
14861 
14862     return false;
14863   }
14864   }
14865 
14866   llvm_unreachable("unknown expr/type trait");
14867 }
14868 
14869 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14870   CharUnits Result;
14871   unsigned n = OOE->getNumComponents();
14872   if (n == 0)
14873     return Error(OOE);
14874   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14875   for (unsigned i = 0; i != n; ++i) {
14876     OffsetOfNode ON = OOE->getComponent(i);
14877     switch (ON.getKind()) {
14878     case OffsetOfNode::Array: {
14879       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14880       APSInt IdxResult;
14881       if (!EvaluateInteger(Idx, IdxResult, Info))
14882         return false;
14883       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
14884       if (!AT)
14885         return Error(OOE);
14886       CurrentType = AT->getElementType();
14887       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
14888       Result += IdxResult.getSExtValue() * ElementSize;
14889       break;
14890     }
14891 
14892     case OffsetOfNode::Field: {
14893       FieldDecl *MemberDecl = ON.getField();
14894       const RecordType *RT = CurrentType->getAs<RecordType>();
14895       if (!RT)
14896         return Error(OOE);
14897       RecordDecl *RD = RT->getDecl();
14898       if (RD->isInvalidDecl()) return false;
14899       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14900       unsigned i = MemberDecl->getFieldIndex();
14901       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14902       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
14903       CurrentType = MemberDecl->getType().getNonReferenceType();
14904       break;
14905     }
14906 
14907     case OffsetOfNode::Identifier:
14908       llvm_unreachable("dependent __builtin_offsetof");
14909 
14910     case OffsetOfNode::Base: {
14911       CXXBaseSpecifier *BaseSpec = ON.getBase();
14912       if (BaseSpec->isVirtual())
14913         return Error(OOE);
14914 
14915       // Find the layout of the class whose base we are looking into.
14916       const RecordType *RT = CurrentType->getAs<RecordType>();
14917       if (!RT)
14918         return Error(OOE);
14919       RecordDecl *RD = RT->getDecl();
14920       if (RD->isInvalidDecl()) return false;
14921       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14922 
14923       // Find the base class itself.
14924       CurrentType = BaseSpec->getType();
14925       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14926       if (!BaseRT)
14927         return Error(OOE);
14928 
14929       // Add the offset to the base.
14930       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14931       break;
14932     }
14933     }
14934   }
14935   return Success(Result, OOE);
14936 }
14937 
14938 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14939   switch (E->getOpcode()) {
14940   default:
14941     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14942     // See C99 6.6p3.
14943     return Error(E);
14944   case UO_Extension:
14945     // FIXME: Should extension allow i-c-e extension expressions in its scope?
14946     // If so, we could clear the diagnostic ID.
14947     return Visit(E->getSubExpr());
14948   case UO_Plus:
14949     // The result is just the value.
14950     return Visit(E->getSubExpr());
14951   case UO_Minus: {
14952     if (!Visit(E->getSubExpr()))
14953       return false;
14954     if (!Result.isInt()) return Error(E);
14955     const APSInt &Value = Result.getInt();
14956     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14957       if (Info.checkingForUndefinedBehavior())
14958         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14959                                          diag::warn_integer_constant_overflow)
14960             << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
14961                         /*UpperCase=*/true, /*InsertSeparators=*/true)
14962             << E->getType() << E->getSourceRange();
14963 
14964       if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14965                           E->getType()))
14966         return false;
14967     }
14968     return Success(-Value, E);
14969   }
14970   case UO_Not: {
14971     if (!Visit(E->getSubExpr()))
14972       return false;
14973     if (!Result.isInt()) return Error(E);
14974     return Success(~Result.getInt(), E);
14975   }
14976   case UO_LNot: {
14977     bool bres;
14978     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14979       return false;
14980     return Success(!bres, E);
14981   }
14982   }
14983 }
14984 
14985 /// HandleCast - This is used to evaluate implicit or explicit casts where the
14986 /// result type is integer.
14987 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14988   const Expr *SubExpr = E->getSubExpr();
14989   QualType DestType = E->getType();
14990   QualType SrcType = SubExpr->getType();
14991 
14992   switch (E->getCastKind()) {
14993   case CK_BaseToDerived:
14994   case CK_DerivedToBase:
14995   case CK_UncheckedDerivedToBase:
14996   case CK_Dynamic:
14997   case CK_ToUnion:
14998   case CK_ArrayToPointerDecay:
14999   case CK_FunctionToPointerDecay:
15000   case CK_NullToPointer:
15001   case CK_NullToMemberPointer:
15002   case CK_BaseToDerivedMemberPointer:
15003   case CK_DerivedToBaseMemberPointer:
15004   case CK_ReinterpretMemberPointer:
15005   case CK_ConstructorConversion:
15006   case CK_IntegralToPointer:
15007   case CK_ToVoid:
15008   case CK_VectorSplat:
15009   case CK_IntegralToFloating:
15010   case CK_FloatingCast:
15011   case CK_CPointerToObjCPointerCast:
15012   case CK_BlockPointerToObjCPointerCast:
15013   case CK_AnyPointerToBlockPointerCast:
15014   case CK_ObjCObjectLValueCast:
15015   case CK_FloatingRealToComplex:
15016   case CK_FloatingComplexToReal:
15017   case CK_FloatingComplexCast:
15018   case CK_FloatingComplexToIntegralComplex:
15019   case CK_IntegralRealToComplex:
15020   case CK_IntegralComplexCast:
15021   case CK_IntegralComplexToFloatingComplex:
15022   case CK_BuiltinFnToFnPtr:
15023   case CK_ZeroToOCLOpaqueType:
15024   case CK_NonAtomicToAtomic:
15025   case CK_AddressSpaceConversion:
15026   case CK_IntToOCLSampler:
15027   case CK_FloatingToFixedPoint:
15028   case CK_FixedPointToFloating:
15029   case CK_FixedPointCast:
15030   case CK_IntegralToFixedPoint:
15031   case CK_MatrixCast:
15032     llvm_unreachable("invalid cast kind for integral value");
15033 
15034   case CK_BitCast:
15035   case CK_Dependent:
15036   case CK_LValueBitCast:
15037   case CK_ARCProduceObject:
15038   case CK_ARCConsumeObject:
15039   case CK_ARCReclaimReturnedObject:
15040   case CK_ARCExtendBlockObject:
15041   case CK_CopyAndAutoreleaseBlockObject:
15042     return Error(E);
15043 
15044   case CK_UserDefinedConversion:
15045   case CK_LValueToRValue:
15046   case CK_AtomicToNonAtomic:
15047   case CK_NoOp:
15048   case CK_LValueToRValueBitCast:
15049   case CK_HLSLArrayRValue:
15050     return ExprEvaluatorBaseTy::VisitCastExpr(E);
15051 
15052   case CK_MemberPointerToBoolean:
15053   case CK_PointerToBoolean:
15054   case CK_IntegralToBoolean:
15055   case CK_FloatingToBoolean:
15056   case CK_BooleanToSignedIntegral:
15057   case CK_FloatingComplexToBoolean:
15058   case CK_IntegralComplexToBoolean: {
15059     bool BoolResult;
15060     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
15061       return false;
15062     uint64_t IntResult = BoolResult;
15063     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
15064       IntResult = (uint64_t)-1;
15065     return Success(IntResult, E);
15066   }
15067 
15068   case CK_FixedPointToIntegral: {
15069     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
15070     if (!EvaluateFixedPoint(SubExpr, Src, Info))
15071       return false;
15072     bool Overflowed;
15073     llvm::APSInt Result = Src.convertToInt(
15074         Info.Ctx.getIntWidth(DestType),
15075         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
15076     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
15077       return false;
15078     return Success(Result, E);
15079   }
15080 
15081   case CK_FixedPointToBoolean: {
15082     // Unsigned padding does not affect this.
15083     APValue Val;
15084     if (!Evaluate(Val, Info, SubExpr))
15085       return false;
15086     return Success(Val.getFixedPoint().getBoolValue(), E);
15087   }
15088 
15089   case CK_IntegralCast: {
15090     if (!Visit(SubExpr))
15091       return false;
15092 
15093     if (!Result.isInt()) {
15094       // Allow casts of address-of-label differences if they are no-ops
15095       // or narrowing.  (The narrowing case isn't actually guaranteed to
15096       // be constant-evaluatable except in some narrow cases which are hard
15097       // to detect here.  We let it through on the assumption the user knows
15098       // what they are doing.)
15099       if (Result.isAddrLabelDiff())
15100         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
15101       // Only allow casts of lvalues if they are lossless.
15102       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
15103     }
15104 
15105     if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
15106         Info.EvalMode == EvalInfo::EM_ConstantExpression &&
15107         DestType->isEnumeralType()) {
15108 
15109       bool ConstexprVar = true;
15110 
15111       // We know if we are here that we are in a context that we might require
15112       // a constant expression or a context that requires a constant
15113       // value. But if we are initializing a value we don't know if it is a
15114       // constexpr variable or not. We can check the EvaluatingDecl to determine
15115       // if it constexpr or not. If not then we don't want to emit a diagnostic.
15116       if (const auto *VD = dyn_cast_or_null<VarDecl>(
15117               Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
15118         ConstexprVar = VD->isConstexpr();
15119 
15120       const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
15121       const EnumDecl *ED = ET->getDecl();
15122       // Check that the value is within the range of the enumeration values.
15123       //
15124       // This corressponds to [expr.static.cast]p10 which says:
15125       // A value of integral or enumeration type can be explicitly converted
15126       // to a complete enumeration type ... If the enumeration type does not
15127       // have a fixed underlying type, the value is unchanged if the original
15128       // value is within the range of the enumeration values ([dcl.enum]), and
15129       // otherwise, the behavior is undefined.
15130       //
15131       // This was resolved as part of DR2338 which has CD5 status.
15132       if (!ED->isFixed()) {
15133         llvm::APInt Min;
15134         llvm::APInt Max;
15135 
15136         ED->getValueRange(Max, Min);
15137         --Max;
15138 
15139         if (ED->getNumNegativeBits() && ConstexprVar &&
15140             (Max.slt(Result.getInt().getSExtValue()) ||
15141              Min.sgt(Result.getInt().getSExtValue())))
15142           Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15143               << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
15144               << Max.getSExtValue() << ED;
15145         else if (!ED->getNumNegativeBits() && ConstexprVar &&
15146                  Max.ult(Result.getInt().getZExtValue()))
15147           Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15148               << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
15149               << Max.getZExtValue() << ED;
15150       }
15151     }
15152 
15153     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
15154                                       Result.getInt()), E);
15155   }
15156 
15157   case CK_PointerToIntegral: {
15158     CCEDiag(E, diag::note_constexpr_invalid_cast)
15159         << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
15160 
15161     LValue LV;
15162     if (!EvaluatePointer(SubExpr, LV, Info))
15163       return false;
15164 
15165     if (LV.getLValueBase()) {
15166       // Only allow based lvalue casts if they are lossless.
15167       // FIXME: Allow a larger integer size than the pointer size, and allow
15168       // narrowing back down to pointer width in subsequent integral casts.
15169       // FIXME: Check integer type's active bits, not its type size.
15170       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
15171         return Error(E);
15172 
15173       LV.Designator.setInvalid();
15174       LV.moveInto(Result);
15175       return true;
15176     }
15177 
15178     APSInt AsInt;
15179     APValue V;
15180     LV.moveInto(V);
15181     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
15182       llvm_unreachable("Can't cast this!");
15183 
15184     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
15185   }
15186 
15187   case CK_IntegralComplexToReal: {
15188     ComplexValue C;
15189     if (!EvaluateComplex(SubExpr, C, Info))
15190       return false;
15191     return Success(C.getComplexIntReal(), E);
15192   }
15193 
15194   case CK_FloatingToIntegral: {
15195     APFloat F(0.0);
15196     if (!EvaluateFloat(SubExpr, F, Info))
15197       return false;
15198 
15199     APSInt Value;
15200     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
15201       return false;
15202     return Success(Value, E);
15203   }
15204   case CK_HLSLVectorTruncation: {
15205     APValue Val;
15206     if (!EvaluateVector(SubExpr, Val, Info))
15207       return Error(E);
15208     return Success(Val.getVectorElt(0), E);
15209   }
15210   }
15211 
15212   llvm_unreachable("unknown cast resulting in integral value");
15213 }
15214 
15215 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15216   if (E->getSubExpr()->getType()->isAnyComplexType()) {
15217     ComplexValue LV;
15218     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15219       return false;
15220     if (!LV.isComplexInt())
15221       return Error(E);
15222     return Success(LV.getComplexIntReal(), E);
15223   }
15224 
15225   return Visit(E->getSubExpr());
15226 }
15227 
15228 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15229   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
15230     ComplexValue LV;
15231     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15232       return false;
15233     if (!LV.isComplexInt())
15234       return Error(E);
15235     return Success(LV.getComplexIntImag(), E);
15236   }
15237 
15238   VisitIgnoredValue(E->getSubExpr());
15239   return Success(0, E);
15240 }
15241 
15242 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
15243   return Success(E->getPackLength(), E);
15244 }
15245 
15246 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
15247   return Success(E->getValue(), E);
15248 }
15249 
15250 bool IntExprEvaluator::VisitConceptSpecializationExpr(
15251        const ConceptSpecializationExpr *E) {
15252   return Success(E->isSatisfied(), E);
15253 }
15254 
15255 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
15256   return Success(E->isSatisfied(), E);
15257 }
15258 
15259 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15260   switch (E->getOpcode()) {
15261     default:
15262       // Invalid unary operators
15263       return Error(E);
15264     case UO_Plus:
15265       // The result is just the value.
15266       return Visit(E->getSubExpr());
15267     case UO_Minus: {
15268       if (!Visit(E->getSubExpr())) return false;
15269       if (!Result.isFixedPoint())
15270         return Error(E);
15271       bool Overflowed;
15272       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
15273       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
15274         return false;
15275       return Success(Negated, E);
15276     }
15277     case UO_LNot: {
15278       bool bres;
15279       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15280         return false;
15281       return Success(!bres, E);
15282     }
15283   }
15284 }
15285 
15286 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
15287   const Expr *SubExpr = E->getSubExpr();
15288   QualType DestType = E->getType();
15289   assert(DestType->isFixedPointType() &&
15290          "Expected destination type to be a fixed point type");
15291   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
15292 
15293   switch (E->getCastKind()) {
15294   case CK_FixedPointCast: {
15295     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15296     if (!EvaluateFixedPoint(SubExpr, Src, Info))
15297       return false;
15298     bool Overflowed;
15299     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
15300     if (Overflowed) {
15301       if (Info.checkingForUndefinedBehavior())
15302         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15303                                          diag::warn_fixedpoint_constant_overflow)
15304           << Result.toString() << E->getType();
15305       if (!HandleOverflow(Info, E, Result, E->getType()))
15306         return false;
15307     }
15308     return Success(Result, E);
15309   }
15310   case CK_IntegralToFixedPoint: {
15311     APSInt Src;
15312     if (!EvaluateInteger(SubExpr, Src, Info))
15313       return false;
15314 
15315     bool Overflowed;
15316     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
15317         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15318 
15319     if (Overflowed) {
15320       if (Info.checkingForUndefinedBehavior())
15321         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15322                                          diag::warn_fixedpoint_constant_overflow)
15323           << IntResult.toString() << E->getType();
15324       if (!HandleOverflow(Info, E, IntResult, E->getType()))
15325         return false;
15326     }
15327 
15328     return Success(IntResult, E);
15329   }
15330   case CK_FloatingToFixedPoint: {
15331     APFloat Src(0.0);
15332     if (!EvaluateFloat(SubExpr, Src, Info))
15333       return false;
15334 
15335     bool Overflowed;
15336     APFixedPoint Result = APFixedPoint::getFromFloatValue(
15337         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15338 
15339     if (Overflowed) {
15340       if (Info.checkingForUndefinedBehavior())
15341         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15342                                          diag::warn_fixedpoint_constant_overflow)
15343           << Result.toString() << E->getType();
15344       if (!HandleOverflow(Info, E, Result, E->getType()))
15345         return false;
15346     }
15347 
15348     return Success(Result, E);
15349   }
15350   case CK_NoOp:
15351   case CK_LValueToRValue:
15352     return ExprEvaluatorBaseTy::VisitCastExpr(E);
15353   default:
15354     return Error(E);
15355   }
15356 }
15357 
15358 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15359   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15360     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15361 
15362   const Expr *LHS = E->getLHS();
15363   const Expr *RHS = E->getRHS();
15364   FixedPointSemantics ResultFXSema =
15365       Info.Ctx.getFixedPointSemantics(E->getType());
15366 
15367   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
15368   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
15369     return false;
15370   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
15371   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
15372     return false;
15373 
15374   bool OpOverflow = false, ConversionOverflow = false;
15375   APFixedPoint Result(LHSFX.getSemantics());
15376   switch (E->getOpcode()) {
15377   case BO_Add: {
15378     Result = LHSFX.add(RHSFX, &OpOverflow)
15379                   .convert(ResultFXSema, &ConversionOverflow);
15380     break;
15381   }
15382   case BO_Sub: {
15383     Result = LHSFX.sub(RHSFX, &OpOverflow)
15384                   .convert(ResultFXSema, &ConversionOverflow);
15385     break;
15386   }
15387   case BO_Mul: {
15388     Result = LHSFX.mul(RHSFX, &OpOverflow)
15389                   .convert(ResultFXSema, &ConversionOverflow);
15390     break;
15391   }
15392   case BO_Div: {
15393     if (RHSFX.getValue() == 0) {
15394       Info.FFDiag(E, diag::note_expr_divide_by_zero);
15395       return false;
15396     }
15397     Result = LHSFX.div(RHSFX, &OpOverflow)
15398                   .convert(ResultFXSema, &ConversionOverflow);
15399     break;
15400   }
15401   case BO_Shl:
15402   case BO_Shr: {
15403     FixedPointSemantics LHSSema = LHSFX.getSemantics();
15404     llvm::APSInt RHSVal = RHSFX.getValue();
15405 
15406     unsigned ShiftBW =
15407         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
15408     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
15409     // Embedded-C 4.1.6.2.2:
15410     //   The right operand must be nonnegative and less than the total number
15411     //   of (nonpadding) bits of the fixed-point operand ...
15412     if (RHSVal.isNegative())
15413       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
15414     else if (Amt != RHSVal)
15415       Info.CCEDiag(E, diag::note_constexpr_large_shift)
15416           << RHSVal << E->getType() << ShiftBW;
15417 
15418     if (E->getOpcode() == BO_Shl)
15419       Result = LHSFX.shl(Amt, &OpOverflow);
15420     else
15421       Result = LHSFX.shr(Amt, &OpOverflow);
15422     break;
15423   }
15424   default:
15425     return false;
15426   }
15427   if (OpOverflow || ConversionOverflow) {
15428     if (Info.checkingForUndefinedBehavior())
15429       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15430                                        diag::warn_fixedpoint_constant_overflow)
15431         << Result.toString() << E->getType();
15432     if (!HandleOverflow(Info, E, Result, E->getType()))
15433       return false;
15434   }
15435   return Success(Result, E);
15436 }
15437 
15438 //===----------------------------------------------------------------------===//
15439 // Float Evaluation
15440 //===----------------------------------------------------------------------===//
15441 
15442 namespace {
15443 class FloatExprEvaluator
15444   : public ExprEvaluatorBase<FloatExprEvaluator> {
15445   APFloat &Result;
15446 public:
15447   FloatExprEvaluator(EvalInfo &info, APFloat &result)
15448     : ExprEvaluatorBaseTy(info), Result(result) {}
15449 
15450   bool Success(const APValue &V, const Expr *e) {
15451     Result = V.getFloat();
15452     return true;
15453   }
15454 
15455   bool ZeroInitialization(const Expr *E) {
15456     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
15457     return true;
15458   }
15459 
15460   bool VisitCallExpr(const CallExpr *E);
15461 
15462   bool VisitUnaryOperator(const UnaryOperator *E);
15463   bool VisitBinaryOperator(const BinaryOperator *E);
15464   bool VisitFloatingLiteral(const FloatingLiteral *E);
15465   bool VisitCastExpr(const CastExpr *E);
15466 
15467   bool VisitUnaryReal(const UnaryOperator *E);
15468   bool VisitUnaryImag(const UnaryOperator *E);
15469 
15470   // FIXME: Missing: array subscript of vector, member of vector
15471 };
15472 } // end anonymous namespace
15473 
15474 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
15475   assert(!E->isValueDependent());
15476   assert(E->isPRValue() && E->getType()->isRealFloatingType());
15477   return FloatExprEvaluator(Info, Result).Visit(E);
15478 }
15479 
15480 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
15481                                   QualType ResultTy,
15482                                   const Expr *Arg,
15483                                   bool SNaN,
15484                                   llvm::APFloat &Result) {
15485   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
15486   if (!S) return false;
15487 
15488   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
15489 
15490   llvm::APInt fill;
15491 
15492   // Treat empty strings as if they were zero.
15493   if (S->getString().empty())
15494     fill = llvm::APInt(32, 0);
15495   else if (S->getString().getAsInteger(0, fill))
15496     return false;
15497 
15498   if (Context.getTargetInfo().isNan2008()) {
15499     if (SNaN)
15500       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15501     else
15502       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15503   } else {
15504     // Prior to IEEE 754-2008, architectures were allowed to choose whether
15505     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
15506     // a different encoding to what became a standard in 2008, and for pre-
15507     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
15508     // sNaN. This is now known as "legacy NaN" encoding.
15509     if (SNaN)
15510       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15511     else
15512       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15513   }
15514 
15515   return true;
15516 }
15517 
15518 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
15519   if (!IsConstantEvaluatedBuiltinCall(E))
15520     return ExprEvaluatorBaseTy::VisitCallExpr(E);
15521 
15522   switch (E->getBuiltinCallee()) {
15523   default:
15524     return false;
15525 
15526   case Builtin::BI__builtin_huge_val:
15527   case Builtin::BI__builtin_huge_valf:
15528   case Builtin::BI__builtin_huge_vall:
15529   case Builtin::BI__builtin_huge_valf16:
15530   case Builtin::BI__builtin_huge_valf128:
15531   case Builtin::BI__builtin_inf:
15532   case Builtin::BI__builtin_inff:
15533   case Builtin::BI__builtin_infl:
15534   case Builtin::BI__builtin_inff16:
15535   case Builtin::BI__builtin_inff128: {
15536     const llvm::fltSemantics &Sem =
15537       Info.Ctx.getFloatTypeSemantics(E->getType());
15538     Result = llvm::APFloat::getInf(Sem);
15539     return true;
15540   }
15541 
15542   case Builtin::BI__builtin_nans:
15543   case Builtin::BI__builtin_nansf:
15544   case Builtin::BI__builtin_nansl:
15545   case Builtin::BI__builtin_nansf16:
15546   case Builtin::BI__builtin_nansf128:
15547     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15548                                true, Result))
15549       return Error(E);
15550     return true;
15551 
15552   case Builtin::BI__builtin_nan:
15553   case Builtin::BI__builtin_nanf:
15554   case Builtin::BI__builtin_nanl:
15555   case Builtin::BI__builtin_nanf16:
15556   case Builtin::BI__builtin_nanf128:
15557     // If this is __builtin_nan() turn this into a nan, otherwise we
15558     // can't constant fold it.
15559     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15560                                false, Result))
15561       return Error(E);
15562     return true;
15563 
15564   case Builtin::BI__builtin_fabs:
15565   case Builtin::BI__builtin_fabsf:
15566   case Builtin::BI__builtin_fabsl:
15567   case Builtin::BI__builtin_fabsf128:
15568     // The C standard says "fabs raises no floating-point exceptions,
15569     // even if x is a signaling NaN. The returned value is independent of
15570     // the current rounding direction mode."  Therefore constant folding can
15571     // proceed without regard to the floating point settings.
15572     // Reference, WG14 N2478 F.10.4.3
15573     if (!EvaluateFloat(E->getArg(0), Result, Info))
15574       return false;
15575 
15576     if (Result.isNegative())
15577       Result.changeSign();
15578     return true;
15579 
15580   case Builtin::BI__arithmetic_fence:
15581     return EvaluateFloat(E->getArg(0), Result, Info);
15582 
15583   // FIXME: Builtin::BI__builtin_powi
15584   // FIXME: Builtin::BI__builtin_powif
15585   // FIXME: Builtin::BI__builtin_powil
15586 
15587   case Builtin::BI__builtin_copysign:
15588   case Builtin::BI__builtin_copysignf:
15589   case Builtin::BI__builtin_copysignl:
15590   case Builtin::BI__builtin_copysignf128: {
15591     APFloat RHS(0.);
15592     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15593         !EvaluateFloat(E->getArg(1), RHS, Info))
15594       return false;
15595     Result.copySign(RHS);
15596     return true;
15597   }
15598 
15599   case Builtin::BI__builtin_fmax:
15600   case Builtin::BI__builtin_fmaxf:
15601   case Builtin::BI__builtin_fmaxl:
15602   case Builtin::BI__builtin_fmaxf16:
15603   case Builtin::BI__builtin_fmaxf128: {
15604     // TODO: Handle sNaN.
15605     APFloat RHS(0.);
15606     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15607         !EvaluateFloat(E->getArg(1), RHS, Info))
15608       return false;
15609     // When comparing zeroes, return +0.0 if one of the zeroes is positive.
15610     if (Result.isZero() && RHS.isZero() && Result.isNegative())
15611       Result = RHS;
15612     else if (Result.isNaN() || RHS > Result)
15613       Result = RHS;
15614     return true;
15615   }
15616 
15617   case Builtin::BI__builtin_fmin:
15618   case Builtin::BI__builtin_fminf:
15619   case Builtin::BI__builtin_fminl:
15620   case Builtin::BI__builtin_fminf16:
15621   case Builtin::BI__builtin_fminf128: {
15622     // TODO: Handle sNaN.
15623     APFloat RHS(0.);
15624     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15625         !EvaluateFloat(E->getArg(1), RHS, Info))
15626       return false;
15627     // When comparing zeroes, return -0.0 if one of the zeroes is negative.
15628     if (Result.isZero() && RHS.isZero() && RHS.isNegative())
15629       Result = RHS;
15630     else if (Result.isNaN() || RHS < Result)
15631       Result = RHS;
15632     return true;
15633   }
15634 
15635   case Builtin::BI__builtin_fmaximum_num:
15636   case Builtin::BI__builtin_fmaximum_numf:
15637   case Builtin::BI__builtin_fmaximum_numl:
15638   case Builtin::BI__builtin_fmaximum_numf16:
15639   case Builtin::BI__builtin_fmaximum_numf128: {
15640     APFloat RHS(0.);
15641     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15642         !EvaluateFloat(E->getArg(1), RHS, Info))
15643       return false;
15644     Result = maximumnum(Result, RHS);
15645     return true;
15646   }
15647 
15648   case Builtin::BI__builtin_fminimum_num:
15649   case Builtin::BI__builtin_fminimum_numf:
15650   case Builtin::BI__builtin_fminimum_numl:
15651   case Builtin::BI__builtin_fminimum_numf16:
15652   case Builtin::BI__builtin_fminimum_numf128: {
15653     APFloat RHS(0.);
15654     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15655         !EvaluateFloat(E->getArg(1), RHS, Info))
15656       return false;
15657     Result = minimumnum(Result, RHS);
15658     return true;
15659   }
15660   }
15661 }
15662 
15663 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15664   if (E->getSubExpr()->getType()->isAnyComplexType()) {
15665     ComplexValue CV;
15666     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15667       return false;
15668     Result = CV.FloatReal;
15669     return true;
15670   }
15671 
15672   return Visit(E->getSubExpr());
15673 }
15674 
15675 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15676   if (E->getSubExpr()->getType()->isAnyComplexType()) {
15677     ComplexValue CV;
15678     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15679       return false;
15680     Result = CV.FloatImag;
15681     return true;
15682   }
15683 
15684   VisitIgnoredValue(E->getSubExpr());
15685   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
15686   Result = llvm::APFloat::getZero(Sem);
15687   return true;
15688 }
15689 
15690 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15691   switch (E->getOpcode()) {
15692   default: return Error(E);
15693   case UO_Plus:
15694     return EvaluateFloat(E->getSubExpr(), Result, Info);
15695   case UO_Minus:
15696     // In C standard, WG14 N2478 F.3 p4
15697     // "the unary - raises no floating point exceptions,
15698     // even if the operand is signalling."
15699     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
15700       return false;
15701     Result.changeSign();
15702     return true;
15703   }
15704 }
15705 
15706 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15707   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15708     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15709 
15710   APFloat RHS(0.0);
15711   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
15712   if (!LHSOK && !Info.noteFailure())
15713     return false;
15714   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
15715          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
15716 }
15717 
15718 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
15719   Result = E->getValue();
15720   return true;
15721 }
15722 
15723 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
15724   const Expr* SubExpr = E->getSubExpr();
15725 
15726   switch (E->getCastKind()) {
15727   default:
15728     return ExprEvaluatorBaseTy::VisitCastExpr(E);
15729 
15730   case CK_IntegralToFloating: {
15731     APSInt IntResult;
15732     const FPOptions FPO = E->getFPFeaturesInEffect(
15733                                   Info.Ctx.getLangOpts());
15734     return EvaluateInteger(SubExpr, IntResult, Info) &&
15735            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
15736                                 IntResult, E->getType(), Result);
15737   }
15738 
15739   case CK_FixedPointToFloating: {
15740     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15741     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
15742       return false;
15743     Result =
15744         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
15745     return true;
15746   }
15747 
15748   case CK_FloatingCast: {
15749     if (!Visit(SubExpr))
15750       return false;
15751     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
15752                                   Result);
15753   }
15754 
15755   case CK_FloatingComplexToReal: {
15756     ComplexValue V;
15757     if (!EvaluateComplex(SubExpr, V, Info))
15758       return false;
15759     Result = V.getComplexFloatReal();
15760     return true;
15761   }
15762   case CK_HLSLVectorTruncation: {
15763     APValue Val;
15764     if (!EvaluateVector(SubExpr, Val, Info))
15765       return Error(E);
15766     return Success(Val.getVectorElt(0), E);
15767   }
15768   }
15769 }
15770 
15771 //===----------------------------------------------------------------------===//
15772 // Complex Evaluation (for float and integer)
15773 //===----------------------------------------------------------------------===//
15774 
15775 namespace {
15776 class ComplexExprEvaluator
15777   : public ExprEvaluatorBase<ComplexExprEvaluator> {
15778   ComplexValue &Result;
15779 
15780 public:
15781   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15782     : ExprEvaluatorBaseTy(info), Result(Result) {}
15783 
15784   bool Success(const APValue &V, const Expr *e) {
15785     Result.setFrom(V);
15786     return true;
15787   }
15788 
15789   bool ZeroInitialization(const Expr *E);
15790 
15791   //===--------------------------------------------------------------------===//
15792   //                            Visitor Methods
15793   //===--------------------------------------------------------------------===//
15794 
15795   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15796   bool VisitCastExpr(const CastExpr *E);
15797   bool VisitBinaryOperator(const BinaryOperator *E);
15798   bool VisitUnaryOperator(const UnaryOperator *E);
15799   bool VisitInitListExpr(const InitListExpr *E);
15800   bool VisitCallExpr(const CallExpr *E);
15801 };
15802 } // end anonymous namespace
15803 
15804 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15805                             EvalInfo &Info) {
15806   assert(!E->isValueDependent());
15807   assert(E->isPRValue() && E->getType()->isAnyComplexType());
15808   return ComplexExprEvaluator(Info, Result).Visit(E);
15809 }
15810 
15811 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15812   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15813   if (ElemTy->isRealFloatingType()) {
15814     Result.makeComplexFloat();
15815     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
15816     Result.FloatReal = Zero;
15817     Result.FloatImag = Zero;
15818   } else {
15819     Result.makeComplexInt();
15820     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
15821     Result.IntReal = Zero;
15822     Result.IntImag = Zero;
15823   }
15824   return true;
15825 }
15826 
15827 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15828   const Expr* SubExpr = E->getSubExpr();
15829 
15830   if (SubExpr->getType()->isRealFloatingType()) {
15831     Result.makeComplexFloat();
15832     APFloat &Imag = Result.FloatImag;
15833     if (!EvaluateFloat(SubExpr, Imag, Info))
15834       return false;
15835 
15836     Result.FloatReal = APFloat(Imag.getSemantics());
15837     return true;
15838   } else {
15839     assert(SubExpr->getType()->isIntegerType() &&
15840            "Unexpected imaginary literal.");
15841 
15842     Result.makeComplexInt();
15843     APSInt &Imag = Result.IntImag;
15844     if (!EvaluateInteger(SubExpr, Imag, Info))
15845       return false;
15846 
15847     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15848     return true;
15849   }
15850 }
15851 
15852 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15853 
15854   switch (E->getCastKind()) {
15855   case CK_BitCast:
15856   case CK_BaseToDerived:
15857   case CK_DerivedToBase:
15858   case CK_UncheckedDerivedToBase:
15859   case CK_Dynamic:
15860   case CK_ToUnion:
15861   case CK_ArrayToPointerDecay:
15862   case CK_FunctionToPointerDecay:
15863   case CK_NullToPointer:
15864   case CK_NullToMemberPointer:
15865   case CK_BaseToDerivedMemberPointer:
15866   case CK_DerivedToBaseMemberPointer:
15867   case CK_MemberPointerToBoolean:
15868   case CK_ReinterpretMemberPointer:
15869   case CK_ConstructorConversion:
15870   case CK_IntegralToPointer:
15871   case CK_PointerToIntegral:
15872   case CK_PointerToBoolean:
15873   case CK_ToVoid:
15874   case CK_VectorSplat:
15875   case CK_IntegralCast:
15876   case CK_BooleanToSignedIntegral:
15877   case CK_IntegralToBoolean:
15878   case CK_IntegralToFloating:
15879   case CK_FloatingToIntegral:
15880   case CK_FloatingToBoolean:
15881   case CK_FloatingCast:
15882   case CK_CPointerToObjCPointerCast:
15883   case CK_BlockPointerToObjCPointerCast:
15884   case CK_AnyPointerToBlockPointerCast:
15885   case CK_ObjCObjectLValueCast:
15886   case CK_FloatingComplexToReal:
15887   case CK_FloatingComplexToBoolean:
15888   case CK_IntegralComplexToReal:
15889   case CK_IntegralComplexToBoolean:
15890   case CK_ARCProduceObject:
15891   case CK_ARCConsumeObject:
15892   case CK_ARCReclaimReturnedObject:
15893   case CK_ARCExtendBlockObject:
15894   case CK_CopyAndAutoreleaseBlockObject:
15895   case CK_BuiltinFnToFnPtr:
15896   case CK_ZeroToOCLOpaqueType:
15897   case CK_NonAtomicToAtomic:
15898   case CK_AddressSpaceConversion:
15899   case CK_IntToOCLSampler:
15900   case CK_FloatingToFixedPoint:
15901   case CK_FixedPointToFloating:
15902   case CK_FixedPointCast:
15903   case CK_FixedPointToBoolean:
15904   case CK_FixedPointToIntegral:
15905   case CK_IntegralToFixedPoint:
15906   case CK_MatrixCast:
15907   case CK_HLSLVectorTruncation:
15908     llvm_unreachable("invalid cast kind for complex value");
15909 
15910   case CK_LValueToRValue:
15911   case CK_AtomicToNonAtomic:
15912   case CK_NoOp:
15913   case CK_LValueToRValueBitCast:
15914   case CK_HLSLArrayRValue:
15915     return ExprEvaluatorBaseTy::VisitCastExpr(E);
15916 
15917   case CK_Dependent:
15918   case CK_LValueBitCast:
15919   case CK_UserDefinedConversion:
15920     return Error(E);
15921 
15922   case CK_FloatingRealToComplex: {
15923     APFloat &Real = Result.FloatReal;
15924     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15925       return false;
15926 
15927     Result.makeComplexFloat();
15928     Result.FloatImag = APFloat(Real.getSemantics());
15929     return true;
15930   }
15931 
15932   case CK_FloatingComplexCast: {
15933     if (!Visit(E->getSubExpr()))
15934       return false;
15935 
15936     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15937     QualType From
15938       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15939 
15940     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
15941            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
15942   }
15943 
15944   case CK_FloatingComplexToIntegralComplex: {
15945     if (!Visit(E->getSubExpr()))
15946       return false;
15947 
15948     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15949     QualType From
15950       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15951     Result.makeComplexInt();
15952     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
15953                                 To, Result.IntReal) &&
15954            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
15955                                 To, Result.IntImag);
15956   }
15957 
15958   case CK_IntegralRealToComplex: {
15959     APSInt &Real = Result.IntReal;
15960     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15961       return false;
15962 
15963     Result.makeComplexInt();
15964     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15965     return true;
15966   }
15967 
15968   case CK_IntegralComplexCast: {
15969     if (!Visit(E->getSubExpr()))
15970       return false;
15971 
15972     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15973     QualType From
15974       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15975 
15976     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
15977     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
15978     return true;
15979   }
15980 
15981   case CK_IntegralComplexToFloatingComplex: {
15982     if (!Visit(E->getSubExpr()))
15983       return false;
15984 
15985     const FPOptions FPO = E->getFPFeaturesInEffect(
15986                                   Info.Ctx.getLangOpts());
15987     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15988     QualType From
15989       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15990     Result.makeComplexFloat();
15991     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
15992                                 To, Result.FloatReal) &&
15993            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
15994                                 To, Result.FloatImag);
15995   }
15996   }
15997 
15998   llvm_unreachable("unknown cast resulting in complex value");
15999 }
16000 
16001 void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
16002                              APFloat &ResR, APFloat &ResI) {
16003   // This is an implementation of complex multiplication according to the
16004   // constraints laid out in C11 Annex G. The implementation uses the
16005   // following naming scheme:
16006   //   (a + ib) * (c + id)
16007 
16008   APFloat AC = A * C;
16009   APFloat BD = B * D;
16010   APFloat AD = A * D;
16011   APFloat BC = B * C;
16012   ResR = AC - BD;
16013   ResI = AD + BC;
16014   if (ResR.isNaN() && ResI.isNaN()) {
16015     bool Recalc = false;
16016     if (A.isInfinity() || B.isInfinity()) {
16017       A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16018                             A);
16019       B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16020                             B);
16021       if (C.isNaN())
16022         C = APFloat::copySign(APFloat(C.getSemantics()), C);
16023       if (D.isNaN())
16024         D = APFloat::copySign(APFloat(D.getSemantics()), D);
16025       Recalc = true;
16026     }
16027     if (C.isInfinity() || D.isInfinity()) {
16028       C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16029                             C);
16030       D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16031                             D);
16032       if (A.isNaN())
16033         A = APFloat::copySign(APFloat(A.getSemantics()), A);
16034       if (B.isNaN())
16035         B = APFloat::copySign(APFloat(B.getSemantics()), B);
16036       Recalc = true;
16037     }
16038     if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
16039                     BC.isInfinity())) {
16040       if (A.isNaN())
16041         A = APFloat::copySign(APFloat(A.getSemantics()), A);
16042       if (B.isNaN())
16043         B = APFloat::copySign(APFloat(B.getSemantics()), B);
16044       if (C.isNaN())
16045         C = APFloat::copySign(APFloat(C.getSemantics()), C);
16046       if (D.isNaN())
16047         D = APFloat::copySign(APFloat(D.getSemantics()), D);
16048       Recalc = true;
16049     }
16050     if (Recalc) {
16051       ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
16052       ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
16053     }
16054   }
16055 }
16056 
16057 void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
16058                              APFloat &ResR, APFloat &ResI) {
16059   // This is an implementation of complex division according to the
16060   // constraints laid out in C11 Annex G. The implementation uses the
16061   // following naming scheme:
16062   //   (a + ib) / (c + id)
16063 
16064   int DenomLogB = 0;
16065   APFloat MaxCD = maxnum(abs(C), abs(D));
16066   if (MaxCD.isFinite()) {
16067     DenomLogB = ilogb(MaxCD);
16068     C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
16069     D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
16070   }
16071   APFloat Denom = C * C + D * D;
16072   ResR =
16073       scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16074   ResI =
16075       scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16076   if (ResR.isNaN() && ResI.isNaN()) {
16077     if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
16078       ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
16079       ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
16080     } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
16081                D.isFinite()) {
16082       A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16083                             A);
16084       B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16085                             B);
16086       ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
16087       ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
16088     } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
16089       C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16090                             C);
16091       D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16092                             D);
16093       ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
16094       ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
16095     }
16096   }
16097 }
16098 
16099 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16100   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16101     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16102 
16103   // Track whether the LHS or RHS is real at the type system level. When this is
16104   // the case we can simplify our evaluation strategy.
16105   bool LHSReal = false, RHSReal = false;
16106 
16107   bool LHSOK;
16108   if (E->getLHS()->getType()->isRealFloatingType()) {
16109     LHSReal = true;
16110     APFloat &Real = Result.FloatReal;
16111     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
16112     if (LHSOK) {
16113       Result.makeComplexFloat();
16114       Result.FloatImag = APFloat(Real.getSemantics());
16115     }
16116   } else {
16117     LHSOK = Visit(E->getLHS());
16118   }
16119   if (!LHSOK && !Info.noteFailure())
16120     return false;
16121 
16122   ComplexValue RHS;
16123   if (E->getRHS()->getType()->isRealFloatingType()) {
16124     RHSReal = true;
16125     APFloat &Real = RHS.FloatReal;
16126     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
16127       return false;
16128     RHS.makeComplexFloat();
16129     RHS.FloatImag = APFloat(Real.getSemantics());
16130   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16131     return false;
16132 
16133   assert(!(LHSReal && RHSReal) &&
16134          "Cannot have both operands of a complex operation be real.");
16135   switch (E->getOpcode()) {
16136   default: return Error(E);
16137   case BO_Add:
16138     if (Result.isComplexFloat()) {
16139       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
16140                                        APFloat::rmNearestTiesToEven);
16141       if (LHSReal)
16142         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16143       else if (!RHSReal)
16144         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
16145                                          APFloat::rmNearestTiesToEven);
16146     } else {
16147       Result.getComplexIntReal() += RHS.getComplexIntReal();
16148       Result.getComplexIntImag() += RHS.getComplexIntImag();
16149     }
16150     break;
16151   case BO_Sub:
16152     if (Result.isComplexFloat()) {
16153       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
16154                                             APFloat::rmNearestTiesToEven);
16155       if (LHSReal) {
16156         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16157         Result.getComplexFloatImag().changeSign();
16158       } else if (!RHSReal) {
16159         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
16160                                               APFloat::rmNearestTiesToEven);
16161       }
16162     } else {
16163       Result.getComplexIntReal() -= RHS.getComplexIntReal();
16164       Result.getComplexIntImag() -= RHS.getComplexIntImag();
16165     }
16166     break;
16167   case BO_Mul:
16168     if (Result.isComplexFloat()) {
16169       // This is an implementation of complex multiplication according to the
16170       // constraints laid out in C11 Annex G. The implementation uses the
16171       // following naming scheme:
16172       //   (a + ib) * (c + id)
16173       ComplexValue LHS = Result;
16174       APFloat &A = LHS.getComplexFloatReal();
16175       APFloat &B = LHS.getComplexFloatImag();
16176       APFloat &C = RHS.getComplexFloatReal();
16177       APFloat &D = RHS.getComplexFloatImag();
16178       APFloat &ResR = Result.getComplexFloatReal();
16179       APFloat &ResI = Result.getComplexFloatImag();
16180       if (LHSReal) {
16181         assert(!RHSReal && "Cannot have two real operands for a complex op!");
16182         ResR = A;
16183         ResI = A;
16184         // ResR = A * C;
16185         // ResI = A * D;
16186         if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
16187             !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
16188           return false;
16189       } else if (RHSReal) {
16190         // ResR = C * A;
16191         // ResI = C * B;
16192         ResR = C;
16193         ResI = C;
16194         if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
16195             !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
16196           return false;
16197       } else {
16198         HandleComplexComplexMul(A, B, C, D, ResR, ResI);
16199       }
16200     } else {
16201       ComplexValue LHS = Result;
16202       Result.getComplexIntReal() =
16203         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
16204          LHS.getComplexIntImag() * RHS.getComplexIntImag());
16205       Result.getComplexIntImag() =
16206         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
16207          LHS.getComplexIntImag() * RHS.getComplexIntReal());
16208     }
16209     break;
16210   case BO_Div:
16211     if (Result.isComplexFloat()) {
16212       // This is an implementation of complex division according to the
16213       // constraints laid out in C11 Annex G. The implementation uses the
16214       // following naming scheme:
16215       //   (a + ib) / (c + id)
16216       ComplexValue LHS = Result;
16217       APFloat &A = LHS.getComplexFloatReal();
16218       APFloat &B = LHS.getComplexFloatImag();
16219       APFloat &C = RHS.getComplexFloatReal();
16220       APFloat &D = RHS.getComplexFloatImag();
16221       APFloat &ResR = Result.getComplexFloatReal();
16222       APFloat &ResI = Result.getComplexFloatImag();
16223       if (RHSReal) {
16224         ResR = A;
16225         ResI = B;
16226         // ResR = A / C;
16227         // ResI = B / C;
16228         if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
16229             !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
16230           return false;
16231       } else {
16232         if (LHSReal) {
16233           // No real optimizations we can do here, stub out with zero.
16234           B = APFloat::getZero(A.getSemantics());
16235         }
16236         HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
16237       }
16238     } else {
16239       ComplexValue LHS = Result;
16240       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
16241         RHS.getComplexIntImag() * RHS.getComplexIntImag();
16242       if (Den.isZero())
16243         return Error(E, diag::note_expr_divide_by_zero);
16244 
16245       Result.getComplexIntReal() =
16246         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
16247          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
16248       Result.getComplexIntImag() =
16249         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
16250          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
16251     }
16252     break;
16253   }
16254 
16255   return true;
16256 }
16257 
16258 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16259   // Get the operand value into 'Result'.
16260   if (!Visit(E->getSubExpr()))
16261     return false;
16262 
16263   switch (E->getOpcode()) {
16264   default:
16265     return Error(E);
16266   case UO_Extension:
16267     return true;
16268   case UO_Plus:
16269     // The result is always just the subexpr.
16270     return true;
16271   case UO_Minus:
16272     if (Result.isComplexFloat()) {
16273       Result.getComplexFloatReal().changeSign();
16274       Result.getComplexFloatImag().changeSign();
16275     }
16276     else {
16277       Result.getComplexIntReal() = -Result.getComplexIntReal();
16278       Result.getComplexIntImag() = -Result.getComplexIntImag();
16279     }
16280     return true;
16281   case UO_Not:
16282     if (Result.isComplexFloat())
16283       Result.getComplexFloatImag().changeSign();
16284     else
16285       Result.getComplexIntImag() = -Result.getComplexIntImag();
16286     return true;
16287   }
16288 }
16289 
16290 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
16291   if (E->getNumInits() == 2) {
16292     if (E->getType()->isComplexType()) {
16293       Result.makeComplexFloat();
16294       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
16295         return false;
16296       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
16297         return false;
16298     } else {
16299       Result.makeComplexInt();
16300       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
16301         return false;
16302       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
16303         return false;
16304     }
16305     return true;
16306   }
16307   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
16308 }
16309 
16310 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
16311   if (!IsConstantEvaluatedBuiltinCall(E))
16312     return ExprEvaluatorBaseTy::VisitCallExpr(E);
16313 
16314   switch (E->getBuiltinCallee()) {
16315   case Builtin::BI__builtin_complex:
16316     Result.makeComplexFloat();
16317     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
16318       return false;
16319     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
16320       return false;
16321     return true;
16322 
16323   default:
16324     return false;
16325   }
16326 }
16327 
16328 //===----------------------------------------------------------------------===//
16329 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
16330 // implicit conversion.
16331 //===----------------------------------------------------------------------===//
16332 
16333 namespace {
16334 class AtomicExprEvaluator :
16335     public ExprEvaluatorBase<AtomicExprEvaluator> {
16336   const LValue *This;
16337   APValue &Result;
16338 public:
16339   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
16340       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
16341 
16342   bool Success(const APValue &V, const Expr *E) {
16343     Result = V;
16344     return true;
16345   }
16346 
16347   bool ZeroInitialization(const Expr *E) {
16348     ImplicitValueInitExpr VIE(
16349         E->getType()->castAs<AtomicType>()->getValueType());
16350     // For atomic-qualified class (and array) types in C++, initialize the
16351     // _Atomic-wrapped subobject directly, in-place.
16352     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
16353                 : Evaluate(Result, Info, &VIE);
16354   }
16355 
16356   bool VisitCastExpr(const CastExpr *E) {
16357     switch (E->getCastKind()) {
16358     default:
16359       return ExprEvaluatorBaseTy::VisitCastExpr(E);
16360     case CK_NullToPointer:
16361       VisitIgnoredValue(E->getSubExpr());
16362       return ZeroInitialization(E);
16363     case CK_NonAtomicToAtomic:
16364       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
16365                   : Evaluate(Result, Info, E->getSubExpr());
16366     }
16367   }
16368 };
16369 } // end anonymous namespace
16370 
16371 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
16372                            EvalInfo &Info) {
16373   assert(!E->isValueDependent());
16374   assert(E->isPRValue() && E->getType()->isAtomicType());
16375   return AtomicExprEvaluator(Info, This, Result).Visit(E);
16376 }
16377 
16378 //===----------------------------------------------------------------------===//
16379 // Void expression evaluation, primarily for a cast to void on the LHS of a
16380 // comma operator
16381 //===----------------------------------------------------------------------===//
16382 
16383 namespace {
16384 class VoidExprEvaluator
16385   : public ExprEvaluatorBase<VoidExprEvaluator> {
16386 public:
16387   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
16388 
16389   bool Success(const APValue &V, const Expr *e) { return true; }
16390 
16391   bool ZeroInitialization(const Expr *E) { return true; }
16392 
16393   bool VisitCastExpr(const CastExpr *E) {
16394     switch (E->getCastKind()) {
16395     default:
16396       return ExprEvaluatorBaseTy::VisitCastExpr(E);
16397     case CK_ToVoid:
16398       VisitIgnoredValue(E->getSubExpr());
16399       return true;
16400     }
16401   }
16402 
16403   bool VisitCallExpr(const CallExpr *E) {
16404     if (!IsConstantEvaluatedBuiltinCall(E))
16405       return ExprEvaluatorBaseTy::VisitCallExpr(E);
16406 
16407     switch (E->getBuiltinCallee()) {
16408     case Builtin::BI__assume:
16409     case Builtin::BI__builtin_assume:
16410       // The argument is not evaluated!
16411       return true;
16412 
16413     case Builtin::BI__builtin_operator_delete:
16414       return HandleOperatorDeleteCall(Info, E);
16415 
16416     default:
16417       return false;
16418     }
16419   }
16420 
16421   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
16422 };
16423 } // end anonymous namespace
16424 
16425 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
16426   // We cannot speculatively evaluate a delete expression.
16427   if (Info.SpeculativeEvaluationDepth)
16428     return false;
16429 
16430   FunctionDecl *OperatorDelete = E->getOperatorDelete();
16431   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
16432     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16433         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
16434     return false;
16435   }
16436 
16437   const Expr *Arg = E->getArgument();
16438 
16439   LValue Pointer;
16440   if (!EvaluatePointer(Arg, Pointer, Info))
16441     return false;
16442   if (Pointer.Designator.Invalid)
16443     return false;
16444 
16445   // Deleting a null pointer has no effect.
16446   if (Pointer.isNullPointer()) {
16447     // This is the only case where we need to produce an extension warning:
16448     // the only other way we can succeed is if we find a dynamic allocation,
16449     // and we will have warned when we allocated it in that case.
16450     if (!Info.getLangOpts().CPlusPlus20)
16451       Info.CCEDiag(E, diag::note_constexpr_new);
16452     return true;
16453   }
16454 
16455   std::optional<DynAlloc *> Alloc = CheckDeleteKind(
16456       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
16457   if (!Alloc)
16458     return false;
16459   QualType AllocType = Pointer.Base.getDynamicAllocType();
16460 
16461   // For the non-array case, the designator must be empty if the static type
16462   // does not have a virtual destructor.
16463   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
16464       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
16465     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
16466         << Arg->getType()->getPointeeType() << AllocType;
16467     return false;
16468   }
16469 
16470   // For a class type with a virtual destructor, the selected operator delete
16471   // is the one looked up when building the destructor.
16472   if (!E->isArrayForm() && !E->isGlobalDelete()) {
16473     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
16474     if (VirtualDelete &&
16475         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
16476       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16477           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
16478       return false;
16479     }
16480   }
16481 
16482   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
16483                          (*Alloc)->Value, AllocType))
16484     return false;
16485 
16486   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
16487     // The element was already erased. This means the destructor call also
16488     // deleted the object.
16489     // FIXME: This probably results in undefined behavior before we get this
16490     // far, and should be diagnosed elsewhere first.
16491     Info.FFDiag(E, diag::note_constexpr_double_delete);
16492     return false;
16493   }
16494 
16495   return true;
16496 }
16497 
16498 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
16499   assert(!E->isValueDependent());
16500   assert(E->isPRValue() && E->getType()->isVoidType());
16501   return VoidExprEvaluator(Info).Visit(E);
16502 }
16503 
16504 //===----------------------------------------------------------------------===//
16505 // Top level Expr::EvaluateAsRValue method.
16506 //===----------------------------------------------------------------------===//
16507 
16508 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
16509   assert(!E->isValueDependent());
16510   // In C, function designators are not lvalues, but we evaluate them as if they
16511   // are.
16512   QualType T = E->getType();
16513   if (E->isGLValue() || T->isFunctionType()) {
16514     LValue LV;
16515     if (!EvaluateLValue(E, LV, Info))
16516       return false;
16517     LV.moveInto(Result);
16518   } else if (T->isVectorType()) {
16519     if (!EvaluateVector(E, Result, Info))
16520       return false;
16521   } else if (T->isIntegralOrEnumerationType()) {
16522     if (!IntExprEvaluator(Info, Result).Visit(E))
16523       return false;
16524   } else if (T->hasPointerRepresentation()) {
16525     LValue LV;
16526     if (!EvaluatePointer(E, LV, Info))
16527       return false;
16528     LV.moveInto(Result);
16529   } else if (T->isRealFloatingType()) {
16530     llvm::APFloat F(0.0);
16531     if (!EvaluateFloat(E, F, Info))
16532       return false;
16533     Result = APValue(F);
16534   } else if (T->isAnyComplexType()) {
16535     ComplexValue C;
16536     if (!EvaluateComplex(E, C, Info))
16537       return false;
16538     C.moveInto(Result);
16539   } else if (T->isFixedPointType()) {
16540     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
16541   } else if (T->isMemberPointerType()) {
16542     MemberPtr P;
16543     if (!EvaluateMemberPointer(E, P, Info))
16544       return false;
16545     P.moveInto(Result);
16546     return true;
16547   } else if (T->isArrayType()) {
16548     LValue LV;
16549     APValue &Value =
16550         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16551     if (!EvaluateArray(E, LV, Value, Info))
16552       return false;
16553     Result = Value;
16554   } else if (T->isRecordType()) {
16555     LValue LV;
16556     APValue &Value =
16557         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16558     if (!EvaluateRecord(E, LV, Value, Info))
16559       return false;
16560     Result = Value;
16561   } else if (T->isVoidType()) {
16562     if (!Info.getLangOpts().CPlusPlus11)
16563       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
16564         << E->getType();
16565     if (!EvaluateVoid(E, Info))
16566       return false;
16567   } else if (T->isAtomicType()) {
16568     QualType Unqual = T.getAtomicUnqualifiedType();
16569     if (Unqual->isArrayType() || Unqual->isRecordType()) {
16570       LValue LV;
16571       APValue &Value = Info.CurrentCall->createTemporary(
16572           E, Unqual, ScopeKind::FullExpression, LV);
16573       if (!EvaluateAtomic(E, &LV, Value, Info))
16574         return false;
16575       Result = Value;
16576     } else {
16577       if (!EvaluateAtomic(E, nullptr, Result, Info))
16578         return false;
16579     }
16580   } else if (Info.getLangOpts().CPlusPlus11) {
16581     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
16582     return false;
16583   } else {
16584     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16585     return false;
16586   }
16587 
16588   return true;
16589 }
16590 
16591 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
16592 /// cases, the in-place evaluation is essential, since later initializers for
16593 /// an object can indirectly refer to subobjects which were initialized earlier.
16594 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
16595                             const Expr *E, bool AllowNonLiteralTypes) {
16596   assert(!E->isValueDependent());
16597 
16598   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
16599     return false;
16600 
16601   if (E->isPRValue()) {
16602     // Evaluate arrays and record types in-place, so that later initializers can
16603     // refer to earlier-initialized members of the object.
16604     QualType T = E->getType();
16605     if (T->isArrayType())
16606       return EvaluateArray(E, This, Result, Info);
16607     else if (T->isRecordType())
16608       return EvaluateRecord(E, This, Result, Info);
16609     else if (T->isAtomicType()) {
16610       QualType Unqual = T.getAtomicUnqualifiedType();
16611       if (Unqual->isArrayType() || Unqual->isRecordType())
16612         return EvaluateAtomic(E, &This, Result, Info);
16613     }
16614   }
16615 
16616   // For any other type, in-place evaluation is unimportant.
16617   return Evaluate(Result, Info, E);
16618 }
16619 
16620 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
16621 /// lvalue-to-rvalue cast if it is an lvalue.
16622 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
16623   assert(!E->isValueDependent());
16624 
16625   if (E->getType().isNull())
16626     return false;
16627 
16628   if (!CheckLiteralType(Info, E))
16629     return false;
16630 
16631   if (Info.EnableNewConstInterp) {
16632     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
16633       return false;
16634     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16635                                    ConstantExprKind::Normal);
16636   }
16637 
16638   if (!::Evaluate(Result, Info, E))
16639     return false;
16640 
16641   // Implicit lvalue-to-rvalue cast.
16642   if (E->isGLValue()) {
16643     LValue LV;
16644     LV.setFrom(Info.Ctx, Result);
16645     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
16646       return false;
16647   }
16648 
16649   // Check this core constant expression is a constant expression.
16650   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16651                                  ConstantExprKind::Normal) &&
16652          CheckMemoryLeaks(Info);
16653 }
16654 
16655 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
16656                                  const ASTContext &Ctx, bool &IsConst) {
16657   // Fast-path evaluations of integer literals, since we sometimes see files
16658   // containing vast quantities of these.
16659   if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
16660     Result.Val = APValue(APSInt(L->getValue(),
16661                                 L->getType()->isUnsignedIntegerType()));
16662     IsConst = true;
16663     return true;
16664   }
16665 
16666   if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
16667     Result.Val = APValue(APSInt(APInt(1, L->getValue())));
16668     IsConst = true;
16669     return true;
16670   }
16671 
16672   if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
16673     Result.Val = APValue(FL->getValue());
16674     IsConst = true;
16675     return true;
16676   }
16677 
16678   if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
16679     Result.Val = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
16680     IsConst = true;
16681     return true;
16682   }
16683 
16684   if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
16685     if (CE->hasAPValueResult()) {
16686       APValue APV = CE->getAPValueResult();
16687       if (!APV.isLValue()) {
16688         Result.Val = std::move(APV);
16689         IsConst = true;
16690         return true;
16691       }
16692     }
16693 
16694     // The SubExpr is usually just an IntegerLiteral.
16695     return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
16696   }
16697 
16698   // This case should be rare, but we need to check it before we check on
16699   // the type below.
16700   if (Exp->getType().isNull()) {
16701     IsConst = false;
16702     return true;
16703   }
16704 
16705   return false;
16706 }
16707 
16708 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
16709                                       Expr::SideEffectsKind SEK) {
16710   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
16711          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
16712 }
16713 
16714 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
16715                              const ASTContext &Ctx, EvalInfo &Info) {
16716   assert(!E->isValueDependent());
16717   bool IsConst;
16718   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
16719     return IsConst;
16720 
16721   return EvaluateAsRValue(Info, E, Result.Val);
16722 }
16723 
16724 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
16725                           const ASTContext &Ctx,
16726                           Expr::SideEffectsKind AllowSideEffects,
16727                           EvalInfo &Info) {
16728   assert(!E->isValueDependent());
16729   if (!E->getType()->isIntegralOrEnumerationType())
16730     return false;
16731 
16732   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
16733       !ExprResult.Val.isInt() ||
16734       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16735     return false;
16736 
16737   return true;
16738 }
16739 
16740 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
16741                                  const ASTContext &Ctx,
16742                                  Expr::SideEffectsKind AllowSideEffects,
16743                                  EvalInfo &Info) {
16744   assert(!E->isValueDependent());
16745   if (!E->getType()->isFixedPointType())
16746     return false;
16747 
16748   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
16749     return false;
16750 
16751   if (!ExprResult.Val.isFixedPoint() ||
16752       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16753     return false;
16754 
16755   return true;
16756 }
16757 
16758 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
16759 /// any crazy technique (that has nothing to do with language standards) that
16760 /// we want to.  If this function returns true, it returns the folded constant
16761 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
16762 /// will be applied to the result.
16763 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
16764                             bool InConstantContext) const {
16765   assert(!isValueDependent() &&
16766          "Expression evaluator can't be called on a dependent expression.");
16767   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
16768   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16769   Info.InConstantContext = InConstantContext;
16770   return ::EvaluateAsRValue(this, Result, Ctx, Info);
16771 }
16772 
16773 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
16774                                       bool InConstantContext) const {
16775   assert(!isValueDependent() &&
16776          "Expression evaluator can't be called on a dependent expression.");
16777   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
16778   EvalResult Scratch;
16779   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
16780          HandleConversionToBool(Scratch.Val, Result);
16781 }
16782 
16783 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
16784                          SideEffectsKind AllowSideEffects,
16785                          bool InConstantContext) const {
16786   assert(!isValueDependent() &&
16787          "Expression evaluator can't be called on a dependent expression.");
16788   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16789   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16790   Info.InConstantContext = InConstantContext;
16791   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
16792 }
16793 
16794 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
16795                                 SideEffectsKind AllowSideEffects,
16796                                 bool InConstantContext) const {
16797   assert(!isValueDependent() &&
16798          "Expression evaluator can't be called on a dependent expression.");
16799   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16800   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16801   Info.InConstantContext = InConstantContext;
16802   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
16803 }
16804 
16805 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16806                            SideEffectsKind AllowSideEffects,
16807                            bool InConstantContext) const {
16808   assert(!isValueDependent() &&
16809          "Expression evaluator can't be called on a dependent expression.");
16810 
16811   if (!getType()->isRealFloatingType())
16812     return false;
16813 
16814   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16815   EvalResult ExprResult;
16816   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
16817       !ExprResult.Val.isFloat() ||
16818       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16819     return false;
16820 
16821   Result = ExprResult.Val.getFloat();
16822   return true;
16823 }
16824 
16825 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
16826                             bool InConstantContext) const {
16827   assert(!isValueDependent() &&
16828          "Expression evaluator can't be called on a dependent expression.");
16829 
16830   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16831   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16832   Info.InConstantContext = InConstantContext;
16833   LValue LV;
16834   CheckedTemporaries CheckedTemps;
16835   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
16836       Result.HasSideEffects ||
16837       !CheckLValueConstantExpression(Info, getExprLoc(),
16838                                      Ctx.getLValueReferenceType(getType()), LV,
16839                                      ConstantExprKind::Normal, CheckedTemps))
16840     return false;
16841 
16842   LV.moveInto(Result.Val);
16843   return true;
16844 }
16845 
16846 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
16847                                 APValue DestroyedValue, QualType Type,
16848                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
16849                                 bool IsConstantDestruction) {
16850   EvalInfo Info(Ctx, EStatus,
16851                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16852                                       : EvalInfo::EM_ConstantFold);
16853   Info.setEvaluatingDecl(Base, DestroyedValue,
16854                          EvalInfo::EvaluatingDeclKind::Dtor);
16855   Info.InConstantContext = IsConstantDestruction;
16856 
16857   LValue LVal;
16858   LVal.set(Base);
16859 
16860   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
16861       EStatus.HasSideEffects)
16862     return false;
16863 
16864   if (!Info.discardCleanups())
16865     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16866 
16867   return true;
16868 }
16869 
16870 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
16871                                   ConstantExprKind Kind) const {
16872   assert(!isValueDependent() &&
16873          "Expression evaluator can't be called on a dependent expression.");
16874   bool IsConst;
16875   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
16876     return true;
16877 
16878   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
16879   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
16880   EvalInfo Info(Ctx, Result, EM);
16881   Info.InConstantContext = true;
16882 
16883   if (Info.EnableNewConstInterp) {
16884     if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
16885       return false;
16886     return CheckConstantExpression(Info, getExprLoc(),
16887                                    getStorageType(Ctx, this), Result.Val, Kind);
16888   }
16889 
16890   // The type of the object we're initializing is 'const T' for a class NTTP.
16891   QualType T = getType();
16892   if (Kind == ConstantExprKind::ClassTemplateArgument)
16893     T.addConst();
16894 
16895   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
16896   // represent the result of the evaluation. CheckConstantExpression ensures
16897   // this doesn't escape.
16898   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
16899   APValue::LValueBase Base(&BaseMTE);
16900   Info.setEvaluatingDecl(Base, Result.Val);
16901 
16902   if (Info.EnableNewConstInterp) {
16903     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
16904       return false;
16905   } else {
16906     LValue LVal;
16907     LVal.set(Base);
16908     // C++23 [intro.execution]/p5
16909     // A full-expression is [...] a constant-expression
16910     // So we need to make sure temporary objects are destroyed after having
16911     // evaluating the expression (per C++23 [class.temporary]/p4).
16912     FullExpressionRAII Scope(Info);
16913     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
16914         Result.HasSideEffects || !Scope.destroy())
16915       return false;
16916 
16917     if (!Info.discardCleanups())
16918       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16919   }
16920 
16921   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
16922                                Result.Val, Kind))
16923     return false;
16924   if (!CheckMemoryLeaks(Info))
16925     return false;
16926 
16927   // If this is a class template argument, it's required to have constant
16928   // destruction too.
16929   if (Kind == ConstantExprKind::ClassTemplateArgument &&
16930       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
16931                             true) ||
16932        Result.HasSideEffects)) {
16933     // FIXME: Prefix a note to indicate that the problem is lack of constant
16934     // destruction.
16935     return false;
16936   }
16937 
16938   return true;
16939 }
16940 
16941 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
16942                                  const VarDecl *VD,
16943                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
16944                                  bool IsConstantInitialization) const {
16945   assert(!isValueDependent() &&
16946          "Expression evaluator can't be called on a dependent expression.");
16947 
16948   llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16949     std::string Name;
16950     llvm::raw_string_ostream OS(Name);
16951     VD->printQualifiedName(OS);
16952     return Name;
16953   });
16954 
16955   Expr::EvalStatus EStatus;
16956   EStatus.Diag = &Notes;
16957 
16958   EvalInfo Info(Ctx, EStatus,
16959                 (IsConstantInitialization &&
16960                  (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16961                     ? EvalInfo::EM_ConstantExpression
16962                     : EvalInfo::EM_ConstantFold);
16963   Info.setEvaluatingDecl(VD, Value);
16964   Info.InConstantContext = IsConstantInitialization;
16965 
16966   SourceLocation DeclLoc = VD->getLocation();
16967   QualType DeclTy = VD->getType();
16968 
16969   if (Info.EnableNewConstInterp) {
16970     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16971     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
16972       return false;
16973 
16974     return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16975                                    ConstantExprKind::Normal);
16976   } else {
16977     LValue LVal;
16978     LVal.set(VD);
16979 
16980     {
16981       // C++23 [intro.execution]/p5
16982       // A full-expression is ... an init-declarator ([dcl.decl]) or a
16983       // mem-initializer.
16984       // So we need to make sure temporary objects are destroyed after having
16985       // evaluated the expression (per C++23 [class.temporary]/p4).
16986       //
16987       // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16988       // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16989       // outermost FullExpr, such as ExprWithCleanups.
16990       FullExpressionRAII Scope(Info);
16991       if (!EvaluateInPlace(Value, Info, LVal, this,
16992                            /*AllowNonLiteralTypes=*/true) ||
16993           EStatus.HasSideEffects)
16994         return false;
16995     }
16996 
16997     // At this point, any lifetime-extended temporaries are completely
16998     // initialized.
16999     Info.performLifetimeExtension();
17000 
17001     if (!Info.discardCleanups())
17002       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
17003   }
17004 
17005   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17006                                  ConstantExprKind::Normal) &&
17007          CheckMemoryLeaks(Info);
17008 }
17009 
17010 bool VarDecl::evaluateDestruction(
17011     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
17012   Expr::EvalStatus EStatus;
17013   EStatus.Diag = &Notes;
17014 
17015   // Only treat the destruction as constant destruction if we formally have
17016   // constant initialization (or are usable in a constant expression).
17017   bool IsConstantDestruction = hasConstantInitialization();
17018 
17019   // Make a copy of the value for the destructor to mutate, if we know it.
17020   // Otherwise, treat the value as default-initialized; if the destructor works
17021   // anyway, then the destruction is constant (and must be essentially empty).
17022   APValue DestroyedValue;
17023   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
17024     DestroyedValue = *getEvaluatedValue();
17025   else if (!handleDefaultInitValue(getType(), DestroyedValue))
17026     return false;
17027 
17028   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
17029                            getType(), getLocation(), EStatus,
17030                            IsConstantDestruction) ||
17031       EStatus.HasSideEffects)
17032     return false;
17033 
17034   ensureEvaluatedStmt()->HasConstantDestruction = true;
17035   return true;
17036 }
17037 
17038 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
17039 /// constant folded, but discard the result.
17040 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
17041   assert(!isValueDependent() &&
17042          "Expression evaluator can't be called on a dependent expression.");
17043 
17044   EvalResult Result;
17045   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
17046          !hasUnacceptableSideEffect(Result, SEK);
17047 }
17048 
17049 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
17050                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
17051   assert(!isValueDependent() &&
17052          "Expression evaluator can't be called on a dependent expression.");
17053 
17054   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
17055   EvalResult EVResult;
17056   EVResult.Diag = Diag;
17057   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17058   Info.InConstantContext = true;
17059 
17060   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
17061   (void)Result;
17062   assert(Result && "Could not evaluate expression");
17063   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17064 
17065   return EVResult.Val.getInt();
17066 }
17067 
17068 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
17069     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
17070   assert(!isValueDependent() &&
17071          "Expression evaluator can't be called on a dependent expression.");
17072 
17073   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
17074   EvalResult EVResult;
17075   EVResult.Diag = Diag;
17076   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17077   Info.InConstantContext = true;
17078   Info.CheckingForUndefinedBehavior = true;
17079 
17080   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
17081   (void)Result;
17082   assert(Result && "Could not evaluate expression");
17083   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17084 
17085   return EVResult.Val.getInt();
17086 }
17087 
17088 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
17089   assert(!isValueDependent() &&
17090          "Expression evaluator can't be called on a dependent expression.");
17091 
17092   ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
17093   bool IsConst;
17094   EvalResult EVResult;
17095   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
17096     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17097     Info.CheckingForUndefinedBehavior = true;
17098     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
17099   }
17100 }
17101 
17102 bool Expr::EvalResult::isGlobalLValue() const {
17103   assert(Val.isLValue());
17104   return IsGlobalLValue(Val.getLValueBase());
17105 }
17106 
17107 /// isIntegerConstantExpr - this recursive routine will test if an expression is
17108 /// an integer constant expression.
17109 
17110 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
17111 /// comma, etc
17112 
17113 // CheckICE - This function does the fundamental ICE checking: the returned
17114 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
17115 // and a (possibly null) SourceLocation indicating the location of the problem.
17116 //
17117 // Note that to reduce code duplication, this helper does no evaluation
17118 // itself; the caller checks whether the expression is evaluatable, and
17119 // in the rare cases where CheckICE actually cares about the evaluated
17120 // value, it calls into Evaluate.
17121 
17122 namespace {
17123 
17124 enum ICEKind {
17125   /// This expression is an ICE.
17126   IK_ICE,
17127   /// This expression is not an ICE, but if it isn't evaluated, it's
17128   /// a legal subexpression for an ICE. This return value is used to handle
17129   /// the comma operator in C99 mode, and non-constant subexpressions.
17130   IK_ICEIfUnevaluated,
17131   /// This expression is not an ICE, and is not a legal subexpression for one.
17132   IK_NotICE
17133 };
17134 
17135 struct ICEDiag {
17136   ICEKind Kind;
17137   SourceLocation Loc;
17138 
17139   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
17140 };
17141 
17142 }
17143 
17144 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
17145 
17146 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
17147 
17148 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
17149   Expr::EvalResult EVResult;
17150   Expr::EvalStatus Status;
17151   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17152 
17153   Info.InConstantContext = true;
17154   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
17155       !EVResult.Val.isInt())
17156     return ICEDiag(IK_NotICE, E->getBeginLoc());
17157 
17158   return NoDiag();
17159 }
17160 
17161 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
17162   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
17163   if (!E->getType()->isIntegralOrEnumerationType())
17164     return ICEDiag(IK_NotICE, E->getBeginLoc());
17165 
17166   switch (E->getStmtClass()) {
17167 #define ABSTRACT_STMT(Node)
17168 #define STMT(Node, Base) case Expr::Node##Class:
17169 #define EXPR(Node, Base)
17170 #include "clang/AST/StmtNodes.inc"
17171   case Expr::PredefinedExprClass:
17172   case Expr::FloatingLiteralClass:
17173   case Expr::ImaginaryLiteralClass:
17174   case Expr::StringLiteralClass:
17175   case Expr::ArraySubscriptExprClass:
17176   case Expr::MatrixSubscriptExprClass:
17177   case Expr::ArraySectionExprClass:
17178   case Expr::OMPArrayShapingExprClass:
17179   case Expr::OMPIteratorExprClass:
17180   case Expr::MemberExprClass:
17181   case Expr::CompoundAssignOperatorClass:
17182   case Expr::CompoundLiteralExprClass:
17183   case Expr::ExtVectorElementExprClass:
17184   case Expr::DesignatedInitExprClass:
17185   case Expr::ArrayInitLoopExprClass:
17186   case Expr::ArrayInitIndexExprClass:
17187   case Expr::NoInitExprClass:
17188   case Expr::DesignatedInitUpdateExprClass:
17189   case Expr::ImplicitValueInitExprClass:
17190   case Expr::ParenListExprClass:
17191   case Expr::VAArgExprClass:
17192   case Expr::AddrLabelExprClass:
17193   case Expr::StmtExprClass:
17194   case Expr::CXXMemberCallExprClass:
17195   case Expr::CUDAKernelCallExprClass:
17196   case Expr::CXXAddrspaceCastExprClass:
17197   case Expr::CXXDynamicCastExprClass:
17198   case Expr::CXXTypeidExprClass:
17199   case Expr::CXXUuidofExprClass:
17200   case Expr::MSPropertyRefExprClass:
17201   case Expr::MSPropertySubscriptExprClass:
17202   case Expr::CXXNullPtrLiteralExprClass:
17203   case Expr::UserDefinedLiteralClass:
17204   case Expr::CXXThisExprClass:
17205   case Expr::CXXThrowExprClass:
17206   case Expr::CXXNewExprClass:
17207   case Expr::CXXDeleteExprClass:
17208   case Expr::CXXPseudoDestructorExprClass:
17209   case Expr::UnresolvedLookupExprClass:
17210   case Expr::TypoExprClass:
17211   case Expr::RecoveryExprClass:
17212   case Expr::DependentScopeDeclRefExprClass:
17213   case Expr::CXXConstructExprClass:
17214   case Expr::CXXInheritedCtorInitExprClass:
17215   case Expr::CXXStdInitializerListExprClass:
17216   case Expr::CXXBindTemporaryExprClass:
17217   case Expr::ExprWithCleanupsClass:
17218   case Expr::CXXTemporaryObjectExprClass:
17219   case Expr::CXXUnresolvedConstructExprClass:
17220   case Expr::CXXDependentScopeMemberExprClass:
17221   case Expr::UnresolvedMemberExprClass:
17222   case Expr::ObjCStringLiteralClass:
17223   case Expr::ObjCBoxedExprClass:
17224   case Expr::ObjCArrayLiteralClass:
17225   case Expr::ObjCDictionaryLiteralClass:
17226   case Expr::ObjCEncodeExprClass:
17227   case Expr::ObjCMessageExprClass:
17228   case Expr::ObjCSelectorExprClass:
17229   case Expr::ObjCProtocolExprClass:
17230   case Expr::ObjCIvarRefExprClass:
17231   case Expr::ObjCPropertyRefExprClass:
17232   case Expr::ObjCSubscriptRefExprClass:
17233   case Expr::ObjCIsaExprClass:
17234   case Expr::ObjCAvailabilityCheckExprClass:
17235   case Expr::ShuffleVectorExprClass:
17236   case Expr::ConvertVectorExprClass:
17237   case Expr::BlockExprClass:
17238   case Expr::NoStmtClass:
17239   case Expr::OpaqueValueExprClass:
17240   case Expr::PackExpansionExprClass:
17241   case Expr::SubstNonTypeTemplateParmPackExprClass:
17242   case Expr::FunctionParmPackExprClass:
17243   case Expr::AsTypeExprClass:
17244   case Expr::ObjCIndirectCopyRestoreExprClass:
17245   case Expr::MaterializeTemporaryExprClass:
17246   case Expr::PseudoObjectExprClass:
17247   case Expr::AtomicExprClass:
17248   case Expr::LambdaExprClass:
17249   case Expr::CXXFoldExprClass:
17250   case Expr::CoawaitExprClass:
17251   case Expr::DependentCoawaitExprClass:
17252   case Expr::CoyieldExprClass:
17253   case Expr::SYCLUniqueStableNameExprClass:
17254   case Expr::CXXParenListInitExprClass:
17255   case Expr::HLSLOutArgExprClass:
17256   case Expr::ResolvedUnexpandedPackExprClass:
17257     return ICEDiag(IK_NotICE, E->getBeginLoc());
17258 
17259   case Expr::InitListExprClass: {
17260     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
17261     // form "T x = { a };" is equivalent to "T x = a;".
17262     // Unless we're initializing a reference, T is a scalar as it is known to be
17263     // of integral or enumeration type.
17264     if (E->isPRValue())
17265       if (cast<InitListExpr>(E)->getNumInits() == 1)
17266         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
17267     return ICEDiag(IK_NotICE, E->getBeginLoc());
17268   }
17269 
17270   case Expr::SizeOfPackExprClass:
17271   case Expr::GNUNullExprClass:
17272   case Expr::SourceLocExprClass:
17273   case Expr::EmbedExprClass:
17274   case Expr::OpenACCAsteriskSizeExprClass:
17275     return NoDiag();
17276 
17277   case Expr::PackIndexingExprClass:
17278     return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
17279 
17280   case Expr::SubstNonTypeTemplateParmExprClass:
17281     return
17282       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
17283 
17284   case Expr::ConstantExprClass:
17285     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
17286 
17287   case Expr::ParenExprClass:
17288     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
17289   case Expr::GenericSelectionExprClass:
17290     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
17291   case Expr::IntegerLiteralClass:
17292   case Expr::FixedPointLiteralClass:
17293   case Expr::CharacterLiteralClass:
17294   case Expr::ObjCBoolLiteralExprClass:
17295   case Expr::CXXBoolLiteralExprClass:
17296   case Expr::CXXScalarValueInitExprClass:
17297   case Expr::TypeTraitExprClass:
17298   case Expr::ConceptSpecializationExprClass:
17299   case Expr::RequiresExprClass:
17300   case Expr::ArrayTypeTraitExprClass:
17301   case Expr::ExpressionTraitExprClass:
17302   case Expr::CXXNoexceptExprClass:
17303     return NoDiag();
17304   case Expr::CallExprClass:
17305   case Expr::CXXOperatorCallExprClass: {
17306     // C99 6.6/3 allows function calls within unevaluated subexpressions of
17307     // constant expressions, but they can never be ICEs because an ICE cannot
17308     // contain an operand of (pointer to) function type.
17309     const CallExpr *CE = cast<CallExpr>(E);
17310     if (CE->getBuiltinCallee())
17311       return CheckEvalInICE(E, Ctx);
17312     return ICEDiag(IK_NotICE, E->getBeginLoc());
17313   }
17314   case Expr::CXXRewrittenBinaryOperatorClass:
17315     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
17316                     Ctx);
17317   case Expr::DeclRefExprClass: {
17318     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
17319     if (isa<EnumConstantDecl>(D))
17320       return NoDiag();
17321 
17322     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
17323     // integer variables in constant expressions:
17324     //
17325     // C++ 7.1.5.1p2
17326     //   A variable of non-volatile const-qualified integral or enumeration
17327     //   type initialized by an ICE can be used in ICEs.
17328     //
17329     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
17330     // that mode, use of reference variables should not be allowed.
17331     const VarDecl *VD = dyn_cast<VarDecl>(D);
17332     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
17333         !VD->getType()->isReferenceType())
17334       return NoDiag();
17335 
17336     return ICEDiag(IK_NotICE, E->getBeginLoc());
17337   }
17338   case Expr::UnaryOperatorClass: {
17339     const UnaryOperator *Exp = cast<UnaryOperator>(E);
17340     switch (Exp->getOpcode()) {
17341     case UO_PostInc:
17342     case UO_PostDec:
17343     case UO_PreInc:
17344     case UO_PreDec:
17345     case UO_AddrOf:
17346     case UO_Deref:
17347     case UO_Coawait:
17348       // C99 6.6/3 allows increment and decrement within unevaluated
17349       // subexpressions of constant expressions, but they can never be ICEs
17350       // because an ICE cannot contain an lvalue operand.
17351       return ICEDiag(IK_NotICE, E->getBeginLoc());
17352     case UO_Extension:
17353     case UO_LNot:
17354     case UO_Plus:
17355     case UO_Minus:
17356     case UO_Not:
17357     case UO_Real:
17358     case UO_Imag:
17359       return CheckICE(Exp->getSubExpr(), Ctx);
17360     }
17361     llvm_unreachable("invalid unary operator class");
17362   }
17363   case Expr::OffsetOfExprClass: {
17364     // Note that per C99, offsetof must be an ICE. And AFAIK, using
17365     // EvaluateAsRValue matches the proposed gcc behavior for cases like
17366     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
17367     // compliance: we should warn earlier for offsetof expressions with
17368     // array subscripts that aren't ICEs, and if the array subscripts
17369     // are ICEs, the value of the offsetof must be an integer constant.
17370     return CheckEvalInICE(E, Ctx);
17371   }
17372   case Expr::UnaryExprOrTypeTraitExprClass: {
17373     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
17374     if ((Exp->getKind() ==  UETT_SizeOf) &&
17375         Exp->getTypeOfArgument()->isVariableArrayType())
17376       return ICEDiag(IK_NotICE, E->getBeginLoc());
17377     return NoDiag();
17378   }
17379   case Expr::BinaryOperatorClass: {
17380     const BinaryOperator *Exp = cast<BinaryOperator>(E);
17381     switch (Exp->getOpcode()) {
17382     case BO_PtrMemD:
17383     case BO_PtrMemI:
17384     case BO_Assign:
17385     case BO_MulAssign:
17386     case BO_DivAssign:
17387     case BO_RemAssign:
17388     case BO_AddAssign:
17389     case BO_SubAssign:
17390     case BO_ShlAssign:
17391     case BO_ShrAssign:
17392     case BO_AndAssign:
17393     case BO_XorAssign:
17394     case BO_OrAssign:
17395       // C99 6.6/3 allows assignments within unevaluated subexpressions of
17396       // constant expressions, but they can never be ICEs because an ICE cannot
17397       // contain an lvalue operand.
17398       return ICEDiag(IK_NotICE, E->getBeginLoc());
17399 
17400     case BO_Mul:
17401     case BO_Div:
17402     case BO_Rem:
17403     case BO_Add:
17404     case BO_Sub:
17405     case BO_Shl:
17406     case BO_Shr:
17407     case BO_LT:
17408     case BO_GT:
17409     case BO_LE:
17410     case BO_GE:
17411     case BO_EQ:
17412     case BO_NE:
17413     case BO_And:
17414     case BO_Xor:
17415     case BO_Or:
17416     case BO_Comma:
17417     case BO_Cmp: {
17418       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17419       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17420       if (Exp->getOpcode() == BO_Div ||
17421           Exp->getOpcode() == BO_Rem) {
17422         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
17423         // we don't evaluate one.
17424         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
17425           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
17426           if (REval == 0)
17427             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17428           if (REval.isSigned() && REval.isAllOnes()) {
17429             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
17430             if (LEval.isMinSignedValue())
17431               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17432           }
17433         }
17434       }
17435       if (Exp->getOpcode() == BO_Comma) {
17436         if (Ctx.getLangOpts().C99) {
17437           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
17438           // if it isn't evaluated.
17439           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
17440             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17441         } else {
17442           // In both C89 and C++, commas in ICEs are illegal.
17443           return ICEDiag(IK_NotICE, E->getBeginLoc());
17444         }
17445       }
17446       return Worst(LHSResult, RHSResult);
17447     }
17448     case BO_LAnd:
17449     case BO_LOr: {
17450       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17451       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17452       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
17453         // Rare case where the RHS has a comma "side-effect"; we need
17454         // to actually check the condition to see whether the side
17455         // with the comma is evaluated.
17456         if ((Exp->getOpcode() == BO_LAnd) !=
17457             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
17458           return RHSResult;
17459         return NoDiag();
17460       }
17461 
17462       return Worst(LHSResult, RHSResult);
17463     }
17464     }
17465     llvm_unreachable("invalid binary operator kind");
17466   }
17467   case Expr::ImplicitCastExprClass:
17468   case Expr::CStyleCastExprClass:
17469   case Expr::CXXFunctionalCastExprClass:
17470   case Expr::CXXStaticCastExprClass:
17471   case Expr::CXXReinterpretCastExprClass:
17472   case Expr::CXXConstCastExprClass:
17473   case Expr::ObjCBridgedCastExprClass: {
17474     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
17475     if (isa<ExplicitCastExpr>(E)) {
17476       if (const FloatingLiteral *FL
17477             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
17478         unsigned DestWidth = Ctx.getIntWidth(E->getType());
17479         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
17480         APSInt IgnoredVal(DestWidth, !DestSigned);
17481         bool Ignored;
17482         // If the value does not fit in the destination type, the behavior is
17483         // undefined, so we are not required to treat it as a constant
17484         // expression.
17485         if (FL->getValue().convertToInteger(IgnoredVal,
17486                                             llvm::APFloat::rmTowardZero,
17487                                             &Ignored) & APFloat::opInvalidOp)
17488           return ICEDiag(IK_NotICE, E->getBeginLoc());
17489         return NoDiag();
17490       }
17491     }
17492     switch (cast<CastExpr>(E)->getCastKind()) {
17493     case CK_LValueToRValue:
17494     case CK_AtomicToNonAtomic:
17495     case CK_NonAtomicToAtomic:
17496     case CK_NoOp:
17497     case CK_IntegralToBoolean:
17498     case CK_IntegralCast:
17499       return CheckICE(SubExpr, Ctx);
17500     default:
17501       return ICEDiag(IK_NotICE, E->getBeginLoc());
17502     }
17503   }
17504   case Expr::BinaryConditionalOperatorClass: {
17505     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
17506     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
17507     if (CommonResult.Kind == IK_NotICE) return CommonResult;
17508     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17509     if (FalseResult.Kind == IK_NotICE) return FalseResult;
17510     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
17511     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
17512         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
17513     return FalseResult;
17514   }
17515   case Expr::ConditionalOperatorClass: {
17516     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
17517     // If the condition (ignoring parens) is a __builtin_constant_p call,
17518     // then only the true side is actually considered in an integer constant
17519     // expression, and it is fully evaluated.  This is an important GNU
17520     // extension.  See GCC PR38377 for discussion.
17521     if (const CallExpr *CallCE
17522         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
17523       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
17524         return CheckEvalInICE(E, Ctx);
17525     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
17526     if (CondResult.Kind == IK_NotICE)
17527       return CondResult;
17528 
17529     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
17530     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17531 
17532     if (TrueResult.Kind == IK_NotICE)
17533       return TrueResult;
17534     if (FalseResult.Kind == IK_NotICE)
17535       return FalseResult;
17536     if (CondResult.Kind == IK_ICEIfUnevaluated)
17537       return CondResult;
17538     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
17539       return NoDiag();
17540     // Rare case where the diagnostics depend on which side is evaluated
17541     // Note that if we get here, CondResult is 0, and at least one of
17542     // TrueResult and FalseResult is non-zero.
17543     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
17544       return FalseResult;
17545     return TrueResult;
17546   }
17547   case Expr::CXXDefaultArgExprClass:
17548     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
17549   case Expr::CXXDefaultInitExprClass:
17550     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
17551   case Expr::ChooseExprClass: {
17552     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
17553   }
17554   case Expr::BuiltinBitCastExprClass: {
17555     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
17556       return ICEDiag(IK_NotICE, E->getBeginLoc());
17557     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
17558   }
17559   }
17560 
17561   llvm_unreachable("Invalid StmtClass!");
17562 }
17563 
17564 /// Evaluate an expression as a C++11 integral constant expression.
17565 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
17566                                                     const Expr *E,
17567                                                     llvm::APSInt *Value,
17568                                                     SourceLocation *Loc) {
17569   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17570     if (Loc) *Loc = E->getExprLoc();
17571     return false;
17572   }
17573 
17574   APValue Result;
17575   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
17576     return false;
17577 
17578   if (!Result.isInt()) {
17579     if (Loc) *Loc = E->getExprLoc();
17580     return false;
17581   }
17582 
17583   if (Value) *Value = Result.getInt();
17584   return true;
17585 }
17586 
17587 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
17588                                  SourceLocation *Loc) const {
17589   assert(!isValueDependent() &&
17590          "Expression evaluator can't be called on a dependent expression.");
17591 
17592   ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
17593 
17594   if (Ctx.getLangOpts().CPlusPlus11)
17595     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
17596 
17597   ICEDiag D = CheckICE(this, Ctx);
17598   if (D.Kind != IK_ICE) {
17599     if (Loc) *Loc = D.Loc;
17600     return false;
17601   }
17602   return true;
17603 }
17604 
17605 std::optional<llvm::APSInt>
17606 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const {
17607   if (isValueDependent()) {
17608     // Expression evaluator can't succeed on a dependent expression.
17609     return std::nullopt;
17610   }
17611 
17612   APSInt Value;
17613 
17614   if (Ctx.getLangOpts().CPlusPlus11) {
17615     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
17616       return Value;
17617     return std::nullopt;
17618   }
17619 
17620   if (!isIntegerConstantExpr(Ctx, Loc))
17621     return std::nullopt;
17622 
17623   // The only possible side-effects here are due to UB discovered in the
17624   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
17625   // required to treat the expression as an ICE, so we produce the folded
17626   // value.
17627   EvalResult ExprResult;
17628   Expr::EvalStatus Status;
17629   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
17630   Info.InConstantContext = true;
17631 
17632   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
17633     llvm_unreachable("ICE cannot be evaluated!");
17634 
17635   return ExprResult.Val.getInt();
17636 }
17637 
17638 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
17639   assert(!isValueDependent() &&
17640          "Expression evaluator can't be called on a dependent expression.");
17641 
17642   return CheckICE(this, Ctx).Kind == IK_ICE;
17643 }
17644 
17645 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
17646                                SourceLocation *Loc) const {
17647   assert(!isValueDependent() &&
17648          "Expression evaluator can't be called on a dependent expression.");
17649 
17650   // We support this checking in C++98 mode in order to diagnose compatibility
17651   // issues.
17652   assert(Ctx.getLangOpts().CPlusPlus);
17653 
17654   // Build evaluation settings.
17655   Expr::EvalStatus Status;
17656   SmallVector<PartialDiagnosticAt, 8> Diags;
17657   Status.Diag = &Diags;
17658   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17659 
17660   APValue Scratch;
17661   bool IsConstExpr =
17662       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
17663       // FIXME: We don't produce a diagnostic for this, but the callers that
17664       // call us on arbitrary full-expressions should generally not care.
17665       Info.discardCleanups() && !Status.HasSideEffects;
17666 
17667   if (!Diags.empty()) {
17668     IsConstExpr = false;
17669     if (Loc) *Loc = Diags[0].first;
17670   } else if (!IsConstExpr) {
17671     // FIXME: This shouldn't happen.
17672     if (Loc) *Loc = getExprLoc();
17673   }
17674 
17675   return IsConstExpr;
17676 }
17677 
17678 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
17679                                     const FunctionDecl *Callee,
17680                                     ArrayRef<const Expr*> Args,
17681                                     const Expr *This) const {
17682   assert(!isValueDependent() &&
17683          "Expression evaluator can't be called on a dependent expression.");
17684 
17685   llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
17686     std::string Name;
17687     llvm::raw_string_ostream OS(Name);
17688     Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
17689                                  /*Qualified=*/true);
17690     return Name;
17691   });
17692 
17693   Expr::EvalStatus Status;
17694   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
17695   Info.InConstantContext = true;
17696 
17697   LValue ThisVal;
17698   const LValue *ThisPtr = nullptr;
17699   if (This) {
17700 #ifndef NDEBUG
17701     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
17702     assert(MD && "Don't provide `this` for non-methods.");
17703     assert(MD->isImplicitObjectMemberFunction() &&
17704            "Don't provide `this` for methods without an implicit object.");
17705 #endif
17706     if (!This->isValueDependent() &&
17707         EvaluateObjectArgument(Info, This, ThisVal) &&
17708         !Info.EvalStatus.HasSideEffects)
17709       ThisPtr = &ThisVal;
17710 
17711     // Ignore any side-effects from a failed evaluation. This is safe because
17712     // they can't interfere with any other argument evaluation.
17713     Info.EvalStatus.HasSideEffects = false;
17714   }
17715 
17716   CallRef Call = Info.CurrentCall->createCall(Callee);
17717   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
17718        I != E; ++I) {
17719     unsigned Idx = I - Args.begin();
17720     if (Idx >= Callee->getNumParams())
17721       break;
17722     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
17723     if ((*I)->isValueDependent() ||
17724         !EvaluateCallArg(PVD, *I, Call, Info) ||
17725         Info.EvalStatus.HasSideEffects) {
17726       // If evaluation fails, throw away the argument entirely.
17727       if (APValue *Slot = Info.getParamSlot(Call, PVD))
17728         *Slot = APValue();
17729     }
17730 
17731     // Ignore any side-effects from a failed evaluation. This is safe because
17732     // they can't interfere with any other argument evaluation.
17733     Info.EvalStatus.HasSideEffects = false;
17734   }
17735 
17736   // Parameter cleanups happen in the caller and are not part of this
17737   // evaluation.
17738   Info.discardCleanups();
17739   Info.EvalStatus.HasSideEffects = false;
17740 
17741   // Build fake call to Callee.
17742   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
17743                        Call);
17744   // FIXME: Missing ExprWithCleanups in enable_if conditions?
17745   FullExpressionRAII Scope(Info);
17746   return Evaluate(Value, Info, this) && Scope.destroy() &&
17747          !Info.EvalStatus.HasSideEffects;
17748 }
17749 
17750 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
17751                                    SmallVectorImpl<
17752                                      PartialDiagnosticAt> &Diags) {
17753   // FIXME: It would be useful to check constexpr function templates, but at the
17754   // moment the constant expression evaluator cannot cope with the non-rigorous
17755   // ASTs which we build for dependent expressions.
17756   if (FD->isDependentContext())
17757     return true;
17758 
17759   llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
17760     std::string Name;
17761     llvm::raw_string_ostream OS(Name);
17762     FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
17763                              /*Qualified=*/true);
17764     return Name;
17765   });
17766 
17767   Expr::EvalStatus Status;
17768   Status.Diag = &Diags;
17769 
17770   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
17771   Info.InConstantContext = true;
17772   Info.CheckingPotentialConstantExpression = true;
17773 
17774   // The constexpr VM attempts to compile all methods to bytecode here.
17775   if (Info.EnableNewConstInterp) {
17776     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
17777     return Diags.empty();
17778   }
17779 
17780   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
17781   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
17782 
17783   // Fabricate an arbitrary expression on the stack and pretend that it
17784   // is a temporary being used as the 'this' pointer.
17785   LValue This;
17786   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
17787   This.set({&VIE, Info.CurrentCall->Index});
17788 
17789   ArrayRef<const Expr*> Args;
17790 
17791   APValue Scratch;
17792   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
17793     // Evaluate the call as a constant initializer, to allow the construction
17794     // of objects of non-literal types.
17795     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
17796     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
17797   } else {
17798     SourceLocation Loc = FD->getLocation();
17799     HandleFunctionCall(
17800         Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17801         &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17802         /*ResultSlot=*/nullptr);
17803   }
17804 
17805   return Diags.empty();
17806 }
17807 
17808 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
17809                                               const FunctionDecl *FD,
17810                                               SmallVectorImpl<
17811                                                 PartialDiagnosticAt> &Diags) {
17812   assert(!E->isValueDependent() &&
17813          "Expression evaluator can't be called on a dependent expression.");
17814 
17815   Expr::EvalStatus Status;
17816   Status.Diag = &Diags;
17817 
17818   EvalInfo Info(FD->getASTContext(), Status,
17819                 EvalInfo::EM_ConstantExpressionUnevaluated);
17820   Info.InConstantContext = true;
17821   Info.CheckingPotentialConstantExpression = true;
17822 
17823   // Fabricate a call stack frame to give the arguments a plausible cover story.
17824   CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17825                        /*CallExpr=*/nullptr, CallRef());
17826 
17827   APValue ResultScratch;
17828   Evaluate(ResultScratch, Info, E);
17829   return Diags.empty();
17830 }
17831 
17832 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17833                                  unsigned Type) const {
17834   if (!getType()->isPointerType())
17835     return false;
17836 
17837   Expr::EvalStatus Status;
17838   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17839   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
17840 }
17841 
17842 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17843                                   EvalInfo &Info, std::string *StringResult) {
17844   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17845     return false;
17846 
17847   LValue String;
17848 
17849   if (!EvaluatePointer(E, String, Info))
17850     return false;
17851 
17852   QualType CharTy = E->getType()->getPointeeType();
17853 
17854   // Fast path: if it's a string literal, search the string value.
17855   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17856           String.getLValueBase().dyn_cast<const Expr *>())) {
17857     StringRef Str = S->getBytes();
17858     int64_t Off = String.Offset.getQuantity();
17859     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17860         S->getCharByteWidth() == 1 &&
17861         // FIXME: Add fast-path for wchar_t too.
17862         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
17863       Str = Str.substr(Off);
17864 
17865       StringRef::size_type Pos = Str.find(0);
17866       if (Pos != StringRef::npos)
17867         Str = Str.substr(0, Pos);
17868 
17869       Result = Str.size();
17870       if (StringResult)
17871         *StringResult = Str;
17872       return true;
17873     }
17874 
17875     // Fall through to slow path.
17876   }
17877 
17878   // Slow path: scan the bytes of the string looking for the terminating 0.
17879   for (uint64_t Strlen = 0; /**/; ++Strlen) {
17880     APValue Char;
17881     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
17882         !Char.isInt())
17883       return false;
17884     if (!Char.getInt()) {
17885       Result = Strlen;
17886       return true;
17887     } else if (StringResult)
17888       StringResult->push_back(Char.getInt().getExtValue());
17889     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
17890       return false;
17891   }
17892 }
17893 
17894 std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
17895   Expr::EvalStatus Status;
17896   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17897   uint64_t Result;
17898   std::string StringResult;
17899 
17900   if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
17901     return StringResult;
17902   return {};
17903 }
17904 
17905 bool Expr::EvaluateCharRangeAsString(std::string &Result,
17906                                      const Expr *SizeExpression,
17907                                      const Expr *PtrExpression, ASTContext &Ctx,
17908                                      EvalResult &Status) const {
17909   LValue String;
17910   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17911   Info.InConstantContext = true;
17912 
17913   FullExpressionRAII Scope(Info);
17914   APSInt SizeValue;
17915   if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
17916     return false;
17917 
17918   uint64_t Size = SizeValue.getZExtValue();
17919 
17920   if (!::EvaluatePointer(PtrExpression, String, Info))
17921     return false;
17922 
17923   QualType CharTy = PtrExpression->getType()->getPointeeType();
17924   for (uint64_t I = 0; I < Size; ++I) {
17925     APValue Char;
17926     if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
17927                                         Char))
17928       return false;
17929 
17930     APSInt C = Char.getInt();
17931     Result.push_back(static_cast<char>(C.getExtValue()));
17932     if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
17933       return false;
17934   }
17935   if (!Scope.destroy())
17936     return false;
17937 
17938   if (!CheckMemoryLeaks(Info))
17939     return false;
17940 
17941   return true;
17942 }
17943 
17944 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17945   Expr::EvalStatus Status;
17946   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17947   return EvaluateBuiltinStrLen(this, Result, Info);
17948 }
17949 
17950 namespace {
17951 struct IsWithinLifetimeHandler {
17952   EvalInfo &Info;
17953   static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
17954   using result_type = std::optional<bool>;
17955   std::optional<bool> failed() { return std::nullopt; }
17956   template <typename T>
17957   std::optional<bool> found(T &Subobj, QualType SubobjType) {
17958     return true;
17959   }
17960 };
17961 
17962 std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
17963                                                     const CallExpr *E) {
17964   EvalInfo &Info = IEE.Info;
17965   // Sometimes this is called during some sorts of constant folding / early
17966   // evaluation. These are meant for non-constant expressions and are not
17967   // necessary since this consteval builtin will never be evaluated at runtime.
17968   // Just fail to evaluate when not in a constant context.
17969   if (!Info.InConstantContext)
17970     return std::nullopt;
17971   assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
17972   const Expr *Arg = E->getArg(0);
17973   if (Arg->isValueDependent())
17974     return std::nullopt;
17975   LValue Val;
17976   if (!EvaluatePointer(Arg, Val, Info))
17977     return std::nullopt;
17978 
17979   if (Val.allowConstexprUnknown())
17980     return true;
17981 
17982   auto Error = [&](int Diag) {
17983     bool CalledFromStd = false;
17984     const auto *Callee = Info.CurrentCall->getCallee();
17985     if (Callee && Callee->isInStdNamespace()) {
17986       const IdentifierInfo *Identifier = Callee->getIdentifier();
17987       CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
17988     }
17989     Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
17990                                : E->getExprLoc(),
17991                  diag::err_invalid_is_within_lifetime)
17992         << (CalledFromStd ? "std::is_within_lifetime"
17993                           : "__builtin_is_within_lifetime")
17994         << Diag;
17995     return std::nullopt;
17996   };
17997   // C++2c [meta.const.eval]p4:
17998   //   During the evaluation of an expression E as a core constant expression, a
17999   //   call to this function is ill-formed unless p points to an object that is
18000   //   usable in constant expressions or whose complete object's lifetime began
18001   //   within E.
18002 
18003   // Make sure it points to an object
18004   // nullptr does not point to an object
18005   if (Val.isNullPointer() || Val.getLValueBase().isNull())
18006     return Error(0);
18007   QualType T = Val.getLValueBase().getType();
18008   assert(!T->isFunctionType() &&
18009          "Pointers to functions should have been typed as function pointers "
18010          "which would have been rejected earlier");
18011   assert(T->isObjectType());
18012   // Hypothetical array element is not an object
18013   if (Val.getLValueDesignator().isOnePastTheEnd())
18014     return Error(1);
18015   assert(Val.getLValueDesignator().isValidSubobject() &&
18016          "Unchecked case for valid subobject");
18017   // All other ill-formed values should have failed EvaluatePointer, so the
18018   // object should be a pointer to an object that is usable in a constant
18019   // expression or whose complete lifetime began within the expression
18020   CompleteObject CO =
18021       findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
18022   // The lifetime hasn't begun yet if we are still evaluating the
18023   // initializer ([basic.life]p(1.2))
18024   if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
18025     return Error(2);
18026 
18027   if (!CO)
18028     return false;
18029   IsWithinLifetimeHandler handler{Info};
18030   return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
18031 }
18032 } // namespace
18033