1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
81   static QualType getType(APValue::LValueBase B) {
82     return B.getType();
83   }
84 
85   /// Get an LValue path entry, which is known to not be an array index, as a
86   /// field declaration.
87   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89   }
90   /// Get an LValue path entry, which is known to not be an array index, as a
91   /// base class declaration.
92   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94   }
95   /// Determine whether this LValue path entry for a base class names a virtual
96   /// base class.
97   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98     return E.getAsBaseOrMember().getInt();
99   }
100 
101   /// Given an expression, determine the type used to store the result of
102   /// evaluating that expression.
103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isPRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
272     SubobjectDesignator() : Invalid(true) {}
273 
274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       // Pair (Key,Version) wasn't found in the map. Check that no elements
596       // in the map have 'Key' as their key.
597       assert((LB == Temporaries.end() || LB->first.first != Key) &&
598              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599              "Element with key 'Key' found in map");
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) override;
631 
632     Frame *getCaller() const override { return Caller; }
633     SourceLocation getCallLocation() const override { return CallLoc; }
634     const FunctionDecl *getCallee() const override { return Callee; }
635 
636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 }
664 
665 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666                               const LValue &This, QualType ThisType);
667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668                               APValue::LValueBase LVBase, APValue &Value,
669                               QualType T);
670 
671 namespace {
672   /// A cleanup, and a flag indicating whether it is lifetime-extended.
673   class Cleanup {
674     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675     APValue::LValueBase Base;
676     QualType T;
677 
678   public:
679     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680             ScopeKind Scope)
681         : Value(Val, Scope), Base(Base), T(T) {}
682 
683     /// Determine whether this cleanup should be performed at the end of the
684     /// given kind of scope.
685     bool isDestroyedAtEndOf(ScopeKind K) const {
686       return (int)Value.getInt() >= (int)K;
687     }
688     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689       if (RunDestructors) {
690         SourceLocation Loc;
691         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692           Loc = VD->getLocation();
693         else if (const Expr *E = Base.dyn_cast<const Expr*>())
694           Loc = E->getExprLoc();
695         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696       }
697       *Value.getPointer() = APValue();
698       return true;
699     }
700 
701     bool hasSideEffect() {
702       return T.isDestructedType();
703     }
704   };
705 
706   /// A reference to an object whose construction we are currently evaluating.
707   struct ObjectUnderConstruction {
708     APValue::LValueBase Base;
709     ArrayRef<APValue::LValuePathEntry> Path;
710     friend bool operator==(const ObjectUnderConstruction &LHS,
711                            const ObjectUnderConstruction &RHS) {
712       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713     }
714     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715       return llvm::hash_combine(Obj.Base, Obj.Path);
716     }
717   };
718   enum class ConstructionPhase {
719     None,
720     Bases,
721     AfterBases,
722     AfterFields,
723     Destroying,
724     DestroyingBases
725   };
726 }
727 
728 namespace llvm {
729 template<> struct DenseMapInfo<ObjectUnderConstruction> {
730   using Base = DenseMapInfo<APValue::LValueBase>;
731   static ObjectUnderConstruction getEmptyKey() {
732     return {Base::getEmptyKey(), {}}; }
733   static ObjectUnderConstruction getTombstoneKey() {
734     return {Base::getTombstoneKey(), {}};
735   }
736   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737     return hash_value(Object);
738   }
739   static bool isEqual(const ObjectUnderConstruction &LHS,
740                       const ObjectUnderConstruction &RHS) {
741     return LHS == RHS;
742   }
743 };
744 }
745 
746 namespace {
747   /// A dynamically-allocated heap object.
748   struct DynAlloc {
749     /// The value of this heap-allocated object.
750     APValue Value;
751     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752     /// or a CallExpr (the latter is for direct calls to operator new inside
753     /// std::allocator<T>::allocate).
754     const Expr *AllocExpr = nullptr;
755 
756     enum Kind {
757       New,
758       ArrayNew,
759       StdAllocator
760     };
761 
762     /// Get the kind of the allocation. This must match between allocation
763     /// and deallocation.
764     Kind getKind() const {
765       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766         return NE->isArray() ? ArrayNew : New;
767       assert(isa<CallExpr>(AllocExpr));
768       return StdAllocator;
769     }
770   };
771 
772   struct DynAllocOrder {
773     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774       return L.getIndex() < R.getIndex();
775     }
776   };
777 
778   /// EvalInfo - This is a private struct used by the evaluator to capture
779   /// information about a subexpression as it is folded.  It retains information
780   /// about the AST context, but also maintains information about the folded
781   /// expression.
782   ///
783   /// If an expression could be evaluated, it is still possible it is not a C
784   /// "integer constant expression" or constant expression.  If not, this struct
785   /// captures information about how and why not.
786   ///
787   /// One bit of information passed *into* the request for constant folding
788   /// indicates whether the subexpression is "evaluated" or not according to C
789   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790   /// evaluate the expression regardless of what the RHS is, but C only allows
791   /// certain things in certain situations.
792   class EvalInfo : public interp::State {
793   public:
794     ASTContext &Ctx;
795 
796     /// EvalStatus - Contains information about the evaluation.
797     Expr::EvalStatus &EvalStatus;
798 
799     /// CurrentCall - The top of the constexpr call stack.
800     CallStackFrame *CurrentCall;
801 
802     /// CallStackDepth - The number of calls in the call stack right now.
803     unsigned CallStackDepth;
804 
805     /// NextCallIndex - The next call index to assign.
806     unsigned NextCallIndex;
807 
808     /// StepsLeft - The remaining number of evaluation steps we're permitted
809     /// to perform. This is essentially a limit for the number of statements
810     /// we will evaluate.
811     unsigned StepsLeft;
812 
813     /// Enable the experimental new constant interpreter. If an expression is
814     /// not supported by the interpreter, an error is triggered.
815     bool EnableNewConstInterp;
816 
817     /// BottomFrame - The frame in which evaluation started. This must be
818     /// initialized after CurrentCall and CallStackDepth.
819     CallStackFrame BottomFrame;
820 
821     /// A stack of values whose lifetimes end at the end of some surrounding
822     /// evaluation frame.
823     llvm::SmallVector<Cleanup, 16> CleanupStack;
824 
825     /// EvaluatingDecl - This is the declaration whose initializer is being
826     /// evaluated, if any.
827     APValue::LValueBase EvaluatingDecl;
828 
829     enum class EvaluatingDeclKind {
830       None,
831       /// We're evaluating the construction of EvaluatingDecl.
832       Ctor,
833       /// We're evaluating the destruction of EvaluatingDecl.
834       Dtor,
835     };
836     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837 
838     /// EvaluatingDeclValue - This is the value being constructed for the
839     /// declaration whose initializer is being evaluated, if any.
840     APValue *EvaluatingDeclValue;
841 
842     /// Set of objects that are currently being constructed.
843     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844         ObjectsUnderConstruction;
845 
846     /// Current heap allocations, along with the location where each was
847     /// allocated. We use std::map here because we need stable addresses
848     /// for the stored APValues.
849     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850 
851     /// The number of heap allocations performed so far in this evaluation.
852     unsigned NumHeapAllocs = 0;
853 
854     struct EvaluatingConstructorRAII {
855       EvalInfo &EI;
856       ObjectUnderConstruction Object;
857       bool DidInsert;
858       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859                                 bool HasBases)
860           : EI(EI), Object(Object) {
861         DidInsert =
862             EI.ObjectsUnderConstruction
863                 .insert({Object, HasBases ? ConstructionPhase::Bases
864                                           : ConstructionPhase::AfterBases})
865                 .second;
866       }
867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
873       ~EvaluatingConstructorRAII() {
874         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875       }
876     };
877 
878     struct EvaluatingDestructorRAII {
879       EvalInfo &EI;
880       ObjectUnderConstruction Object;
881       bool DidInsert;
882       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883           : EI(EI), Object(Object) {
884         DidInsert = EI.ObjectsUnderConstruction
885                         .insert({Object, ConstructionPhase::Destroying})
886                         .second;
887       }
888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
892       ~EvaluatingDestructorRAII() {
893         if (DidInsert)
894           EI.ObjectsUnderConstruction.erase(Object);
895       }
896     };
897 
898     ConstructionPhase
899     isEvaluatingCtorDtor(APValue::LValueBase Base,
900                          ArrayRef<APValue::LValuePathEntry> Path) {
901       return ObjectsUnderConstruction.lookup({Base, Path});
902     }
903 
904     /// If we're currently speculatively evaluating, the outermost call stack
905     /// depth at which we can mutate state, otherwise 0.
906     unsigned SpeculativeEvaluationDepth = 0;
907 
908     /// The current array initialization index, if we're performing array
909     /// initialization.
910     uint64_t ArrayInitIndex = -1;
911 
912     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913     /// notes attached to it will also be stored, otherwise they will not be.
914     bool HasActiveDiagnostic;
915 
916     /// Have we emitted a diagnostic explaining why we couldn't constant
917     /// fold (not just why it's not strictly a constant expression)?
918     bool HasFoldFailureDiagnostic;
919 
920     /// Whether or not we're in a context where the front end requires a
921     /// constant value.
922     bool InConstantContext;
923 
924     /// Whether we're checking that an expression is a potential constant
925     /// expression. If so, do not fail on constructs that could become constant
926     /// later on (such as a use of an undefined global).
927     bool CheckingPotentialConstantExpression = false;
928 
929     /// Whether we're checking for an expression that has undefined behavior.
930     /// If so, we will produce warnings if we encounter an operation that is
931     /// always undefined.
932     ///
933     /// Note that we still need to evaluate the expression normally when this
934     /// is set; this is used when evaluating ICEs in C.
935     bool CheckingForUndefinedBehavior = false;
936 
937     enum EvaluationMode {
938       /// Evaluate as a constant expression. Stop if we find that the expression
939       /// is not a constant expression.
940       EM_ConstantExpression,
941 
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression. Some expressions can be retried in the
944       /// optimizer if we don't constant fold them here, but in an unevaluated
945       /// context we try to fold them immediately since the optimizer never
946       /// gets a chance to look at it.
947       EM_ConstantExpressionUnevaluated,
948 
949       /// Fold the expression to a constant. Stop if we hit a side-effect that
950       /// we can't model.
951       EM_ConstantFold,
952 
953       /// Evaluate in any way we know how. Don't worry about side-effects that
954       /// can't be modeled.
955       EM_IgnoreSideEffects,
956     } EvalMode;
957 
958     /// Are we checking whether the expression is a potential constant
959     /// expression?
960     bool checkingPotentialConstantExpression() const override  {
961       return CheckingPotentialConstantExpression;
962     }
963 
964     /// Are we checking an expression for overflow?
965     // FIXME: We should check for any kind of undefined or suspicious behavior
966     // in such constructs, not just overflow.
967     bool checkingForUndefinedBehavior() const override {
968       return CheckingForUndefinedBehavior;
969     }
970 
971     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973           CallStackDepth(0), NextCallIndex(1),
974           StepsLeft(C.getLangOpts().ConstexprStepLimit),
975           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977           EvaluatingDecl((const ValueDecl *)nullptr),
978           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979           HasFoldFailureDiagnostic(false), InConstantContext(false),
980           EvalMode(Mode) {}
981 
982     ~EvalInfo() {
983       discardCleanups();
984     }
985 
986     ASTContext &getCtx() const override { return Ctx; }
987 
988     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
989                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
990       EvaluatingDecl = Base;
991       IsEvaluatingDecl = EDK;
992       EvaluatingDeclValue = &Value;
993     }
994 
995     bool CheckCallLimit(SourceLocation Loc) {
996       // Don't perform any constexpr calls (other than the call we're checking)
997       // when checking a potential constant expression.
998       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
999         return false;
1000       if (NextCallIndex == 0) {
1001         // NextCallIndex has wrapped around.
1002         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1003         return false;
1004       }
1005       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1006         return true;
1007       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1008         << getLangOpts().ConstexprCallDepth;
1009       return false;
1010     }
1011 
1012     std::pair<CallStackFrame *, unsigned>
1013     getCallFrameAndDepth(unsigned CallIndex) {
1014       assert(CallIndex && "no call index in getCallFrameAndDepth");
1015       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1016       // be null in this loop.
1017       unsigned Depth = CallStackDepth;
1018       CallStackFrame *Frame = CurrentCall;
1019       while (Frame->Index > CallIndex) {
1020         Frame = Frame->Caller;
1021         --Depth;
1022       }
1023       if (Frame->Index == CallIndex)
1024         return {Frame, Depth};
1025       return {nullptr, 0};
1026     }
1027 
1028     bool nextStep(const Stmt *S) {
1029       if (!StepsLeft) {
1030         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1031         return false;
1032       }
1033       --StepsLeft;
1034       return true;
1035     }
1036 
1037     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1038 
1039     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1040       Optional<DynAlloc*> Result;
1041       auto It = HeapAllocs.find(DA);
1042       if (It != HeapAllocs.end())
1043         Result = &It->second;
1044       return Result;
1045     }
1046 
1047     /// Get the allocated storage for the given parameter of the given call.
1048     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1049       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1050       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1051                    : nullptr;
1052     }
1053 
1054     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1055     struct StdAllocatorCaller {
1056       unsigned FrameIndex;
1057       QualType ElemType;
1058       explicit operator bool() const { return FrameIndex != 0; };
1059     };
1060 
1061     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1062       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1063            Call = Call->Caller) {
1064         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1065         if (!MD)
1066           continue;
1067         const IdentifierInfo *FnII = MD->getIdentifier();
1068         if (!FnII || !FnII->isStr(FnName))
1069           continue;
1070 
1071         const auto *CTSD =
1072             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1073         if (!CTSD)
1074           continue;
1075 
1076         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1077         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1078         if (CTSD->isInStdNamespace() && ClassII &&
1079             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1080             TAL[0].getKind() == TemplateArgument::Type)
1081           return {Call->Index, TAL[0].getAsType()};
1082       }
1083 
1084       return {};
1085     }
1086 
1087     void performLifetimeExtension() {
1088       // Disable the cleanups for lifetime-extended temporaries.
1089       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1090         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1091       });
1092     }
1093 
1094     /// Throw away any remaining cleanups at the end of evaluation. If any
1095     /// cleanups would have had a side-effect, note that as an unmodeled
1096     /// side-effect and return false. Otherwise, return true.
1097     bool discardCleanups() {
1098       for (Cleanup &C : CleanupStack) {
1099         if (C.hasSideEffect() && !noteSideEffect()) {
1100           CleanupStack.clear();
1101           return false;
1102         }
1103       }
1104       CleanupStack.clear();
1105       return true;
1106     }
1107 
1108   private:
1109     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1110     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1111 
1112     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1113     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1114 
1115     void setFoldFailureDiagnostic(bool Flag) override {
1116       HasFoldFailureDiagnostic = Flag;
1117     }
1118 
1119     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1120 
1121     // If we have a prior diagnostic, it will be noting that the expression
1122     // isn't a constant expression. This diagnostic is more important,
1123     // unless we require this evaluation to produce a constant expression.
1124     //
1125     // FIXME: We might want to show both diagnostics to the user in
1126     // EM_ConstantFold mode.
1127     bool hasPriorDiagnostic() override {
1128       if (!EvalStatus.Diag->empty()) {
1129         switch (EvalMode) {
1130         case EM_ConstantFold:
1131         case EM_IgnoreSideEffects:
1132           if (!HasFoldFailureDiagnostic)
1133             break;
1134           // We've already failed to fold something. Keep that diagnostic.
1135           LLVM_FALLTHROUGH;
1136         case EM_ConstantExpression:
1137         case EM_ConstantExpressionUnevaluated:
1138           setActiveDiagnostic(false);
1139           return true;
1140         }
1141       }
1142       return false;
1143     }
1144 
1145     unsigned getCallStackDepth() override { return CallStackDepth; }
1146 
1147   public:
1148     /// Should we continue evaluation after encountering a side-effect that we
1149     /// couldn't model?
1150     bool keepEvaluatingAfterSideEffect() {
1151       switch (EvalMode) {
1152       case EM_IgnoreSideEffects:
1153         return true;
1154 
1155       case EM_ConstantExpression:
1156       case EM_ConstantExpressionUnevaluated:
1157       case EM_ConstantFold:
1158         // By default, assume any side effect might be valid in some other
1159         // evaluation of this expression from a different context.
1160         return checkingPotentialConstantExpression() ||
1161                checkingForUndefinedBehavior();
1162       }
1163       llvm_unreachable("Missed EvalMode case");
1164     }
1165 
1166     /// Note that we have had a side-effect, and determine whether we should
1167     /// keep evaluating.
1168     bool noteSideEffect() {
1169       EvalStatus.HasSideEffects = true;
1170       return keepEvaluatingAfterSideEffect();
1171     }
1172 
1173     /// Should we continue evaluation after encountering undefined behavior?
1174     bool keepEvaluatingAfterUndefinedBehavior() {
1175       switch (EvalMode) {
1176       case EM_IgnoreSideEffects:
1177       case EM_ConstantFold:
1178         return true;
1179 
1180       case EM_ConstantExpression:
1181       case EM_ConstantExpressionUnevaluated:
1182         return checkingForUndefinedBehavior();
1183       }
1184       llvm_unreachable("Missed EvalMode case");
1185     }
1186 
1187     /// Note that we hit something that was technically undefined behavior, but
1188     /// that we can evaluate past it (such as signed overflow or floating-point
1189     /// division by zero.)
1190     bool noteUndefinedBehavior() override {
1191       EvalStatus.HasUndefinedBehavior = true;
1192       return keepEvaluatingAfterUndefinedBehavior();
1193     }
1194 
1195     /// Should we continue evaluation as much as possible after encountering a
1196     /// construct which can't be reduced to a value?
1197     bool keepEvaluatingAfterFailure() const override {
1198       if (!StepsLeft)
1199         return false;
1200 
1201       switch (EvalMode) {
1202       case EM_ConstantExpression:
1203       case EM_ConstantExpressionUnevaluated:
1204       case EM_ConstantFold:
1205       case EM_IgnoreSideEffects:
1206         return checkingPotentialConstantExpression() ||
1207                checkingForUndefinedBehavior();
1208       }
1209       llvm_unreachable("Missed EvalMode case");
1210     }
1211 
1212     /// Notes that we failed to evaluate an expression that other expressions
1213     /// directly depend on, and determine if we should keep evaluating. This
1214     /// should only be called if we actually intend to keep evaluating.
1215     ///
1216     /// Call noteSideEffect() instead if we may be able to ignore the value that
1217     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218     ///
1219     /// (Foo(), 1)      // use noteSideEffect
1220     /// (Foo() || true) // use noteSideEffect
1221     /// Foo() + 1       // use noteFailure
1222     LLVM_NODISCARD bool noteFailure() {
1223       // Failure when evaluating some expression often means there is some
1224       // subexpression whose evaluation was skipped. Therefore, (because we
1225       // don't track whether we skipped an expression when unwinding after an
1226       // evaluation failure) every evaluation failure that bubbles up from a
1227       // subexpression implies that a side-effect has potentially happened. We
1228       // skip setting the HasSideEffects flag to true until we decide to
1229       // continue evaluating after that point, which happens here.
1230       bool KeepGoing = keepEvaluatingAfterFailure();
1231       EvalStatus.HasSideEffects |= KeepGoing;
1232       return KeepGoing;
1233     }
1234 
1235     class ArrayInitLoopIndex {
1236       EvalInfo &Info;
1237       uint64_t OuterIndex;
1238 
1239     public:
1240       ArrayInitLoopIndex(EvalInfo &Info)
1241           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242         Info.ArrayInitIndex = 0;
1243       }
1244       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245 
1246       operator uint64_t&() { return Info.ArrayInitIndex; }
1247     };
1248   };
1249 
1250   /// Object used to treat all foldable expressions as constant expressions.
1251   struct FoldConstant {
1252     EvalInfo &Info;
1253     bool Enabled;
1254     bool HadNoPriorDiags;
1255     EvalInfo::EvaluationMode OldMode;
1256 
1257     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258       : Info(Info),
1259         Enabled(Enabled),
1260         HadNoPriorDiags(Info.EvalStatus.Diag &&
1261                         Info.EvalStatus.Diag->empty() &&
1262                         !Info.EvalStatus.HasSideEffects),
1263         OldMode(Info.EvalMode) {
1264       if (Enabled)
1265         Info.EvalMode = EvalInfo::EM_ConstantFold;
1266     }
1267     void keepDiagnostics() { Enabled = false; }
1268     ~FoldConstant() {
1269       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1270           !Info.EvalStatus.HasSideEffects)
1271         Info.EvalStatus.Diag->clear();
1272       Info.EvalMode = OldMode;
1273     }
1274   };
1275 
1276   /// RAII object used to set the current evaluation mode to ignore
1277   /// side-effects.
1278   struct IgnoreSideEffectsRAII {
1279     EvalInfo &Info;
1280     EvalInfo::EvaluationMode OldMode;
1281     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282         : Info(Info), OldMode(Info.EvalMode) {
1283       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284     }
1285 
1286     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287   };
1288 
1289   /// RAII object used to optionally suppress diagnostics and side-effects from
1290   /// a speculative evaluation.
1291   class SpeculativeEvaluationRAII {
1292     EvalInfo *Info = nullptr;
1293     Expr::EvalStatus OldStatus;
1294     unsigned OldSpeculativeEvaluationDepth;
1295 
1296     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297       Info = Other.Info;
1298       OldStatus = Other.OldStatus;
1299       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300       Other.Info = nullptr;
1301     }
1302 
1303     void maybeRestoreState() {
1304       if (!Info)
1305         return;
1306 
1307       Info->EvalStatus = OldStatus;
1308       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309     }
1310 
1311   public:
1312     SpeculativeEvaluationRAII() = default;
1313 
1314     SpeculativeEvaluationRAII(
1315         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316         : Info(&Info), OldStatus(Info.EvalStatus),
1317           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318       Info.EvalStatus.Diag = NewDiag;
1319       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320     }
1321 
1322     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1323     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324       moveFromAndCancel(std::move(Other));
1325     }
1326 
1327     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328       maybeRestoreState();
1329       moveFromAndCancel(std::move(Other));
1330       return *this;
1331     }
1332 
1333     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334   };
1335 
1336   /// RAII object wrapping a full-expression or block scope, and handling
1337   /// the ending of the lifetime of temporaries created within it.
1338   template<ScopeKind Kind>
1339   class ScopeRAII {
1340     EvalInfo &Info;
1341     unsigned OldStackSize;
1342   public:
1343     ScopeRAII(EvalInfo &Info)
1344         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345       // Push a new temporary version. This is needed to distinguish between
1346       // temporaries created in different iterations of a loop.
1347       Info.CurrentCall->pushTempVersion();
1348     }
1349     bool destroy(bool RunDestructors = true) {
1350       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351       OldStackSize = -1U;
1352       return OK;
1353     }
1354     ~ScopeRAII() {
1355       if (OldStackSize != -1U)
1356         destroy(false);
1357       // Body moved to a static method to encourage the compiler to inline away
1358       // instances of this class.
1359       Info.CurrentCall->popTempVersion();
1360     }
1361   private:
1362     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363                         unsigned OldStackSize) {
1364       assert(OldStackSize <= Info.CleanupStack.size() &&
1365              "running cleanups out of order?");
1366 
1367       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368       // for a full-expression scope.
1369       bool Success = true;
1370       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1371         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373             Success = false;
1374             break;
1375           }
1376         }
1377       }
1378 
1379       // Compact any retained cleanups.
1380       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381       if (Kind != ScopeKind::Block)
1382         NewEnd =
1383             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384               return C.isDestroyedAtEndOf(Kind);
1385             });
1386       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387       return Success;
1388     }
1389   };
1390   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393 }
1394 
1395 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396                                          CheckSubobjectKind CSK) {
1397   if (Invalid)
1398     return false;
1399   if (isOnePastTheEnd()) {
1400     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401       << CSK;
1402     setInvalid();
1403     return false;
1404   }
1405   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406   // must actually be at least one array element; even a VLA cannot have a
1407   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408   return true;
1409 }
1410 
1411 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412                                                                 const Expr *E) {
1413   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414   // Do not set the designator as invalid: we can represent this situation,
1415   // and correct handling of __builtin_object_size requires us to do so.
1416 }
1417 
1418 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419                                                     const Expr *E,
1420                                                     const APSInt &N) {
1421   // If we're complaining, we must be able to statically determine the size of
1422   // the most derived array.
1423   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1424     Info.CCEDiag(E, diag::note_constexpr_array_index)
1425       << N << /*array*/ 0
1426       << static_cast<unsigned>(getMostDerivedArraySize());
1427   else
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*non-array*/ 1;
1430   setInvalid();
1431 }
1432 
1433 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434                                const FunctionDecl *Callee, const LValue *This,
1435                                CallRef Call)
1436     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438   Info.CurrentCall = this;
1439   ++Info.CallStackDepth;
1440 }
1441 
1442 CallStackFrame::~CallStackFrame() {
1443   assert(Info.CurrentCall == this && "calls retired out of order");
1444   --Info.CallStackDepth;
1445   Info.CurrentCall = Caller;
1446 }
1447 
1448 static bool isRead(AccessKinds AK) {
1449   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1450 }
1451 
1452 static bool isModification(AccessKinds AK) {
1453   switch (AK) {
1454   case AK_Read:
1455   case AK_ReadObjectRepresentation:
1456   case AK_MemberCall:
1457   case AK_DynamicCast:
1458   case AK_TypeId:
1459     return false;
1460   case AK_Assign:
1461   case AK_Increment:
1462   case AK_Decrement:
1463   case AK_Construct:
1464   case AK_Destroy:
1465     return true;
1466   }
1467   llvm_unreachable("unknown access kind");
1468 }
1469 
1470 static bool isAnyAccess(AccessKinds AK) {
1471   return isRead(AK) || isModification(AK);
1472 }
1473 
1474 /// Is this an access per the C++ definition?
1475 static bool isFormalAccess(AccessKinds AK) {
1476   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1477 }
1478 
1479 /// Is this kind of axcess valid on an indeterminate object value?
1480 static bool isValidIndeterminateAccess(AccessKinds AK) {
1481   switch (AK) {
1482   case AK_Read:
1483   case AK_Increment:
1484   case AK_Decrement:
1485     // These need the object's value.
1486     return false;
1487 
1488   case AK_ReadObjectRepresentation:
1489   case AK_Assign:
1490   case AK_Construct:
1491   case AK_Destroy:
1492     // Construction and destruction don't need the value.
1493     return true;
1494 
1495   case AK_MemberCall:
1496   case AK_DynamicCast:
1497   case AK_TypeId:
1498     // These aren't really meaningful on scalars.
1499     return true;
1500   }
1501   llvm_unreachable("unknown access kind");
1502 }
1503 
1504 namespace {
1505   struct ComplexValue {
1506   private:
1507     bool IsInt;
1508 
1509   public:
1510     APSInt IntReal, IntImag;
1511     APFloat FloatReal, FloatImag;
1512 
1513     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514 
1515     void makeComplexFloat() { IsInt = false; }
1516     bool isComplexFloat() const { return !IsInt; }
1517     APFloat &getComplexFloatReal() { return FloatReal; }
1518     APFloat &getComplexFloatImag() { return FloatImag; }
1519 
1520     void makeComplexInt() { IsInt = true; }
1521     bool isComplexInt() const { return IsInt; }
1522     APSInt &getComplexIntReal() { return IntReal; }
1523     APSInt &getComplexIntImag() { return IntImag; }
1524 
1525     void moveInto(APValue &v) const {
1526       if (isComplexFloat())
1527         v = APValue(FloatReal, FloatImag);
1528       else
1529         v = APValue(IntReal, IntImag);
1530     }
1531     void setFrom(const APValue &v) {
1532       assert(v.isComplexFloat() || v.isComplexInt());
1533       if (v.isComplexFloat()) {
1534         makeComplexFloat();
1535         FloatReal = v.getComplexFloatReal();
1536         FloatImag = v.getComplexFloatImag();
1537       } else {
1538         makeComplexInt();
1539         IntReal = v.getComplexIntReal();
1540         IntImag = v.getComplexIntImag();
1541       }
1542     }
1543   };
1544 
1545   struct LValue {
1546     APValue::LValueBase Base;
1547     CharUnits Offset;
1548     SubobjectDesignator Designator;
1549     bool IsNullPtr : 1;
1550     bool InvalidBase : 1;
1551 
1552     const APValue::LValueBase getLValueBase() const { return Base; }
1553     CharUnits &getLValueOffset() { return Offset; }
1554     const CharUnits &getLValueOffset() const { return Offset; }
1555     SubobjectDesignator &getLValueDesignator() { return Designator; }
1556     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1557     bool isNullPointer() const { return IsNullPtr;}
1558 
1559     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1560     unsigned getLValueVersion() const { return Base.getVersion(); }
1561 
1562     void moveInto(APValue &V) const {
1563       if (Designator.Invalid)
1564         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565       else {
1566         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1567         V = APValue(Base, Offset, Designator.Entries,
1568                     Designator.IsOnePastTheEnd, IsNullPtr);
1569       }
1570     }
1571     void setFrom(ASTContext &Ctx, const APValue &V) {
1572       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1573       Base = V.getLValueBase();
1574       Offset = V.getLValueOffset();
1575       InvalidBase = false;
1576       Designator = SubobjectDesignator(Ctx, V);
1577       IsNullPtr = V.isNullPointer();
1578     }
1579 
1580     void set(APValue::LValueBase B, bool BInvalid = false) {
1581 #ifndef NDEBUG
1582       // We only allow a few types of invalid bases. Enforce that here.
1583       if (BInvalid) {
1584         const auto *E = B.get<const Expr *>();
1585         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1586                "Unexpected type of invalid base");
1587       }
1588 #endif
1589 
1590       Base = B;
1591       Offset = CharUnits::fromQuantity(0);
1592       InvalidBase = BInvalid;
1593       Designator = SubobjectDesignator(getType(B));
1594       IsNullPtr = false;
1595     }
1596 
1597     void setNull(ASTContext &Ctx, QualType PointerTy) {
1598       Base = (const ValueDecl *)nullptr;
1599       Offset =
1600           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601       InvalidBase = false;
1602       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603       IsNullPtr = true;
1604     }
1605 
1606     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607       set(B, true);
1608     }
1609 
1610     std::string toString(ASTContext &Ctx, QualType T) const {
1611       APValue Printable;
1612       moveInto(Printable);
1613       return Printable.getAsString(Ctx, T);
1614     }
1615 
1616   private:
1617     // Check that this LValue is not based on a null pointer. If it is, produce
1618     // a diagnostic and mark the designator as invalid.
1619     template <typename GenDiagType>
1620     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621       if (Designator.Invalid)
1622         return false;
1623       if (IsNullPtr) {
1624         GenDiag();
1625         Designator.setInvalid();
1626         return false;
1627       }
1628       return true;
1629     }
1630 
1631   public:
1632     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633                           CheckSubobjectKind CSK) {
1634       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636       });
1637     }
1638 
1639     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640                                        AccessKinds AK) {
1641       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643       });
1644     }
1645 
1646     // Check this LValue refers to an object. If not, set the designator to be
1647     // invalid and emit a diagnostic.
1648     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1650              Designator.checkSubobject(Info, E, CSK);
1651     }
1652 
1653     void addDecl(EvalInfo &Info, const Expr *E,
1654                  const Decl *D, bool Virtual = false) {
1655       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1656         Designator.addDeclUnchecked(D, Virtual);
1657     }
1658     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659       if (!Designator.Entries.empty()) {
1660         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661         Designator.setInvalid();
1662         return;
1663       }
1664       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1666         Designator.FirstEntryIsAnUnsizedArray = true;
1667         Designator.addUnsizedArrayUnchecked(ElemTy);
1668       }
1669     }
1670     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672         Designator.addArrayUnchecked(CAT);
1673     }
1674     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1676         Designator.addComplexUnchecked(EltTy, Imag);
1677     }
1678     void clearIsNullPointer() {
1679       IsNullPtr = false;
1680     }
1681     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682                               const APSInt &Index, CharUnits ElementSize) {
1683       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684       // but we're not required to diagnose it and it's valid in C++.)
1685       if (!Index)
1686         return;
1687 
1688       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690       // offsets.
1691       uint64_t Offset64 = Offset.getQuantity();
1692       uint64_t ElemSize64 = ElementSize.getQuantity();
1693       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695 
1696       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697         Designator.adjustIndex(Info, E, Index);
1698       clearIsNullPointer();
1699     }
1700     void adjustOffset(CharUnits N) {
1701       Offset += N;
1702       if (N.getQuantity())
1703         clearIsNullPointer();
1704     }
1705   };
1706 
1707   struct MemberPtr {
1708     MemberPtr() {}
1709     explicit MemberPtr(const ValueDecl *Decl)
1710         : DeclAndIsDerivedMember(Decl, false) {}
1711 
1712     /// The member or (direct or indirect) field referred to by this member
1713     /// pointer, or 0 if this is a null member pointer.
1714     const ValueDecl *getDecl() const {
1715       return DeclAndIsDerivedMember.getPointer();
1716     }
1717     /// Is this actually a member of some type derived from the relevant class?
1718     bool isDerivedMember() const {
1719       return DeclAndIsDerivedMember.getInt();
1720     }
1721     /// Get the class which the declaration actually lives in.
1722     const CXXRecordDecl *getContainingRecord() const {
1723       return cast<CXXRecordDecl>(
1724           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725     }
1726 
1727     void moveInto(APValue &V) const {
1728       V = APValue(getDecl(), isDerivedMember(), Path);
1729     }
1730     void setFrom(const APValue &V) {
1731       assert(V.isMemberPointer());
1732       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734       Path.clear();
1735       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736       Path.insert(Path.end(), P.begin(), P.end());
1737     }
1738 
1739     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740     /// whether the member is a member of some class derived from the class type
1741     /// of the member pointer.
1742     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743     /// Path - The path of base/derived classes from the member declaration's
1744     /// class (exclusive) to the class type of the member pointer (inclusive).
1745     SmallVector<const CXXRecordDecl*, 4> Path;
1746 
1747     /// Perform a cast towards the class of the Decl (either up or down the
1748     /// hierarchy).
1749     bool castBack(const CXXRecordDecl *Class) {
1750       assert(!Path.empty());
1751       const CXXRecordDecl *Expected;
1752       if (Path.size() >= 2)
1753         Expected = Path[Path.size() - 2];
1754       else
1755         Expected = getContainingRecord();
1756       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758         // if B does not contain the original member and is not a base or
1759         // derived class of the class containing the original member, the result
1760         // of the cast is undefined.
1761         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762         // (D::*). We consider that to be a language defect.
1763         return false;
1764       }
1765       Path.pop_back();
1766       return true;
1767     }
1768     /// Perform a base-to-derived member pointer cast.
1769     bool castToDerived(const CXXRecordDecl *Derived) {
1770       if (!getDecl())
1771         return true;
1772       if (!isDerivedMember()) {
1773         Path.push_back(Derived);
1774         return true;
1775       }
1776       if (!castBack(Derived))
1777         return false;
1778       if (Path.empty())
1779         DeclAndIsDerivedMember.setInt(false);
1780       return true;
1781     }
1782     /// Perform a derived-to-base member pointer cast.
1783     bool castToBase(const CXXRecordDecl *Base) {
1784       if (!getDecl())
1785         return true;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(true);
1788       if (isDerivedMember()) {
1789         Path.push_back(Base);
1790         return true;
1791       }
1792       return castBack(Base);
1793     }
1794   };
1795 
1796   /// Compare two member pointers, which are assumed to be of the same type.
1797   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798     if (!LHS.getDecl() || !RHS.getDecl())
1799       return !LHS.getDecl() && !RHS.getDecl();
1800     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801       return false;
1802     return LHS.Path == RHS.Path;
1803   }
1804 }
1805 
1806 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808                             const LValue &This, const Expr *E,
1809                             bool AllowNonLiteralTypes = false);
1810 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811                            bool InvalidBaseOK = false);
1812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813                             bool InvalidBaseOK = false);
1814 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815                                   EvalInfo &Info);
1816 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819                                     EvalInfo &Info);
1820 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823                            EvalInfo &Info);
1824 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826                                   EvalInfo &Info);
1827 
1828 /// Evaluate an integer or fixed point expression into an APResult.
1829 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830                                         EvalInfo &Info);
1831 
1832 /// Evaluate only a fixed point expression into an APResult.
1833 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834                                EvalInfo &Info);
1835 
1836 //===----------------------------------------------------------------------===//
1837 // Misc utilities
1838 //===----------------------------------------------------------------------===//
1839 
1840 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1841 /// preserving its value (by extending by up to one bit as needed).
1842 static void negateAsSigned(APSInt &Int) {
1843   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1844     Int = Int.extend(Int.getBitWidth() + 1);
1845     Int.setIsSigned(true);
1846   }
1847   Int = -Int;
1848 }
1849 
1850 template<typename KeyT>
1851 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852                                          ScopeKind Scope, LValue &LV) {
1853   unsigned Version = getTempVersion();
1854   APValue::LValueBase Base(Key, Index, Version);
1855   LV.set(Base);
1856   return createLocal(Base, Key, T, Scope);
1857 }
1858 
1859 /// Allocate storage for a parameter of a function call made in this frame.
1860 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861                                      LValue &LV) {
1862   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1863   APValue::LValueBase Base(PVD, Index, Args.Version);
1864   LV.set(Base);
1865   // We always destroy parameters at the end of the call, even if we'd allow
1866   // them to live to the end of the full-expression at runtime, in order to
1867   // give portable results and match other compilers.
1868   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869 }
1870 
1871 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872                                      QualType T, ScopeKind Scope) {
1873   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1874   unsigned Version = Base.getVersion();
1875   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876   assert(Result.isAbsent() && "local created multiple times");
1877 
1878   // If we're creating a local immediately in the operand of a speculative
1879   // evaluation, don't register a cleanup to be run outside the speculative
1880   // evaluation context, since we won't actually be able to initialize this
1881   // object.
1882   if (Index <= Info.SpeculativeEvaluationDepth) {
1883     if (T.isDestructedType())
1884       Info.noteSideEffect();
1885   } else {
1886     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887   }
1888   return Result;
1889 }
1890 
1891 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894     return nullptr;
1895   }
1896 
1897   DynamicAllocLValue DA(NumHeapAllocs++);
1898   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900                                    std::forward_as_tuple(DA), std::tuple<>());
1901   assert(Result.second && "reused a heap alloc index?");
1902   Result.first->second.AllocExpr = E;
1903   return &Result.first->second.Value;
1904 }
1905 
1906 /// Produce a string describing the given constexpr call.
1907 void CallStackFrame::describe(raw_ostream &Out) {
1908   unsigned ArgIndex = 0;
1909   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910                       !isa<CXXConstructorDecl>(Callee) &&
1911                       cast<CXXMethodDecl>(Callee)->isInstance();
1912 
1913   if (!IsMemberCall)
1914     Out << *Callee << '(';
1915 
1916   if (This && IsMemberCall) {
1917     APValue Val;
1918     This->moveInto(Val);
1919     Val.printPretty(Out, Info.Ctx,
1920                     This->Designator.MostDerivedType);
1921     // FIXME: Add parens around Val if needed.
1922     Out << "->" << *Callee << '(';
1923     IsMemberCall = false;
1924   }
1925 
1926   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1928     if (ArgIndex > (unsigned)IsMemberCall)
1929       Out << ", ";
1930 
1931     const ParmVarDecl *Param = *I;
1932     APValue *V = Info.getParamSlot(Arguments, Param);
1933     if (V)
1934       V->printPretty(Out, Info.Ctx, Param->getType());
1935     else
1936       Out << "<...>";
1937 
1938     if (ArgIndex == 0 && IsMemberCall)
1939       Out << "->" << *Callee << '(';
1940   }
1941 
1942   Out << ')';
1943 }
1944 
1945 /// Evaluate an expression to see if it had side-effects, and discard its
1946 /// result.
1947 /// \return \c true if the caller should keep evaluating.
1948 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949   assert(!E->isValueDependent());
1950   APValue Scratch;
1951   if (!Evaluate(Scratch, Info, E))
1952     // We don't need the value, but we might have skipped a side effect here.
1953     return Info.noteSideEffect();
1954   return true;
1955 }
1956 
1957 /// Should this call expression be treated as a constant?
1958 static bool IsConstantCall(const CallExpr *E) {
1959   unsigned Builtin = E->getBuiltinCallee();
1960   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961           Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1962           Builtin == Builtin::BI__builtin_function_start);
1963 }
1964 
1965 static bool IsGlobalLValue(APValue::LValueBase B) {
1966   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967   // constant expression of pointer type that evaluates to...
1968 
1969   // ... a null pointer value, or a prvalue core constant expression of type
1970   // std::nullptr_t.
1971   if (!B) return true;
1972 
1973   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974     // ... the address of an object with static storage duration,
1975     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976       return VD->hasGlobalStorage();
1977     if (isa<TemplateParamObjectDecl>(D))
1978       return true;
1979     // ... the address of a function,
1980     // ... the address of a GUID [MS extension],
1981     // ... the address of an unnamed global constant
1982     return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1983   }
1984 
1985   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1986     return true;
1987 
1988   const Expr *E = B.get<const Expr*>();
1989   switch (E->getStmtClass()) {
1990   default:
1991     return false;
1992   case Expr::CompoundLiteralExprClass: {
1993     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1994     return CLE->isFileScope() && CLE->isLValue();
1995   }
1996   case Expr::MaterializeTemporaryExprClass:
1997     // A materialized temporary might have been lifetime-extended to static
1998     // storage duration.
1999     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2000   // A string literal has static storage duration.
2001   case Expr::StringLiteralClass:
2002   case Expr::PredefinedExprClass:
2003   case Expr::ObjCStringLiteralClass:
2004   case Expr::ObjCEncodeExprClass:
2005     return true;
2006   case Expr::ObjCBoxedExprClass:
2007     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2008   case Expr::CallExprClass:
2009     return IsConstantCall(cast<CallExpr>(E));
2010   // For GCC compatibility, &&label has static storage duration.
2011   case Expr::AddrLabelExprClass:
2012     return true;
2013   // A Block literal expression may be used as the initialization value for
2014   // Block variables at global or local static scope.
2015   case Expr::BlockExprClass:
2016     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2017   // The APValue generated from a __builtin_source_location will be emitted as a
2018   // literal.
2019   case Expr::SourceLocExprClass:
2020     return true;
2021   case Expr::ImplicitValueInitExprClass:
2022     // FIXME:
2023     // We can never form an lvalue with an implicit value initialization as its
2024     // base through expression evaluation, so these only appear in one case: the
2025     // implicit variable declaration we invent when checking whether a constexpr
2026     // constructor can produce a constant expression. We must assume that such
2027     // an expression might be a global lvalue.
2028     return true;
2029   }
2030 }
2031 
2032 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2033   return LVal.Base.dyn_cast<const ValueDecl*>();
2034 }
2035 
2036 static bool IsLiteralLValue(const LValue &Value) {
2037   if (Value.getLValueCallIndex())
2038     return false;
2039   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2040   return E && !isa<MaterializeTemporaryExpr>(E);
2041 }
2042 
2043 static bool IsWeakLValue(const LValue &Value) {
2044   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045   return Decl && Decl->isWeak();
2046 }
2047 
2048 static bool isZeroSized(const LValue &Value) {
2049   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2050   if (Decl && isa<VarDecl>(Decl)) {
2051     QualType Ty = Decl->getType();
2052     if (Ty->isArrayType())
2053       return Ty->isIncompleteType() ||
2054              Decl->getASTContext().getTypeSize(Ty) == 0;
2055   }
2056   return false;
2057 }
2058 
2059 static bool HasSameBase(const LValue &A, const LValue &B) {
2060   if (!A.getLValueBase())
2061     return !B.getLValueBase();
2062   if (!B.getLValueBase())
2063     return false;
2064 
2065   if (A.getLValueBase().getOpaqueValue() !=
2066       B.getLValueBase().getOpaqueValue())
2067     return false;
2068 
2069   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2070          A.getLValueVersion() == B.getLValueVersion();
2071 }
2072 
2073 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2074   assert(Base && "no location for a null lvalue");
2075   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2076 
2077   // For a parameter, find the corresponding call stack frame (if it still
2078   // exists), and point at the parameter of the function definition we actually
2079   // invoked.
2080   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2081     unsigned Idx = PVD->getFunctionScopeIndex();
2082     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2083       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2084           F->Arguments.Version == Base.getVersion() && F->Callee &&
2085           Idx < F->Callee->getNumParams()) {
2086         VD = F->Callee->getParamDecl(Idx);
2087         break;
2088       }
2089     }
2090   }
2091 
2092   if (VD)
2093     Info.Note(VD->getLocation(), diag::note_declared_at);
2094   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2095     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2096   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2097     // FIXME: Produce a note for dangling pointers too.
2098     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2099       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2100                 diag::note_constexpr_dynamic_alloc_here);
2101   }
2102   // We have no information to show for a typeid(T) object.
2103 }
2104 
2105 enum class CheckEvaluationResultKind {
2106   ConstantExpression,
2107   FullyInitialized,
2108 };
2109 
2110 /// Materialized temporaries that we've already checked to determine if they're
2111 /// initializsed by a constant expression.
2112 using CheckedTemporaries =
2113     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2114 
2115 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2116                                   EvalInfo &Info, SourceLocation DiagLoc,
2117                                   QualType Type, const APValue &Value,
2118                                   ConstantExprKind Kind,
2119                                   SourceLocation SubobjectLoc,
2120                                   CheckedTemporaries &CheckedTemps);
2121 
2122 /// Check that this reference or pointer core constant expression is a valid
2123 /// value for an address or reference constant expression. Return true if we
2124 /// can fold this expression, whether or not it's a constant expression.
2125 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2126                                           QualType Type, const LValue &LVal,
2127                                           ConstantExprKind Kind,
2128                                           CheckedTemporaries &CheckedTemps) {
2129   bool IsReferenceType = Type->isReferenceType();
2130 
2131   APValue::LValueBase Base = LVal.getLValueBase();
2132   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2133 
2134   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2135   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2136 
2137   // Additional restrictions apply in a template argument. We only enforce the
2138   // C++20 restrictions here; additional syntactic and semantic restrictions
2139   // are applied elsewhere.
2140   if (isTemplateArgument(Kind)) {
2141     int InvalidBaseKind = -1;
2142     StringRef Ident;
2143     if (Base.is<TypeInfoLValue>())
2144       InvalidBaseKind = 0;
2145     else if (isa_and_nonnull<StringLiteral>(BaseE))
2146       InvalidBaseKind = 1;
2147     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2148              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2149       InvalidBaseKind = 2;
2150     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2151       InvalidBaseKind = 3;
2152       Ident = PE->getIdentKindName();
2153     }
2154 
2155     if (InvalidBaseKind != -1) {
2156       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2157           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2158           << Ident;
2159       return false;
2160     }
2161   }
2162 
2163   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2164     if (FD->isConsteval()) {
2165       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2166           << !Type->isAnyPointerType();
2167       Info.Note(FD->getLocation(), diag::note_declared_at);
2168       return false;
2169     }
2170   }
2171 
2172   // Check that the object is a global. Note that the fake 'this' object we
2173   // manufacture when checking potential constant expressions is conservatively
2174   // assumed to be global here.
2175   if (!IsGlobalLValue(Base)) {
2176     if (Info.getLangOpts().CPlusPlus11) {
2177       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2178       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2179         << IsReferenceType << !Designator.Entries.empty()
2180         << !!VD << VD;
2181 
2182       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2183       if (VarD && VarD->isConstexpr()) {
2184         // Non-static local constexpr variables have unintuitive semantics:
2185         //   constexpr int a = 1;
2186         //   constexpr const int *p = &a;
2187         // ... is invalid because the address of 'a' is not constant. Suggest
2188         // adding a 'static' in this case.
2189         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2190             << VarD
2191             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2192       } else {
2193         NoteLValueLocation(Info, Base);
2194       }
2195     } else {
2196       Info.FFDiag(Loc);
2197     }
2198     // Don't allow references to temporaries to escape.
2199     return false;
2200   }
2201   assert((Info.checkingPotentialConstantExpression() ||
2202           LVal.getLValueCallIndex() == 0) &&
2203          "have call index for global lvalue");
2204 
2205   if (Base.is<DynamicAllocLValue>()) {
2206     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2207         << IsReferenceType << !Designator.Entries.empty();
2208     NoteLValueLocation(Info, Base);
2209     return false;
2210   }
2211 
2212   if (BaseVD) {
2213     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2214       // Check if this is a thread-local variable.
2215       if (Var->getTLSKind())
2216         // FIXME: Diagnostic!
2217         return false;
2218 
2219       // A dllimport variable never acts like a constant, unless we're
2220       // evaluating a value for use only in name mangling.
2221       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2222         // FIXME: Diagnostic!
2223         return false;
2224 
2225       // In CUDA/HIP device compilation, only device side variables have
2226       // constant addresses.
2227       if (Info.getCtx().getLangOpts().CUDA &&
2228           Info.getCtx().getLangOpts().CUDAIsDevice &&
2229           Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2230         if ((!Var->hasAttr<CUDADeviceAttr>() &&
2231              !Var->hasAttr<CUDAConstantAttr>() &&
2232              !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2233              !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2234             Var->hasAttr<HIPManagedAttr>())
2235           return false;
2236       }
2237     }
2238     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2239       // __declspec(dllimport) must be handled very carefully:
2240       // We must never initialize an expression with the thunk in C++.
2241       // Doing otherwise would allow the same id-expression to yield
2242       // different addresses for the same function in different translation
2243       // units.  However, this means that we must dynamically initialize the
2244       // expression with the contents of the import address table at runtime.
2245       //
2246       // The C language has no notion of ODR; furthermore, it has no notion of
2247       // dynamic initialization.  This means that we are permitted to
2248       // perform initialization with the address of the thunk.
2249       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2250           FD->hasAttr<DLLImportAttr>())
2251         // FIXME: Diagnostic!
2252         return false;
2253     }
2254   } else if (const auto *MTE =
2255                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2256     if (CheckedTemps.insert(MTE).second) {
2257       QualType TempType = getType(Base);
2258       if (TempType.isDestructedType()) {
2259         Info.FFDiag(MTE->getExprLoc(),
2260                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2261             << TempType;
2262         return false;
2263       }
2264 
2265       APValue *V = MTE->getOrCreateValue(false);
2266       assert(V && "evasluation result refers to uninitialised temporary");
2267       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2268                                  Info, MTE->getExprLoc(), TempType, *V,
2269                                  Kind, SourceLocation(), CheckedTemps))
2270         return false;
2271     }
2272   }
2273 
2274   // Allow address constant expressions to be past-the-end pointers. This is
2275   // an extension: the standard requires them to point to an object.
2276   if (!IsReferenceType)
2277     return true;
2278 
2279   // A reference constant expression must refer to an object.
2280   if (!Base) {
2281     // FIXME: diagnostic
2282     Info.CCEDiag(Loc);
2283     return true;
2284   }
2285 
2286   // Does this refer one past the end of some object?
2287   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2288     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2289       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2290     NoteLValueLocation(Info, Base);
2291   }
2292 
2293   return true;
2294 }
2295 
2296 /// Member pointers are constant expressions unless they point to a
2297 /// non-virtual dllimport member function.
2298 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2299                                                  SourceLocation Loc,
2300                                                  QualType Type,
2301                                                  const APValue &Value,
2302                                                  ConstantExprKind Kind) {
2303   const ValueDecl *Member = Value.getMemberPointerDecl();
2304   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2305   if (!FD)
2306     return true;
2307   if (FD->isConsteval()) {
2308     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2309     Info.Note(FD->getLocation(), diag::note_declared_at);
2310     return false;
2311   }
2312   return isForManglingOnly(Kind) || FD->isVirtual() ||
2313          !FD->hasAttr<DLLImportAttr>();
2314 }
2315 
2316 /// Check that this core constant expression is of literal type, and if not,
2317 /// produce an appropriate diagnostic.
2318 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2319                              const LValue *This = nullptr) {
2320   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2321     return true;
2322 
2323   // C++1y: A constant initializer for an object o [...] may also invoke
2324   // constexpr constructors for o and its subobjects even if those objects
2325   // are of non-literal class types.
2326   //
2327   // C++11 missed this detail for aggregates, so classes like this:
2328   //   struct foo_t { union { int i; volatile int j; } u; };
2329   // are not (obviously) initializable like so:
2330   //   __attribute__((__require_constant_initialization__))
2331   //   static const foo_t x = {{0}};
2332   // because "i" is a subobject with non-literal initialization (due to the
2333   // volatile member of the union). See:
2334   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2335   // Therefore, we use the C++1y behavior.
2336   if (This && Info.EvaluatingDecl == This->getLValueBase())
2337     return true;
2338 
2339   // Prvalue constant expressions must be of literal types.
2340   if (Info.getLangOpts().CPlusPlus11)
2341     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2342       << E->getType();
2343   else
2344     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2345   return false;
2346 }
2347 
2348 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2349                                   EvalInfo &Info, SourceLocation DiagLoc,
2350                                   QualType Type, const APValue &Value,
2351                                   ConstantExprKind Kind,
2352                                   SourceLocation SubobjectLoc,
2353                                   CheckedTemporaries &CheckedTemps) {
2354   if (!Value.hasValue()) {
2355     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2356       << true << Type;
2357     if (SubobjectLoc.isValid())
2358       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2359     return false;
2360   }
2361 
2362   // We allow _Atomic(T) to be initialized from anything that T can be
2363   // initialized from.
2364   if (const AtomicType *AT = Type->getAs<AtomicType>())
2365     Type = AT->getValueType();
2366 
2367   // Core issue 1454: For a literal constant expression of array or class type,
2368   // each subobject of its value shall have been initialized by a constant
2369   // expression.
2370   if (Value.isArray()) {
2371     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2372     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2373       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2374                                  Value.getArrayInitializedElt(I), Kind,
2375                                  SubobjectLoc, CheckedTemps))
2376         return false;
2377     }
2378     if (!Value.hasArrayFiller())
2379       return true;
2380     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2381                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2382                                  CheckedTemps);
2383   }
2384   if (Value.isUnion() && Value.getUnionField()) {
2385     return CheckEvaluationResult(
2386         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2387         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2388         CheckedTemps);
2389   }
2390   if (Value.isStruct()) {
2391     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2392     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2393       unsigned BaseIndex = 0;
2394       for (const CXXBaseSpecifier &BS : CD->bases()) {
2395         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2396                                    Value.getStructBase(BaseIndex), Kind,
2397                                    BS.getBeginLoc(), CheckedTemps))
2398           return false;
2399         ++BaseIndex;
2400       }
2401     }
2402     for (const auto *I : RD->fields()) {
2403       if (I->isUnnamedBitfield())
2404         continue;
2405 
2406       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2407                                  Value.getStructField(I->getFieldIndex()),
2408                                  Kind, I->getLocation(), CheckedTemps))
2409         return false;
2410     }
2411   }
2412 
2413   if (Value.isLValue() &&
2414       CERK == CheckEvaluationResultKind::ConstantExpression) {
2415     LValue LVal;
2416     LVal.setFrom(Info.Ctx, Value);
2417     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2418                                          CheckedTemps);
2419   }
2420 
2421   if (Value.isMemberPointer() &&
2422       CERK == CheckEvaluationResultKind::ConstantExpression)
2423     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2424 
2425   // Everything else is fine.
2426   return true;
2427 }
2428 
2429 /// Check that this core constant expression value is a valid value for a
2430 /// constant expression. If not, report an appropriate diagnostic. Does not
2431 /// check that the expression is of literal type.
2432 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2433                                     QualType Type, const APValue &Value,
2434                                     ConstantExprKind Kind) {
2435   // Nothing to check for a constant expression of type 'cv void'.
2436   if (Type->isVoidType())
2437     return true;
2438 
2439   CheckedTemporaries CheckedTemps;
2440   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2441                                Info, DiagLoc, Type, Value, Kind,
2442                                SourceLocation(), CheckedTemps);
2443 }
2444 
2445 /// Check that this evaluated value is fully-initialized and can be loaded by
2446 /// an lvalue-to-rvalue conversion.
2447 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2448                                   QualType Type, const APValue &Value) {
2449   CheckedTemporaries CheckedTemps;
2450   return CheckEvaluationResult(
2451       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2452       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2453 }
2454 
2455 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2456 /// "the allocated storage is deallocated within the evaluation".
2457 static bool CheckMemoryLeaks(EvalInfo &Info) {
2458   if (!Info.HeapAllocs.empty()) {
2459     // We can still fold to a constant despite a compile-time memory leak,
2460     // so long as the heap allocation isn't referenced in the result (we check
2461     // that in CheckConstantExpression).
2462     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2463                  diag::note_constexpr_memory_leak)
2464         << unsigned(Info.HeapAllocs.size() - 1);
2465   }
2466   return true;
2467 }
2468 
2469 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2470   // A null base expression indicates a null pointer.  These are always
2471   // evaluatable, and they are false unless the offset is zero.
2472   if (!Value.getLValueBase()) {
2473     Result = !Value.getLValueOffset().isZero();
2474     return true;
2475   }
2476 
2477   // We have a non-null base.  These are generally known to be true, but if it's
2478   // a weak declaration it can be null at runtime.
2479   Result = true;
2480   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2481   return !Decl || !Decl->isWeak();
2482 }
2483 
2484 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2485   switch (Val.getKind()) {
2486   case APValue::None:
2487   case APValue::Indeterminate:
2488     return false;
2489   case APValue::Int:
2490     Result = Val.getInt().getBoolValue();
2491     return true;
2492   case APValue::FixedPoint:
2493     Result = Val.getFixedPoint().getBoolValue();
2494     return true;
2495   case APValue::Float:
2496     Result = !Val.getFloat().isZero();
2497     return true;
2498   case APValue::ComplexInt:
2499     Result = Val.getComplexIntReal().getBoolValue() ||
2500              Val.getComplexIntImag().getBoolValue();
2501     return true;
2502   case APValue::ComplexFloat:
2503     Result = !Val.getComplexFloatReal().isZero() ||
2504              !Val.getComplexFloatImag().isZero();
2505     return true;
2506   case APValue::LValue:
2507     return EvalPointerValueAsBool(Val, Result);
2508   case APValue::MemberPointer:
2509     Result = Val.getMemberPointerDecl();
2510     return true;
2511   case APValue::Vector:
2512   case APValue::Array:
2513   case APValue::Struct:
2514   case APValue::Union:
2515   case APValue::AddrLabelDiff:
2516     return false;
2517   }
2518 
2519   llvm_unreachable("unknown APValue kind");
2520 }
2521 
2522 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2523                                        EvalInfo &Info) {
2524   assert(!E->isValueDependent());
2525   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2526   APValue Val;
2527   if (!Evaluate(Val, Info, E))
2528     return false;
2529   return HandleConversionToBool(Val, Result);
2530 }
2531 
2532 template<typename T>
2533 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2534                            const T &SrcValue, QualType DestType) {
2535   Info.CCEDiag(E, diag::note_constexpr_overflow)
2536     << SrcValue << DestType;
2537   return Info.noteUndefinedBehavior();
2538 }
2539 
2540 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2541                                  QualType SrcType, const APFloat &Value,
2542                                  QualType DestType, APSInt &Result) {
2543   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2544   // Determine whether we are converting to unsigned or signed.
2545   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2546 
2547   Result = APSInt(DestWidth, !DestSigned);
2548   bool ignored;
2549   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2550       & APFloat::opInvalidOp)
2551     return HandleOverflow(Info, E, Value, DestType);
2552   return true;
2553 }
2554 
2555 /// Get rounding mode used for evaluation of the specified expression.
2556 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2557 ///                       dynamic.
2558 /// If rounding mode is unknown at compile time, still try to evaluate the
2559 /// expression. If the result is exact, it does not depend on rounding mode.
2560 /// So return "tonearest" mode instead of "dynamic".
2561 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2562                                                 bool &DynamicRM) {
2563   llvm::RoundingMode RM =
2564       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2565   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2566   if (DynamicRM)
2567     RM = llvm::RoundingMode::NearestTiesToEven;
2568   return RM;
2569 }
2570 
2571 /// Check if the given evaluation result is allowed for constant evaluation.
2572 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2573                                      APFloat::opStatus St) {
2574   // In a constant context, assume that any dynamic rounding mode or FP
2575   // exception state matches the default floating-point environment.
2576   if (Info.InConstantContext)
2577     return true;
2578 
2579   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2580   if ((St & APFloat::opInexact) &&
2581       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2582     // Inexact result means that it depends on rounding mode. If the requested
2583     // mode is dynamic, the evaluation cannot be made in compile time.
2584     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2585     return false;
2586   }
2587 
2588   if ((St != APFloat::opOK) &&
2589       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2590        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2591        FPO.getAllowFEnvAccess())) {
2592     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2593     return false;
2594   }
2595 
2596   if ((St & APFloat::opStatus::opInvalidOp) &&
2597       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2598     // There is no usefully definable result.
2599     Info.FFDiag(E);
2600     return false;
2601   }
2602 
2603   // FIXME: if:
2604   // - evaluation triggered other FP exception, and
2605   // - exception mode is not "ignore", and
2606   // - the expression being evaluated is not a part of global variable
2607   //   initializer,
2608   // the evaluation probably need to be rejected.
2609   return true;
2610 }
2611 
2612 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2613                                    QualType SrcType, QualType DestType,
2614                                    APFloat &Result) {
2615   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2616   bool DynamicRM;
2617   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2618   APFloat::opStatus St;
2619   APFloat Value = Result;
2620   bool ignored;
2621   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2622   return checkFloatingPointResult(Info, E, St);
2623 }
2624 
2625 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2626                                  QualType DestType, QualType SrcType,
2627                                  const APSInt &Value) {
2628   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2629   // Figure out if this is a truncate, extend or noop cast.
2630   // If the input is signed, do a sign extend, noop, or truncate.
2631   APSInt Result = Value.extOrTrunc(DestWidth);
2632   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2633   if (DestType->isBooleanType())
2634     Result = Value.getBoolValue();
2635   return Result;
2636 }
2637 
2638 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2639                                  const FPOptions FPO,
2640                                  QualType SrcType, const APSInt &Value,
2641                                  QualType DestType, APFloat &Result) {
2642   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2643   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2644        APFloat::rmNearestTiesToEven);
2645   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2646       FPO.isFPConstrained()) {
2647     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2648     return false;
2649   }
2650   return true;
2651 }
2652 
2653 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2654                                   APValue &Value, const FieldDecl *FD) {
2655   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2656 
2657   if (!Value.isInt()) {
2658     // Trying to store a pointer-cast-to-integer into a bitfield.
2659     // FIXME: In this case, we should provide the diagnostic for casting
2660     // a pointer to an integer.
2661     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2662     Info.FFDiag(E);
2663     return false;
2664   }
2665 
2666   APSInt &Int = Value.getInt();
2667   unsigned OldBitWidth = Int.getBitWidth();
2668   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2669   if (NewBitWidth < OldBitWidth)
2670     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2671   return true;
2672 }
2673 
2674 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2675                                   llvm::APInt &Res) {
2676   APValue SVal;
2677   if (!Evaluate(SVal, Info, E))
2678     return false;
2679   if (SVal.isInt()) {
2680     Res = SVal.getInt();
2681     return true;
2682   }
2683   if (SVal.isFloat()) {
2684     Res = SVal.getFloat().bitcastToAPInt();
2685     return true;
2686   }
2687   if (SVal.isVector()) {
2688     QualType VecTy = E->getType();
2689     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2690     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2691     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2692     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2693     Res = llvm::APInt::getZero(VecSize);
2694     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2695       APValue &Elt = SVal.getVectorElt(i);
2696       llvm::APInt EltAsInt;
2697       if (Elt.isInt()) {
2698         EltAsInt = Elt.getInt();
2699       } else if (Elt.isFloat()) {
2700         EltAsInt = Elt.getFloat().bitcastToAPInt();
2701       } else {
2702         // Don't try to handle vectors of anything other than int or float
2703         // (not sure if it's possible to hit this case).
2704         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2705         return false;
2706       }
2707       unsigned BaseEltSize = EltAsInt.getBitWidth();
2708       if (BigEndian)
2709         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2710       else
2711         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2712     }
2713     return true;
2714   }
2715   // Give up if the input isn't an int, float, or vector.  For example, we
2716   // reject "(v4i16)(intptr_t)&a".
2717   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2718   return false;
2719 }
2720 
2721 /// Perform the given integer operation, which is known to need at most BitWidth
2722 /// bits, and check for overflow in the original type (if that type was not an
2723 /// unsigned type).
2724 template<typename Operation>
2725 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2726                                  const APSInt &LHS, const APSInt &RHS,
2727                                  unsigned BitWidth, Operation Op,
2728                                  APSInt &Result) {
2729   if (LHS.isUnsigned()) {
2730     Result = Op(LHS, RHS);
2731     return true;
2732   }
2733 
2734   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2735   Result = Value.trunc(LHS.getBitWidth());
2736   if (Result.extend(BitWidth) != Value) {
2737     if (Info.checkingForUndefinedBehavior())
2738       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2739                                        diag::warn_integer_constant_overflow)
2740           << toString(Result, 10) << E->getType();
2741     return HandleOverflow(Info, E, Value, E->getType());
2742   }
2743   return true;
2744 }
2745 
2746 /// Perform the given binary integer operation.
2747 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2748                               BinaryOperatorKind Opcode, APSInt RHS,
2749                               APSInt &Result) {
2750   switch (Opcode) {
2751   default:
2752     Info.FFDiag(E);
2753     return false;
2754   case BO_Mul:
2755     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2756                                 std::multiplies<APSInt>(), Result);
2757   case BO_Add:
2758     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2759                                 std::plus<APSInt>(), Result);
2760   case BO_Sub:
2761     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2762                                 std::minus<APSInt>(), Result);
2763   case BO_And: Result = LHS & RHS; return true;
2764   case BO_Xor: Result = LHS ^ RHS; return true;
2765   case BO_Or:  Result = LHS | RHS; return true;
2766   case BO_Div:
2767   case BO_Rem:
2768     if (RHS == 0) {
2769       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2770       return false;
2771     }
2772     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2773     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2774     // this operation and gives the two's complement result.
2775     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2776         LHS.isMinSignedValue())
2777       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2778                             E->getType());
2779     return true;
2780   case BO_Shl: {
2781     if (Info.getLangOpts().OpenCL)
2782       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2783       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2784                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2785                     RHS.isUnsigned());
2786     else if (RHS.isSigned() && RHS.isNegative()) {
2787       // During constant-folding, a negative shift is an opposite shift. Such
2788       // a shift is not a constant expression.
2789       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2790       RHS = -RHS;
2791       goto shift_right;
2792     }
2793   shift_left:
2794     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2795     // the shifted type.
2796     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2797     if (SA != RHS) {
2798       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2799         << RHS << E->getType() << LHS.getBitWidth();
2800     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2801       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2802       // operand, and must not overflow the corresponding unsigned type.
2803       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2804       // E1 x 2^E2 module 2^N.
2805       if (LHS.isNegative())
2806         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2807       else if (LHS.countLeadingZeros() < SA)
2808         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2809     }
2810     Result = LHS << SA;
2811     return true;
2812   }
2813   case BO_Shr: {
2814     if (Info.getLangOpts().OpenCL)
2815       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2816       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2817                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2818                     RHS.isUnsigned());
2819     else if (RHS.isSigned() && RHS.isNegative()) {
2820       // During constant-folding, a negative shift is an opposite shift. Such a
2821       // shift is not a constant expression.
2822       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2823       RHS = -RHS;
2824       goto shift_left;
2825     }
2826   shift_right:
2827     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2828     // shifted type.
2829     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2830     if (SA != RHS)
2831       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2832         << RHS << E->getType() << LHS.getBitWidth();
2833     Result = LHS >> SA;
2834     return true;
2835   }
2836 
2837   case BO_LT: Result = LHS < RHS; return true;
2838   case BO_GT: Result = LHS > RHS; return true;
2839   case BO_LE: Result = LHS <= RHS; return true;
2840   case BO_GE: Result = LHS >= RHS; return true;
2841   case BO_EQ: Result = LHS == RHS; return true;
2842   case BO_NE: Result = LHS != RHS; return true;
2843   case BO_Cmp:
2844     llvm_unreachable("BO_Cmp should be handled elsewhere");
2845   }
2846 }
2847 
2848 /// Perform the given binary floating-point operation, in-place, on LHS.
2849 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2850                                   APFloat &LHS, BinaryOperatorKind Opcode,
2851                                   const APFloat &RHS) {
2852   bool DynamicRM;
2853   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2854   APFloat::opStatus St;
2855   switch (Opcode) {
2856   default:
2857     Info.FFDiag(E);
2858     return false;
2859   case BO_Mul:
2860     St = LHS.multiply(RHS, RM);
2861     break;
2862   case BO_Add:
2863     St = LHS.add(RHS, RM);
2864     break;
2865   case BO_Sub:
2866     St = LHS.subtract(RHS, RM);
2867     break;
2868   case BO_Div:
2869     // [expr.mul]p4:
2870     //   If the second operand of / or % is zero the behavior is undefined.
2871     if (RHS.isZero())
2872       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2873     St = LHS.divide(RHS, RM);
2874     break;
2875   }
2876 
2877   // [expr.pre]p4:
2878   //   If during the evaluation of an expression, the result is not
2879   //   mathematically defined [...], the behavior is undefined.
2880   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2881   if (LHS.isNaN()) {
2882     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2883     return Info.noteUndefinedBehavior();
2884   }
2885 
2886   return checkFloatingPointResult(Info, E, St);
2887 }
2888 
2889 static bool handleLogicalOpForVector(const APInt &LHSValue,
2890                                      BinaryOperatorKind Opcode,
2891                                      const APInt &RHSValue, APInt &Result) {
2892   bool LHS = (LHSValue != 0);
2893   bool RHS = (RHSValue != 0);
2894 
2895   if (Opcode == BO_LAnd)
2896     Result = LHS && RHS;
2897   else
2898     Result = LHS || RHS;
2899   return true;
2900 }
2901 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2902                                      BinaryOperatorKind Opcode,
2903                                      const APFloat &RHSValue, APInt &Result) {
2904   bool LHS = !LHSValue.isZero();
2905   bool RHS = !RHSValue.isZero();
2906 
2907   if (Opcode == BO_LAnd)
2908     Result = LHS && RHS;
2909   else
2910     Result = LHS || RHS;
2911   return true;
2912 }
2913 
2914 static bool handleLogicalOpForVector(const APValue &LHSValue,
2915                                      BinaryOperatorKind Opcode,
2916                                      const APValue &RHSValue, APInt &Result) {
2917   // The result is always an int type, however operands match the first.
2918   if (LHSValue.getKind() == APValue::Int)
2919     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2920                                     RHSValue.getInt(), Result);
2921   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2922   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2923                                   RHSValue.getFloat(), Result);
2924 }
2925 
2926 template <typename APTy>
2927 static bool
2928 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2929                                const APTy &RHSValue, APInt &Result) {
2930   switch (Opcode) {
2931   default:
2932     llvm_unreachable("unsupported binary operator");
2933   case BO_EQ:
2934     Result = (LHSValue == RHSValue);
2935     break;
2936   case BO_NE:
2937     Result = (LHSValue != RHSValue);
2938     break;
2939   case BO_LT:
2940     Result = (LHSValue < RHSValue);
2941     break;
2942   case BO_GT:
2943     Result = (LHSValue > RHSValue);
2944     break;
2945   case BO_LE:
2946     Result = (LHSValue <= RHSValue);
2947     break;
2948   case BO_GE:
2949     Result = (LHSValue >= RHSValue);
2950     break;
2951   }
2952 
2953   // The boolean operations on these vector types use an instruction that
2954   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2955   // to -1 to make sure that we produce the correct value.
2956   Result.negate();
2957 
2958   return true;
2959 }
2960 
2961 static bool handleCompareOpForVector(const APValue &LHSValue,
2962                                      BinaryOperatorKind Opcode,
2963                                      const APValue &RHSValue, APInt &Result) {
2964   // The result is always an int type, however operands match the first.
2965   if (LHSValue.getKind() == APValue::Int)
2966     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2967                                           RHSValue.getInt(), Result);
2968   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2969   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2970                                         RHSValue.getFloat(), Result);
2971 }
2972 
2973 // Perform binary operations for vector types, in place on the LHS.
2974 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2975                                     BinaryOperatorKind Opcode,
2976                                     APValue &LHSValue,
2977                                     const APValue &RHSValue) {
2978   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2979          "Operation not supported on vector types");
2980 
2981   const auto *VT = E->getType()->castAs<VectorType>();
2982   unsigned NumElements = VT->getNumElements();
2983   QualType EltTy = VT->getElementType();
2984 
2985   // In the cases (typically C as I've observed) where we aren't evaluating
2986   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2987   // just give up.
2988   if (!LHSValue.isVector()) {
2989     assert(LHSValue.isLValue() &&
2990            "A vector result that isn't a vector OR uncalculated LValue");
2991     Info.FFDiag(E);
2992     return false;
2993   }
2994 
2995   assert(LHSValue.getVectorLength() == NumElements &&
2996          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2997 
2998   SmallVector<APValue, 4> ResultElements;
2999 
3000   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3001     APValue LHSElt = LHSValue.getVectorElt(EltNum);
3002     APValue RHSElt = RHSValue.getVectorElt(EltNum);
3003 
3004     if (EltTy->isIntegerType()) {
3005       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3006                        EltTy->isUnsignedIntegerType()};
3007       bool Success = true;
3008 
3009       if (BinaryOperator::isLogicalOp(Opcode))
3010         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3011       else if (BinaryOperator::isComparisonOp(Opcode))
3012         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3013       else
3014         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3015                                     RHSElt.getInt(), EltResult);
3016 
3017       if (!Success) {
3018         Info.FFDiag(E);
3019         return false;
3020       }
3021       ResultElements.emplace_back(EltResult);
3022 
3023     } else if (EltTy->isFloatingType()) {
3024       assert(LHSElt.getKind() == APValue::Float &&
3025              RHSElt.getKind() == APValue::Float &&
3026              "Mismatched LHS/RHS/Result Type");
3027       APFloat LHSFloat = LHSElt.getFloat();
3028 
3029       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3030                                  RHSElt.getFloat())) {
3031         Info.FFDiag(E);
3032         return false;
3033       }
3034 
3035       ResultElements.emplace_back(LHSFloat);
3036     }
3037   }
3038 
3039   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3040   return true;
3041 }
3042 
3043 /// Cast an lvalue referring to a base subobject to a derived class, by
3044 /// truncating the lvalue's path to the given length.
3045 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3046                                const RecordDecl *TruncatedType,
3047                                unsigned TruncatedElements) {
3048   SubobjectDesignator &D = Result.Designator;
3049 
3050   // Check we actually point to a derived class object.
3051   if (TruncatedElements == D.Entries.size())
3052     return true;
3053   assert(TruncatedElements >= D.MostDerivedPathLength &&
3054          "not casting to a derived class");
3055   if (!Result.checkSubobject(Info, E, CSK_Derived))
3056     return false;
3057 
3058   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3059   const RecordDecl *RD = TruncatedType;
3060   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3061     if (RD->isInvalidDecl()) return false;
3062     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3063     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3064     if (isVirtualBaseClass(D.Entries[I]))
3065       Result.Offset -= Layout.getVBaseClassOffset(Base);
3066     else
3067       Result.Offset -= Layout.getBaseClassOffset(Base);
3068     RD = Base;
3069   }
3070   D.Entries.resize(TruncatedElements);
3071   return true;
3072 }
3073 
3074 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3075                                    const CXXRecordDecl *Derived,
3076                                    const CXXRecordDecl *Base,
3077                                    const ASTRecordLayout *RL = nullptr) {
3078   if (!RL) {
3079     if (Derived->isInvalidDecl()) return false;
3080     RL = &Info.Ctx.getASTRecordLayout(Derived);
3081   }
3082 
3083   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3084   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3085   return true;
3086 }
3087 
3088 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3089                              const CXXRecordDecl *DerivedDecl,
3090                              const CXXBaseSpecifier *Base) {
3091   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3092 
3093   if (!Base->isVirtual())
3094     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3095 
3096   SubobjectDesignator &D = Obj.Designator;
3097   if (D.Invalid)
3098     return false;
3099 
3100   // Extract most-derived object and corresponding type.
3101   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3102   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3103     return false;
3104 
3105   // Find the virtual base class.
3106   if (DerivedDecl->isInvalidDecl()) return false;
3107   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3108   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3109   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3110   return true;
3111 }
3112 
3113 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3114                                  QualType Type, LValue &Result) {
3115   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3116                                      PathE = E->path_end();
3117        PathI != PathE; ++PathI) {
3118     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3119                           *PathI))
3120       return false;
3121     Type = (*PathI)->getType();
3122   }
3123   return true;
3124 }
3125 
3126 /// Cast an lvalue referring to a derived class to a known base subobject.
3127 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3128                             const CXXRecordDecl *DerivedRD,
3129                             const CXXRecordDecl *BaseRD) {
3130   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3131                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3132   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3133     llvm_unreachable("Class must be derived from the passed in base class!");
3134 
3135   for (CXXBasePathElement &Elem : Paths.front())
3136     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3137       return false;
3138   return true;
3139 }
3140 
3141 /// Update LVal to refer to the given field, which must be a member of the type
3142 /// currently described by LVal.
3143 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3144                                const FieldDecl *FD,
3145                                const ASTRecordLayout *RL = nullptr) {
3146   if (!RL) {
3147     if (FD->getParent()->isInvalidDecl()) return false;
3148     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3149   }
3150 
3151   unsigned I = FD->getFieldIndex();
3152   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3153   LVal.addDecl(Info, E, FD);
3154   return true;
3155 }
3156 
3157 /// Update LVal to refer to the given indirect field.
3158 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3159                                        LValue &LVal,
3160                                        const IndirectFieldDecl *IFD) {
3161   for (const auto *C : IFD->chain())
3162     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3163       return false;
3164   return true;
3165 }
3166 
3167 /// Get the size of the given type in char units.
3168 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3169                          QualType Type, CharUnits &Size) {
3170   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3171   // extension.
3172   if (Type->isVoidType() || Type->isFunctionType()) {
3173     Size = CharUnits::One();
3174     return true;
3175   }
3176 
3177   if (Type->isDependentType()) {
3178     Info.FFDiag(Loc);
3179     return false;
3180   }
3181 
3182   if (!Type->isConstantSizeType()) {
3183     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3184     // FIXME: Better diagnostic.
3185     Info.FFDiag(Loc);
3186     return false;
3187   }
3188 
3189   Size = Info.Ctx.getTypeSizeInChars(Type);
3190   return true;
3191 }
3192 
3193 /// Update a pointer value to model pointer arithmetic.
3194 /// \param Info - Information about the ongoing evaluation.
3195 /// \param E - The expression being evaluated, for diagnostic purposes.
3196 /// \param LVal - The pointer value to be updated.
3197 /// \param EltTy - The pointee type represented by LVal.
3198 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3199 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3200                                         LValue &LVal, QualType EltTy,
3201                                         APSInt Adjustment) {
3202   CharUnits SizeOfPointee;
3203   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3204     return false;
3205 
3206   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3207   return true;
3208 }
3209 
3210 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3211                                         LValue &LVal, QualType EltTy,
3212                                         int64_t Adjustment) {
3213   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3214                                      APSInt::get(Adjustment));
3215 }
3216 
3217 /// Update an lvalue to refer to a component of a complex number.
3218 /// \param Info - Information about the ongoing evaluation.
3219 /// \param LVal - The lvalue to be updated.
3220 /// \param EltTy - The complex number's component type.
3221 /// \param Imag - False for the real component, true for the imaginary.
3222 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3223                                        LValue &LVal, QualType EltTy,
3224                                        bool Imag) {
3225   if (Imag) {
3226     CharUnits SizeOfComponent;
3227     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3228       return false;
3229     LVal.Offset += SizeOfComponent;
3230   }
3231   LVal.addComplex(Info, E, EltTy, Imag);
3232   return true;
3233 }
3234 
3235 /// Try to evaluate the initializer for a variable declaration.
3236 ///
3237 /// \param Info   Information about the ongoing evaluation.
3238 /// \param E      An expression to be used when printing diagnostics.
3239 /// \param VD     The variable whose initializer should be obtained.
3240 /// \param Version The version of the variable within the frame.
3241 /// \param Frame  The frame in which the variable was created. Must be null
3242 ///               if this variable is not local to the evaluation.
3243 /// \param Result Filled in with a pointer to the value of the variable.
3244 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3245                                 const VarDecl *VD, CallStackFrame *Frame,
3246                                 unsigned Version, APValue *&Result) {
3247   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3248 
3249   // If this is a local variable, dig out its value.
3250   if (Frame) {
3251     Result = Frame->getTemporary(VD, Version);
3252     if (Result)
3253       return true;
3254 
3255     if (!isa<ParmVarDecl>(VD)) {
3256       // Assume variables referenced within a lambda's call operator that were
3257       // not declared within the call operator are captures and during checking
3258       // of a potential constant expression, assume they are unknown constant
3259       // expressions.
3260       assert(isLambdaCallOperator(Frame->Callee) &&
3261              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3262              "missing value for local variable");
3263       if (Info.checkingPotentialConstantExpression())
3264         return false;
3265       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3266       // still reachable at all?
3267       Info.FFDiag(E->getBeginLoc(),
3268                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3269           << "captures not currently allowed";
3270       return false;
3271     }
3272   }
3273 
3274   // If we're currently evaluating the initializer of this declaration, use that
3275   // in-flight value.
3276   if (Info.EvaluatingDecl == Base) {
3277     Result = Info.EvaluatingDeclValue;
3278     return true;
3279   }
3280 
3281   if (isa<ParmVarDecl>(VD)) {
3282     // Assume parameters of a potential constant expression are usable in
3283     // constant expressions.
3284     if (!Info.checkingPotentialConstantExpression() ||
3285         !Info.CurrentCall->Callee ||
3286         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3287       if (Info.getLangOpts().CPlusPlus11) {
3288         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3289             << VD;
3290         NoteLValueLocation(Info, Base);
3291       } else {
3292         Info.FFDiag(E);
3293       }
3294     }
3295     return false;
3296   }
3297 
3298   // Dig out the initializer, and use the declaration which it's attached to.
3299   // FIXME: We should eventually check whether the variable has a reachable
3300   // initializing declaration.
3301   const Expr *Init = VD->getAnyInitializer(VD);
3302   if (!Init) {
3303     // Don't diagnose during potential constant expression checking; an
3304     // initializer might be added later.
3305     if (!Info.checkingPotentialConstantExpression()) {
3306       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3307         << VD;
3308       NoteLValueLocation(Info, Base);
3309     }
3310     return false;
3311   }
3312 
3313   if (Init->isValueDependent()) {
3314     // The DeclRefExpr is not value-dependent, but the variable it refers to
3315     // has a value-dependent initializer. This should only happen in
3316     // constant-folding cases, where the variable is not actually of a suitable
3317     // type for use in a constant expression (otherwise the DeclRefExpr would
3318     // have been value-dependent too), so diagnose that.
3319     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3320     if (!Info.checkingPotentialConstantExpression()) {
3321       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3322                          ? diag::note_constexpr_ltor_non_constexpr
3323                          : diag::note_constexpr_ltor_non_integral, 1)
3324           << VD << VD->getType();
3325       NoteLValueLocation(Info, Base);
3326     }
3327     return false;
3328   }
3329 
3330   // Check that we can fold the initializer. In C++, we will have already done
3331   // this in the cases where it matters for conformance.
3332   if (!VD->evaluateValue()) {
3333     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3334     NoteLValueLocation(Info, Base);
3335     return false;
3336   }
3337 
3338   // Check that the variable is actually usable in constant expressions. For a
3339   // const integral variable or a reference, we might have a non-constant
3340   // initializer that we can nonetheless evaluate the initializer for. Such
3341   // variables are not usable in constant expressions. In C++98, the
3342   // initializer also syntactically needs to be an ICE.
3343   //
3344   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3345   // expressions here; doing so would regress diagnostics for things like
3346   // reading from a volatile constexpr variable.
3347   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3348        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3349       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3350        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3351     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3352     NoteLValueLocation(Info, Base);
3353   }
3354 
3355   // Never use the initializer of a weak variable, not even for constant
3356   // folding. We can't be sure that this is the definition that will be used.
3357   if (VD->isWeak()) {
3358     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3359     NoteLValueLocation(Info, Base);
3360     return false;
3361   }
3362 
3363   Result = VD->getEvaluatedValue();
3364   return true;
3365 }
3366 
3367 /// Get the base index of the given base class within an APValue representing
3368 /// the given derived class.
3369 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3370                              const CXXRecordDecl *Base) {
3371   Base = Base->getCanonicalDecl();
3372   unsigned Index = 0;
3373   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3374          E = Derived->bases_end(); I != E; ++I, ++Index) {
3375     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3376       return Index;
3377   }
3378 
3379   llvm_unreachable("base class missing from derived class's bases list");
3380 }
3381 
3382 /// Extract the value of a character from a string literal.
3383 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3384                                             uint64_t Index) {
3385   assert(!isa<SourceLocExpr>(Lit) &&
3386          "SourceLocExpr should have already been converted to a StringLiteral");
3387 
3388   // FIXME: Support MakeStringConstant
3389   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3390     std::string Str;
3391     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3392     assert(Index <= Str.size() && "Index too large");
3393     return APSInt::getUnsigned(Str.c_str()[Index]);
3394   }
3395 
3396   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3397     Lit = PE->getFunctionName();
3398   const StringLiteral *S = cast<StringLiteral>(Lit);
3399   const ConstantArrayType *CAT =
3400       Info.Ctx.getAsConstantArrayType(S->getType());
3401   assert(CAT && "string literal isn't an array");
3402   QualType CharType = CAT->getElementType();
3403   assert(CharType->isIntegerType() && "unexpected character type");
3404 
3405   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3406                CharType->isUnsignedIntegerType());
3407   if (Index < S->getLength())
3408     Value = S->getCodeUnit(Index);
3409   return Value;
3410 }
3411 
3412 // Expand a string literal into an array of characters.
3413 //
3414 // FIXME: This is inefficient; we should probably introduce something similar
3415 // to the LLVM ConstantDataArray to make this cheaper.
3416 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3417                                 APValue &Result,
3418                                 QualType AllocType = QualType()) {
3419   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3420       AllocType.isNull() ? S->getType() : AllocType);
3421   assert(CAT && "string literal isn't an array");
3422   QualType CharType = CAT->getElementType();
3423   assert(CharType->isIntegerType() && "unexpected character type");
3424 
3425   unsigned Elts = CAT->getSize().getZExtValue();
3426   Result = APValue(APValue::UninitArray(),
3427                    std::min(S->getLength(), Elts), Elts);
3428   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3429                CharType->isUnsignedIntegerType());
3430   if (Result.hasArrayFiller())
3431     Result.getArrayFiller() = APValue(Value);
3432   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3433     Value = S->getCodeUnit(I);
3434     Result.getArrayInitializedElt(I) = APValue(Value);
3435   }
3436 }
3437 
3438 // Expand an array so that it has more than Index filled elements.
3439 static void expandArray(APValue &Array, unsigned Index) {
3440   unsigned Size = Array.getArraySize();
3441   assert(Index < Size);
3442 
3443   // Always at least double the number of elements for which we store a value.
3444   unsigned OldElts = Array.getArrayInitializedElts();
3445   unsigned NewElts = std::max(Index+1, OldElts * 2);
3446   NewElts = std::min(Size, std::max(NewElts, 8u));
3447 
3448   // Copy the data across.
3449   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3450   for (unsigned I = 0; I != OldElts; ++I)
3451     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3452   for (unsigned I = OldElts; I != NewElts; ++I)
3453     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3454   if (NewValue.hasArrayFiller())
3455     NewValue.getArrayFiller() = Array.getArrayFiller();
3456   Array.swap(NewValue);
3457 }
3458 
3459 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3460 /// conversion. If it's of class type, we may assume that the copy operation
3461 /// is trivial. Note that this is never true for a union type with fields
3462 /// (because the copy always "reads" the active member) and always true for
3463 /// a non-class type.
3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3465 static bool isReadByLvalueToRvalueConversion(QualType T) {
3466   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3467   return !RD || isReadByLvalueToRvalueConversion(RD);
3468 }
3469 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3470   // FIXME: A trivial copy of a union copies the object representation, even if
3471   // the union is empty.
3472   if (RD->isUnion())
3473     return !RD->field_empty();
3474   if (RD->isEmpty())
3475     return false;
3476 
3477   for (auto *Field : RD->fields())
3478     if (!Field->isUnnamedBitfield() &&
3479         isReadByLvalueToRvalueConversion(Field->getType()))
3480       return true;
3481 
3482   for (auto &BaseSpec : RD->bases())
3483     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3484       return true;
3485 
3486   return false;
3487 }
3488 
3489 /// Diagnose an attempt to read from any unreadable field within the specified
3490 /// type, which might be a class type.
3491 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3492                                   QualType T) {
3493   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3494   if (!RD)
3495     return false;
3496 
3497   if (!RD->hasMutableFields())
3498     return false;
3499 
3500   for (auto *Field : RD->fields()) {
3501     // If we're actually going to read this field in some way, then it can't
3502     // be mutable. If we're in a union, then assigning to a mutable field
3503     // (even an empty one) can change the active member, so that's not OK.
3504     // FIXME: Add core issue number for the union case.
3505     if (Field->isMutable() &&
3506         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3507       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3508       Info.Note(Field->getLocation(), diag::note_declared_at);
3509       return true;
3510     }
3511 
3512     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3513       return true;
3514   }
3515 
3516   for (auto &BaseSpec : RD->bases())
3517     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3518       return true;
3519 
3520   // All mutable fields were empty, and thus not actually read.
3521   return false;
3522 }
3523 
3524 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3525                                         APValue::LValueBase Base,
3526                                         bool MutableSubobject = false) {
3527   // A temporary or transient heap allocation we created.
3528   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3529     return true;
3530 
3531   switch (Info.IsEvaluatingDecl) {
3532   case EvalInfo::EvaluatingDeclKind::None:
3533     return false;
3534 
3535   case EvalInfo::EvaluatingDeclKind::Ctor:
3536     // The variable whose initializer we're evaluating.
3537     if (Info.EvaluatingDecl == Base)
3538       return true;
3539 
3540     // A temporary lifetime-extended by the variable whose initializer we're
3541     // evaluating.
3542     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3543       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3544         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3545     return false;
3546 
3547   case EvalInfo::EvaluatingDeclKind::Dtor:
3548     // C++2a [expr.const]p6:
3549     //   [during constant destruction] the lifetime of a and its non-mutable
3550     //   subobjects (but not its mutable subobjects) [are] considered to start
3551     //   within e.
3552     if (MutableSubobject || Base != Info.EvaluatingDecl)
3553       return false;
3554     // FIXME: We can meaningfully extend this to cover non-const objects, but
3555     // we will need special handling: we should be able to access only
3556     // subobjects of such objects that are themselves declared const.
3557     QualType T = getType(Base);
3558     return T.isConstQualified() || T->isReferenceType();
3559   }
3560 
3561   llvm_unreachable("unknown evaluating decl kind");
3562 }
3563 
3564 namespace {
3565 /// A handle to a complete object (an object that is not a subobject of
3566 /// another object).
3567 struct CompleteObject {
3568   /// The identity of the object.
3569   APValue::LValueBase Base;
3570   /// The value of the complete object.
3571   APValue *Value;
3572   /// The type of the complete object.
3573   QualType Type;
3574 
3575   CompleteObject() : Value(nullptr) {}
3576   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3577       : Base(Base), Value(Value), Type(Type) {}
3578 
3579   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3580     // If this isn't a "real" access (eg, if it's just accessing the type
3581     // info), allow it. We assume the type doesn't change dynamically for
3582     // subobjects of constexpr objects (even though we'd hit UB here if it
3583     // did). FIXME: Is this right?
3584     if (!isAnyAccess(AK))
3585       return true;
3586 
3587     // In C++14 onwards, it is permitted to read a mutable member whose
3588     // lifetime began within the evaluation.
3589     // FIXME: Should we also allow this in C++11?
3590     if (!Info.getLangOpts().CPlusPlus14)
3591       return false;
3592     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3593   }
3594 
3595   explicit operator bool() const { return !Type.isNull(); }
3596 };
3597 } // end anonymous namespace
3598 
3599 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3600                                  bool IsMutable = false) {
3601   // C++ [basic.type.qualifier]p1:
3602   // - A const object is an object of type const T or a non-mutable subobject
3603   //   of a const object.
3604   if (ObjType.isConstQualified() && !IsMutable)
3605     SubobjType.addConst();
3606   // - A volatile object is an object of type const T or a subobject of a
3607   //   volatile object.
3608   if (ObjType.isVolatileQualified())
3609     SubobjType.addVolatile();
3610   return SubobjType;
3611 }
3612 
3613 /// Find the designated sub-object of an rvalue.
3614 template<typename SubobjectHandler>
3615 typename SubobjectHandler::result_type
3616 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3617               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3618   if (Sub.Invalid)
3619     // A diagnostic will have already been produced.
3620     return handler.failed();
3621   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3622     if (Info.getLangOpts().CPlusPlus11)
3623       Info.FFDiag(E, Sub.isOnePastTheEnd()
3624                          ? diag::note_constexpr_access_past_end
3625                          : diag::note_constexpr_access_unsized_array)
3626           << handler.AccessKind;
3627     else
3628       Info.FFDiag(E);
3629     return handler.failed();
3630   }
3631 
3632   APValue *O = Obj.Value;
3633   QualType ObjType = Obj.Type;
3634   const FieldDecl *LastField = nullptr;
3635   const FieldDecl *VolatileField = nullptr;
3636 
3637   // Walk the designator's path to find the subobject.
3638   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3639     // Reading an indeterminate value is undefined, but assigning over one is OK.
3640     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3641         (O->isIndeterminate() &&
3642          !isValidIndeterminateAccess(handler.AccessKind))) {
3643       if (!Info.checkingPotentialConstantExpression())
3644         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3645             << handler.AccessKind << O->isIndeterminate();
3646       return handler.failed();
3647     }
3648 
3649     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3650     //    const and volatile semantics are not applied on an object under
3651     //    {con,de}struction.
3652     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3653         ObjType->isRecordType() &&
3654         Info.isEvaluatingCtorDtor(
3655             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3656                                          Sub.Entries.begin() + I)) !=
3657                           ConstructionPhase::None) {
3658       ObjType = Info.Ctx.getCanonicalType(ObjType);
3659       ObjType.removeLocalConst();
3660       ObjType.removeLocalVolatile();
3661     }
3662 
3663     // If this is our last pass, check that the final object type is OK.
3664     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3665       // Accesses to volatile objects are prohibited.
3666       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3667         if (Info.getLangOpts().CPlusPlus) {
3668           int DiagKind;
3669           SourceLocation Loc;
3670           const NamedDecl *Decl = nullptr;
3671           if (VolatileField) {
3672             DiagKind = 2;
3673             Loc = VolatileField->getLocation();
3674             Decl = VolatileField;
3675           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3676             DiagKind = 1;
3677             Loc = VD->getLocation();
3678             Decl = VD;
3679           } else {
3680             DiagKind = 0;
3681             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3682               Loc = E->getExprLoc();
3683           }
3684           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3685               << handler.AccessKind << DiagKind << Decl;
3686           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3687         } else {
3688           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3689         }
3690         return handler.failed();
3691       }
3692 
3693       // If we are reading an object of class type, there may still be more
3694       // things we need to check: if there are any mutable subobjects, we
3695       // cannot perform this read. (This only happens when performing a trivial
3696       // copy or assignment.)
3697       if (ObjType->isRecordType() &&
3698           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3699           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3700         return handler.failed();
3701     }
3702 
3703     if (I == N) {
3704       if (!handler.found(*O, ObjType))
3705         return false;
3706 
3707       // If we modified a bit-field, truncate it to the right width.
3708       if (isModification(handler.AccessKind) &&
3709           LastField && LastField->isBitField() &&
3710           !truncateBitfieldValue(Info, E, *O, LastField))
3711         return false;
3712 
3713       return true;
3714     }
3715 
3716     LastField = nullptr;
3717     if (ObjType->isArrayType()) {
3718       // Next subobject is an array element.
3719       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3720       assert(CAT && "vla in literal type?");
3721       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3722       if (CAT->getSize().ule(Index)) {
3723         // Note, it should not be possible to form a pointer with a valid
3724         // designator which points more than one past the end of the array.
3725         if (Info.getLangOpts().CPlusPlus11)
3726           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3727             << handler.AccessKind;
3728         else
3729           Info.FFDiag(E);
3730         return handler.failed();
3731       }
3732 
3733       ObjType = CAT->getElementType();
3734 
3735       if (O->getArrayInitializedElts() > Index)
3736         O = &O->getArrayInitializedElt(Index);
3737       else if (!isRead(handler.AccessKind)) {
3738         expandArray(*O, Index);
3739         O = &O->getArrayInitializedElt(Index);
3740       } else
3741         O = &O->getArrayFiller();
3742     } else if (ObjType->isAnyComplexType()) {
3743       // Next subobject is a complex number.
3744       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3745       if (Index > 1) {
3746         if (Info.getLangOpts().CPlusPlus11)
3747           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3748             << handler.AccessKind;
3749         else
3750           Info.FFDiag(E);
3751         return handler.failed();
3752       }
3753 
3754       ObjType = getSubobjectType(
3755           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3756 
3757       assert(I == N - 1 && "extracting subobject of scalar?");
3758       if (O->isComplexInt()) {
3759         return handler.found(Index ? O->getComplexIntImag()
3760                                    : O->getComplexIntReal(), ObjType);
3761       } else {
3762         assert(O->isComplexFloat());
3763         return handler.found(Index ? O->getComplexFloatImag()
3764                                    : O->getComplexFloatReal(), ObjType);
3765       }
3766     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3767       if (Field->isMutable() &&
3768           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3769         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3770           << handler.AccessKind << Field;
3771         Info.Note(Field->getLocation(), diag::note_declared_at);
3772         return handler.failed();
3773       }
3774 
3775       // Next subobject is a class, struct or union field.
3776       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3777       if (RD->isUnion()) {
3778         const FieldDecl *UnionField = O->getUnionField();
3779         if (!UnionField ||
3780             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3781           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3782             // Placement new onto an inactive union member makes it active.
3783             O->setUnion(Field, APValue());
3784           } else {
3785             // FIXME: If O->getUnionValue() is absent, report that there's no
3786             // active union member rather than reporting the prior active union
3787             // member. We'll need to fix nullptr_t to not use APValue() as its
3788             // representation first.
3789             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3790                 << handler.AccessKind << Field << !UnionField << UnionField;
3791             return handler.failed();
3792           }
3793         }
3794         O = &O->getUnionValue();
3795       } else
3796         O = &O->getStructField(Field->getFieldIndex());
3797 
3798       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3799       LastField = Field;
3800       if (Field->getType().isVolatileQualified())
3801         VolatileField = Field;
3802     } else {
3803       // Next subobject is a base class.
3804       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3805       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3806       O = &O->getStructBase(getBaseIndex(Derived, Base));
3807 
3808       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3809     }
3810   }
3811 }
3812 
3813 namespace {
3814 struct ExtractSubobjectHandler {
3815   EvalInfo &Info;
3816   const Expr *E;
3817   APValue &Result;
3818   const AccessKinds AccessKind;
3819 
3820   typedef bool result_type;
3821   bool failed() { return false; }
3822   bool found(APValue &Subobj, QualType SubobjType) {
3823     Result = Subobj;
3824     if (AccessKind == AK_ReadObjectRepresentation)
3825       return true;
3826     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3827   }
3828   bool found(APSInt &Value, QualType SubobjType) {
3829     Result = APValue(Value);
3830     return true;
3831   }
3832   bool found(APFloat &Value, QualType SubobjType) {
3833     Result = APValue(Value);
3834     return true;
3835   }
3836 };
3837 } // end anonymous namespace
3838 
3839 /// Extract the designated sub-object of an rvalue.
3840 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3841                              const CompleteObject &Obj,
3842                              const SubobjectDesignator &Sub, APValue &Result,
3843                              AccessKinds AK = AK_Read) {
3844   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3845   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3846   return findSubobject(Info, E, Obj, Sub, Handler);
3847 }
3848 
3849 namespace {
3850 struct ModifySubobjectHandler {
3851   EvalInfo &Info;
3852   APValue &NewVal;
3853   const Expr *E;
3854 
3855   typedef bool result_type;
3856   static const AccessKinds AccessKind = AK_Assign;
3857 
3858   bool checkConst(QualType QT) {
3859     // Assigning to a const object has undefined behavior.
3860     if (QT.isConstQualified()) {
3861       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3862       return false;
3863     }
3864     return true;
3865   }
3866 
3867   bool failed() { return false; }
3868   bool found(APValue &Subobj, QualType SubobjType) {
3869     if (!checkConst(SubobjType))
3870       return false;
3871     // We've been given ownership of NewVal, so just swap it in.
3872     Subobj.swap(NewVal);
3873     return true;
3874   }
3875   bool found(APSInt &Value, QualType SubobjType) {
3876     if (!checkConst(SubobjType))
3877       return false;
3878     if (!NewVal.isInt()) {
3879       // Maybe trying to write a cast pointer value into a complex?
3880       Info.FFDiag(E);
3881       return false;
3882     }
3883     Value = NewVal.getInt();
3884     return true;
3885   }
3886   bool found(APFloat &Value, QualType SubobjType) {
3887     if (!checkConst(SubobjType))
3888       return false;
3889     Value = NewVal.getFloat();
3890     return true;
3891   }
3892 };
3893 } // end anonymous namespace
3894 
3895 const AccessKinds ModifySubobjectHandler::AccessKind;
3896 
3897 /// Update the designated sub-object of an rvalue to the given value.
3898 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3899                             const CompleteObject &Obj,
3900                             const SubobjectDesignator &Sub,
3901                             APValue &NewVal) {
3902   ModifySubobjectHandler Handler = { Info, NewVal, E };
3903   return findSubobject(Info, E, Obj, Sub, Handler);
3904 }
3905 
3906 /// Find the position where two subobject designators diverge, or equivalently
3907 /// the length of the common initial subsequence.
3908 static unsigned FindDesignatorMismatch(QualType ObjType,
3909                                        const SubobjectDesignator &A,
3910                                        const SubobjectDesignator &B,
3911                                        bool &WasArrayIndex) {
3912   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3913   for (/**/; I != N; ++I) {
3914     if (!ObjType.isNull() &&
3915         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3916       // Next subobject is an array element.
3917       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3918         WasArrayIndex = true;
3919         return I;
3920       }
3921       if (ObjType->isAnyComplexType())
3922         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3923       else
3924         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3925     } else {
3926       if (A.Entries[I].getAsBaseOrMember() !=
3927           B.Entries[I].getAsBaseOrMember()) {
3928         WasArrayIndex = false;
3929         return I;
3930       }
3931       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3932         // Next subobject is a field.
3933         ObjType = FD->getType();
3934       else
3935         // Next subobject is a base class.
3936         ObjType = QualType();
3937     }
3938   }
3939   WasArrayIndex = false;
3940   return I;
3941 }
3942 
3943 /// Determine whether the given subobject designators refer to elements of the
3944 /// same array object.
3945 static bool AreElementsOfSameArray(QualType ObjType,
3946                                    const SubobjectDesignator &A,
3947                                    const SubobjectDesignator &B) {
3948   if (A.Entries.size() != B.Entries.size())
3949     return false;
3950 
3951   bool IsArray = A.MostDerivedIsArrayElement;
3952   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3953     // A is a subobject of the array element.
3954     return false;
3955 
3956   // If A (and B) designates an array element, the last entry will be the array
3957   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3958   // of length 1' case, and the entire path must match.
3959   bool WasArrayIndex;
3960   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3961   return CommonLength >= A.Entries.size() - IsArray;
3962 }
3963 
3964 /// Find the complete object to which an LValue refers.
3965 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3966                                          AccessKinds AK, const LValue &LVal,
3967                                          QualType LValType) {
3968   if (LVal.InvalidBase) {
3969     Info.FFDiag(E);
3970     return CompleteObject();
3971   }
3972 
3973   if (!LVal.Base) {
3974     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3975     return CompleteObject();
3976   }
3977 
3978   CallStackFrame *Frame = nullptr;
3979   unsigned Depth = 0;
3980   if (LVal.getLValueCallIndex()) {
3981     std::tie(Frame, Depth) =
3982         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3983     if (!Frame) {
3984       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3985         << AK << LVal.Base.is<const ValueDecl*>();
3986       NoteLValueLocation(Info, LVal.Base);
3987       return CompleteObject();
3988     }
3989   }
3990 
3991   bool IsAccess = isAnyAccess(AK);
3992 
3993   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3994   // is not a constant expression (even if the object is non-volatile). We also
3995   // apply this rule to C++98, in order to conform to the expected 'volatile'
3996   // semantics.
3997   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3998     if (Info.getLangOpts().CPlusPlus)
3999       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4000         << AK << LValType;
4001     else
4002       Info.FFDiag(E);
4003     return CompleteObject();
4004   }
4005 
4006   // Compute value storage location and type of base object.
4007   APValue *BaseVal = nullptr;
4008   QualType BaseType = getType(LVal.Base);
4009 
4010   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4011       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4012     // This is the object whose initializer we're evaluating, so its lifetime
4013     // started in the current evaluation.
4014     BaseVal = Info.EvaluatingDeclValue;
4015   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4016     // Allow reading from a GUID declaration.
4017     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4018       if (isModification(AK)) {
4019         // All the remaining cases do not permit modification of the object.
4020         Info.FFDiag(E, diag::note_constexpr_modify_global);
4021         return CompleteObject();
4022       }
4023       APValue &V = GD->getAsAPValue();
4024       if (V.isAbsent()) {
4025         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4026             << GD->getType();
4027         return CompleteObject();
4028       }
4029       return CompleteObject(LVal.Base, &V, GD->getType());
4030     }
4031 
4032     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4033     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4034       if (isModification(AK)) {
4035         Info.FFDiag(E, diag::note_constexpr_modify_global);
4036         return CompleteObject();
4037       }
4038       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4039                             GCD->getType());
4040     }
4041 
4042     // Allow reading from template parameter objects.
4043     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4044       if (isModification(AK)) {
4045         Info.FFDiag(E, diag::note_constexpr_modify_global);
4046         return CompleteObject();
4047       }
4048       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4049                             TPO->getType());
4050     }
4051 
4052     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4053     // In C++11, constexpr, non-volatile variables initialized with constant
4054     // expressions are constant expressions too. Inside constexpr functions,
4055     // parameters are constant expressions even if they're non-const.
4056     // In C++1y, objects local to a constant expression (those with a Frame) are
4057     // both readable and writable inside constant expressions.
4058     // In C, such things can also be folded, although they are not ICEs.
4059     const VarDecl *VD = dyn_cast<VarDecl>(D);
4060     if (VD) {
4061       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4062         VD = VDef;
4063     }
4064     if (!VD || VD->isInvalidDecl()) {
4065       Info.FFDiag(E);
4066       return CompleteObject();
4067     }
4068 
4069     bool IsConstant = BaseType.isConstant(Info.Ctx);
4070 
4071     // Unless we're looking at a local variable or argument in a constexpr call,
4072     // the variable we're reading must be const.
4073     if (!Frame) {
4074       if (IsAccess && isa<ParmVarDecl>(VD)) {
4075         // Access of a parameter that's not associated with a frame isn't going
4076         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4077         // suitable diagnostic.
4078       } else if (Info.getLangOpts().CPlusPlus14 &&
4079                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4080         // OK, we can read and modify an object if we're in the process of
4081         // evaluating its initializer, because its lifetime began in this
4082         // evaluation.
4083       } else if (isModification(AK)) {
4084         // All the remaining cases do not permit modification of the object.
4085         Info.FFDiag(E, diag::note_constexpr_modify_global);
4086         return CompleteObject();
4087       } else if (VD->isConstexpr()) {
4088         // OK, we can read this variable.
4089       } else if (BaseType->isIntegralOrEnumerationType()) {
4090         if (!IsConstant) {
4091           if (!IsAccess)
4092             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4093           if (Info.getLangOpts().CPlusPlus) {
4094             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4095             Info.Note(VD->getLocation(), diag::note_declared_at);
4096           } else {
4097             Info.FFDiag(E);
4098           }
4099           return CompleteObject();
4100         }
4101       } else if (!IsAccess) {
4102         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4103       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4104                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4105         // This variable might end up being constexpr. Don't diagnose it yet.
4106       } else if (IsConstant) {
4107         // Keep evaluating to see what we can do. In particular, we support
4108         // folding of const floating-point types, in order to make static const
4109         // data members of such types (supported as an extension) more useful.
4110         if (Info.getLangOpts().CPlusPlus) {
4111           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4112                               ? diag::note_constexpr_ltor_non_constexpr
4113                               : diag::note_constexpr_ltor_non_integral, 1)
4114               << VD << BaseType;
4115           Info.Note(VD->getLocation(), diag::note_declared_at);
4116         } else {
4117           Info.CCEDiag(E);
4118         }
4119       } else {
4120         // Never allow reading a non-const value.
4121         if (Info.getLangOpts().CPlusPlus) {
4122           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4123                              ? diag::note_constexpr_ltor_non_constexpr
4124                              : diag::note_constexpr_ltor_non_integral, 1)
4125               << VD << BaseType;
4126           Info.Note(VD->getLocation(), diag::note_declared_at);
4127         } else {
4128           Info.FFDiag(E);
4129         }
4130         return CompleteObject();
4131       }
4132     }
4133 
4134     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4135       return CompleteObject();
4136   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4137     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4138     if (!Alloc) {
4139       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4140       return CompleteObject();
4141     }
4142     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4143                           LVal.Base.getDynamicAllocType());
4144   } else {
4145     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4146 
4147     if (!Frame) {
4148       if (const MaterializeTemporaryExpr *MTE =
4149               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4150         assert(MTE->getStorageDuration() == SD_Static &&
4151                "should have a frame for a non-global materialized temporary");
4152 
4153         // C++20 [expr.const]p4: [DR2126]
4154         //   An object or reference is usable in constant expressions if it is
4155         //   - a temporary object of non-volatile const-qualified literal type
4156         //     whose lifetime is extended to that of a variable that is usable
4157         //     in constant expressions
4158         //
4159         // C++20 [expr.const]p5:
4160         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4161         //   - a non-volatile glvalue that refers to an object that is usable
4162         //     in constant expressions, or
4163         //   - a non-volatile glvalue of literal type that refers to a
4164         //     non-volatile object whose lifetime began within the evaluation
4165         //     of E;
4166         //
4167         // C++11 misses the 'began within the evaluation of e' check and
4168         // instead allows all temporaries, including things like:
4169         //   int &&r = 1;
4170         //   int x = ++r;
4171         //   constexpr int k = r;
4172         // Therefore we use the C++14-onwards rules in C++11 too.
4173         //
4174         // Note that temporaries whose lifetimes began while evaluating a
4175         // variable's constructor are not usable while evaluating the
4176         // corresponding destructor, not even if they're of const-qualified
4177         // types.
4178         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4179             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4180           if (!IsAccess)
4181             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4182           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4183           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4184           return CompleteObject();
4185         }
4186 
4187         BaseVal = MTE->getOrCreateValue(false);
4188         assert(BaseVal && "got reference to unevaluated temporary");
4189       } else {
4190         if (!IsAccess)
4191           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4192         APValue Val;
4193         LVal.moveInto(Val);
4194         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4195             << AK
4196             << Val.getAsString(Info.Ctx,
4197                                Info.Ctx.getLValueReferenceType(LValType));
4198         NoteLValueLocation(Info, LVal.Base);
4199         return CompleteObject();
4200       }
4201     } else {
4202       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4203       assert(BaseVal && "missing value for temporary");
4204     }
4205   }
4206 
4207   // In C++14, we can't safely access any mutable state when we might be
4208   // evaluating after an unmodeled side effect. Parameters are modeled as state
4209   // in the caller, but aren't visible once the call returns, so they can be
4210   // modified in a speculatively-evaluated call.
4211   //
4212   // FIXME: Not all local state is mutable. Allow local constant subobjects
4213   // to be read here (but take care with 'mutable' fields).
4214   unsigned VisibleDepth = Depth;
4215   if (llvm::isa_and_nonnull<ParmVarDecl>(
4216           LVal.Base.dyn_cast<const ValueDecl *>()))
4217     ++VisibleDepth;
4218   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4219        Info.EvalStatus.HasSideEffects) ||
4220       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4221     return CompleteObject();
4222 
4223   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4224 }
4225 
4226 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4227 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4228 /// glvalue referred to by an entity of reference type.
4229 ///
4230 /// \param Info - Information about the ongoing evaluation.
4231 /// \param Conv - The expression for which we are performing the conversion.
4232 ///               Used for diagnostics.
4233 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4234 ///               case of a non-class type).
4235 /// \param LVal - The glvalue on which we are attempting to perform this action.
4236 /// \param RVal - The produced value will be placed here.
4237 /// \param WantObjectRepresentation - If true, we're looking for the object
4238 ///               representation rather than the value, and in particular,
4239 ///               there is no requirement that the result be fully initialized.
4240 static bool
4241 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4242                                const LValue &LVal, APValue &RVal,
4243                                bool WantObjectRepresentation = false) {
4244   if (LVal.Designator.Invalid)
4245     return false;
4246 
4247   // Check for special cases where there is no existing APValue to look at.
4248   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4249 
4250   AccessKinds AK =
4251       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4252 
4253   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4254     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4255       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4256       // initializer until now for such expressions. Such an expression can't be
4257       // an ICE in C, so this only matters for fold.
4258       if (Type.isVolatileQualified()) {
4259         Info.FFDiag(Conv);
4260         return false;
4261       }
4262       APValue Lit;
4263       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4264         return false;
4265       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4266       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4267     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4268       // Special-case character extraction so we don't have to construct an
4269       // APValue for the whole string.
4270       assert(LVal.Designator.Entries.size() <= 1 &&
4271              "Can only read characters from string literals");
4272       if (LVal.Designator.Entries.empty()) {
4273         // Fail for now for LValue to RValue conversion of an array.
4274         // (This shouldn't show up in C/C++, but it could be triggered by a
4275         // weird EvaluateAsRValue call from a tool.)
4276         Info.FFDiag(Conv);
4277         return false;
4278       }
4279       if (LVal.Designator.isOnePastTheEnd()) {
4280         if (Info.getLangOpts().CPlusPlus11)
4281           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4282         else
4283           Info.FFDiag(Conv);
4284         return false;
4285       }
4286       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4287       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4288       return true;
4289     }
4290   }
4291 
4292   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4293   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4294 }
4295 
4296 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4297 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4298                              QualType LValType, APValue &Val) {
4299   if (LVal.Designator.Invalid)
4300     return false;
4301 
4302   if (!Info.getLangOpts().CPlusPlus14) {
4303     Info.FFDiag(E);
4304     return false;
4305   }
4306 
4307   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4308   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4309 }
4310 
4311 namespace {
4312 struct CompoundAssignSubobjectHandler {
4313   EvalInfo &Info;
4314   const CompoundAssignOperator *E;
4315   QualType PromotedLHSType;
4316   BinaryOperatorKind Opcode;
4317   const APValue &RHS;
4318 
4319   static const AccessKinds AccessKind = AK_Assign;
4320 
4321   typedef bool result_type;
4322 
4323   bool checkConst(QualType QT) {
4324     // Assigning to a const object has undefined behavior.
4325     if (QT.isConstQualified()) {
4326       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4327       return false;
4328     }
4329     return true;
4330   }
4331 
4332   bool failed() { return false; }
4333   bool found(APValue &Subobj, QualType SubobjType) {
4334     switch (Subobj.getKind()) {
4335     case APValue::Int:
4336       return found(Subobj.getInt(), SubobjType);
4337     case APValue::Float:
4338       return found(Subobj.getFloat(), SubobjType);
4339     case APValue::ComplexInt:
4340     case APValue::ComplexFloat:
4341       // FIXME: Implement complex compound assignment.
4342       Info.FFDiag(E);
4343       return false;
4344     case APValue::LValue:
4345       return foundPointer(Subobj, SubobjType);
4346     case APValue::Vector:
4347       return foundVector(Subobj, SubobjType);
4348     default:
4349       // FIXME: can this happen?
4350       Info.FFDiag(E);
4351       return false;
4352     }
4353   }
4354 
4355   bool foundVector(APValue &Value, QualType SubobjType) {
4356     if (!checkConst(SubobjType))
4357       return false;
4358 
4359     if (!SubobjType->isVectorType()) {
4360       Info.FFDiag(E);
4361       return false;
4362     }
4363     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4364   }
4365 
4366   bool found(APSInt &Value, QualType SubobjType) {
4367     if (!checkConst(SubobjType))
4368       return false;
4369 
4370     if (!SubobjType->isIntegerType()) {
4371       // We don't support compound assignment on integer-cast-to-pointer
4372       // values.
4373       Info.FFDiag(E);
4374       return false;
4375     }
4376 
4377     if (RHS.isInt()) {
4378       APSInt LHS =
4379           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4380       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4381         return false;
4382       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4383       return true;
4384     } else if (RHS.isFloat()) {
4385       const FPOptions FPO = E->getFPFeaturesInEffect(
4386                                     Info.Ctx.getLangOpts());
4387       APFloat FValue(0.0);
4388       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4389                                   PromotedLHSType, FValue) &&
4390              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4391              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4392                                   Value);
4393     }
4394 
4395     Info.FFDiag(E);
4396     return false;
4397   }
4398   bool found(APFloat &Value, QualType SubobjType) {
4399     return checkConst(SubobjType) &&
4400            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4401                                   Value) &&
4402            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4403            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4404   }
4405   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4406     if (!checkConst(SubobjType))
4407       return false;
4408 
4409     QualType PointeeType;
4410     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4411       PointeeType = PT->getPointeeType();
4412 
4413     if (PointeeType.isNull() || !RHS.isInt() ||
4414         (Opcode != BO_Add && Opcode != BO_Sub)) {
4415       Info.FFDiag(E);
4416       return false;
4417     }
4418 
4419     APSInt Offset = RHS.getInt();
4420     if (Opcode == BO_Sub)
4421       negateAsSigned(Offset);
4422 
4423     LValue LVal;
4424     LVal.setFrom(Info.Ctx, Subobj);
4425     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4426       return false;
4427     LVal.moveInto(Subobj);
4428     return true;
4429   }
4430 };
4431 } // end anonymous namespace
4432 
4433 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4434 
4435 /// Perform a compound assignment of LVal <op>= RVal.
4436 static bool handleCompoundAssignment(EvalInfo &Info,
4437                                      const CompoundAssignOperator *E,
4438                                      const LValue &LVal, QualType LValType,
4439                                      QualType PromotedLValType,
4440                                      BinaryOperatorKind Opcode,
4441                                      const APValue &RVal) {
4442   if (LVal.Designator.Invalid)
4443     return false;
4444 
4445   if (!Info.getLangOpts().CPlusPlus14) {
4446     Info.FFDiag(E);
4447     return false;
4448   }
4449 
4450   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4451   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4452                                              RVal };
4453   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4454 }
4455 
4456 namespace {
4457 struct IncDecSubobjectHandler {
4458   EvalInfo &Info;
4459   const UnaryOperator *E;
4460   AccessKinds AccessKind;
4461   APValue *Old;
4462 
4463   typedef bool result_type;
4464 
4465   bool checkConst(QualType QT) {
4466     // Assigning to a const object has undefined behavior.
4467     if (QT.isConstQualified()) {
4468       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4469       return false;
4470     }
4471     return true;
4472   }
4473 
4474   bool failed() { return false; }
4475   bool found(APValue &Subobj, QualType SubobjType) {
4476     // Stash the old value. Also clear Old, so we don't clobber it later
4477     // if we're post-incrementing a complex.
4478     if (Old) {
4479       *Old = Subobj;
4480       Old = nullptr;
4481     }
4482 
4483     switch (Subobj.getKind()) {
4484     case APValue::Int:
4485       return found(Subobj.getInt(), SubobjType);
4486     case APValue::Float:
4487       return found(Subobj.getFloat(), SubobjType);
4488     case APValue::ComplexInt:
4489       return found(Subobj.getComplexIntReal(),
4490                    SubobjType->castAs<ComplexType>()->getElementType()
4491                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4492     case APValue::ComplexFloat:
4493       return found(Subobj.getComplexFloatReal(),
4494                    SubobjType->castAs<ComplexType>()->getElementType()
4495                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4496     case APValue::LValue:
4497       return foundPointer(Subobj, SubobjType);
4498     default:
4499       // FIXME: can this happen?
4500       Info.FFDiag(E);
4501       return false;
4502     }
4503   }
4504   bool found(APSInt &Value, QualType SubobjType) {
4505     if (!checkConst(SubobjType))
4506       return false;
4507 
4508     if (!SubobjType->isIntegerType()) {
4509       // We don't support increment / decrement on integer-cast-to-pointer
4510       // values.
4511       Info.FFDiag(E);
4512       return false;
4513     }
4514 
4515     if (Old) *Old = APValue(Value);
4516 
4517     // bool arithmetic promotes to int, and the conversion back to bool
4518     // doesn't reduce mod 2^n, so special-case it.
4519     if (SubobjType->isBooleanType()) {
4520       if (AccessKind == AK_Increment)
4521         Value = 1;
4522       else
4523         Value = !Value;
4524       return true;
4525     }
4526 
4527     bool WasNegative = Value.isNegative();
4528     if (AccessKind == AK_Increment) {
4529       ++Value;
4530 
4531       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4532         APSInt ActualValue(Value, /*IsUnsigned*/true);
4533         return HandleOverflow(Info, E, ActualValue, SubobjType);
4534       }
4535     } else {
4536       --Value;
4537 
4538       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4539         unsigned BitWidth = Value.getBitWidth();
4540         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4541         ActualValue.setBit(BitWidth);
4542         return HandleOverflow(Info, E, ActualValue, SubobjType);
4543       }
4544     }
4545     return true;
4546   }
4547   bool found(APFloat &Value, QualType SubobjType) {
4548     if (!checkConst(SubobjType))
4549       return false;
4550 
4551     if (Old) *Old = APValue(Value);
4552 
4553     APFloat One(Value.getSemantics(), 1);
4554     if (AccessKind == AK_Increment)
4555       Value.add(One, APFloat::rmNearestTiesToEven);
4556     else
4557       Value.subtract(One, APFloat::rmNearestTiesToEven);
4558     return true;
4559   }
4560   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4561     if (!checkConst(SubobjType))
4562       return false;
4563 
4564     QualType PointeeType;
4565     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4566       PointeeType = PT->getPointeeType();
4567     else {
4568       Info.FFDiag(E);
4569       return false;
4570     }
4571 
4572     LValue LVal;
4573     LVal.setFrom(Info.Ctx, Subobj);
4574     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4575                                      AccessKind == AK_Increment ? 1 : -1))
4576       return false;
4577     LVal.moveInto(Subobj);
4578     return true;
4579   }
4580 };
4581 } // end anonymous namespace
4582 
4583 /// Perform an increment or decrement on LVal.
4584 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4585                          QualType LValType, bool IsIncrement, APValue *Old) {
4586   if (LVal.Designator.Invalid)
4587     return false;
4588 
4589   if (!Info.getLangOpts().CPlusPlus14) {
4590     Info.FFDiag(E);
4591     return false;
4592   }
4593 
4594   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4595   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4596   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4597   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4598 }
4599 
4600 /// Build an lvalue for the object argument of a member function call.
4601 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4602                                    LValue &This) {
4603   if (Object->getType()->isPointerType() && Object->isPRValue())
4604     return EvaluatePointer(Object, This, Info);
4605 
4606   if (Object->isGLValue())
4607     return EvaluateLValue(Object, This, Info);
4608 
4609   if (Object->getType()->isLiteralType(Info.Ctx))
4610     return EvaluateTemporary(Object, This, Info);
4611 
4612   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4613   return false;
4614 }
4615 
4616 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4617 /// lvalue referring to the result.
4618 ///
4619 /// \param Info - Information about the ongoing evaluation.
4620 /// \param LV - An lvalue referring to the base of the member pointer.
4621 /// \param RHS - The member pointer expression.
4622 /// \param IncludeMember - Specifies whether the member itself is included in
4623 ///        the resulting LValue subobject designator. This is not possible when
4624 ///        creating a bound member function.
4625 /// \return The field or method declaration to which the member pointer refers,
4626 ///         or 0 if evaluation fails.
4627 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4628                                                   QualType LVType,
4629                                                   LValue &LV,
4630                                                   const Expr *RHS,
4631                                                   bool IncludeMember = true) {
4632   MemberPtr MemPtr;
4633   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4634     return nullptr;
4635 
4636   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4637   // member value, the behavior is undefined.
4638   if (!MemPtr.getDecl()) {
4639     // FIXME: Specific diagnostic.
4640     Info.FFDiag(RHS);
4641     return nullptr;
4642   }
4643 
4644   if (MemPtr.isDerivedMember()) {
4645     // This is a member of some derived class. Truncate LV appropriately.
4646     // The end of the derived-to-base path for the base object must match the
4647     // derived-to-base path for the member pointer.
4648     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4649         LV.Designator.Entries.size()) {
4650       Info.FFDiag(RHS);
4651       return nullptr;
4652     }
4653     unsigned PathLengthToMember =
4654         LV.Designator.Entries.size() - MemPtr.Path.size();
4655     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4656       const CXXRecordDecl *LVDecl = getAsBaseClass(
4657           LV.Designator.Entries[PathLengthToMember + I]);
4658       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4659       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4660         Info.FFDiag(RHS);
4661         return nullptr;
4662       }
4663     }
4664 
4665     // Truncate the lvalue to the appropriate derived class.
4666     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4667                             PathLengthToMember))
4668       return nullptr;
4669   } else if (!MemPtr.Path.empty()) {
4670     // Extend the LValue path with the member pointer's path.
4671     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4672                                   MemPtr.Path.size() + IncludeMember);
4673 
4674     // Walk down to the appropriate base class.
4675     if (const PointerType *PT = LVType->getAs<PointerType>())
4676       LVType = PT->getPointeeType();
4677     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4678     assert(RD && "member pointer access on non-class-type expression");
4679     // The first class in the path is that of the lvalue.
4680     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4681       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4682       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4683         return nullptr;
4684       RD = Base;
4685     }
4686     // Finally cast to the class containing the member.
4687     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4688                                 MemPtr.getContainingRecord()))
4689       return nullptr;
4690   }
4691 
4692   // Add the member. Note that we cannot build bound member functions here.
4693   if (IncludeMember) {
4694     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4695       if (!HandleLValueMember(Info, RHS, LV, FD))
4696         return nullptr;
4697     } else if (const IndirectFieldDecl *IFD =
4698                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4699       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4700         return nullptr;
4701     } else {
4702       llvm_unreachable("can't construct reference to bound member function");
4703     }
4704   }
4705 
4706   return MemPtr.getDecl();
4707 }
4708 
4709 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4710                                                   const BinaryOperator *BO,
4711                                                   LValue &LV,
4712                                                   bool IncludeMember = true) {
4713   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4714 
4715   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4716     if (Info.noteFailure()) {
4717       MemberPtr MemPtr;
4718       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4719     }
4720     return nullptr;
4721   }
4722 
4723   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4724                                    BO->getRHS(), IncludeMember);
4725 }
4726 
4727 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4728 /// the provided lvalue, which currently refers to the base object.
4729 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4730                                     LValue &Result) {
4731   SubobjectDesignator &D = Result.Designator;
4732   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4733     return false;
4734 
4735   QualType TargetQT = E->getType();
4736   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4737     TargetQT = PT->getPointeeType();
4738 
4739   // Check this cast lands within the final derived-to-base subobject path.
4740   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4741     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4742       << D.MostDerivedType << TargetQT;
4743     return false;
4744   }
4745 
4746   // Check the type of the final cast. We don't need to check the path,
4747   // since a cast can only be formed if the path is unique.
4748   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4749   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4750   const CXXRecordDecl *FinalType;
4751   if (NewEntriesSize == D.MostDerivedPathLength)
4752     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4753   else
4754     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4755   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4756     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4757       << D.MostDerivedType << TargetQT;
4758     return false;
4759   }
4760 
4761   // Truncate the lvalue to the appropriate derived class.
4762   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4763 }
4764 
4765 /// Get the value to use for a default-initialized object of type T.
4766 /// Return false if it encounters something invalid.
4767 static bool getDefaultInitValue(QualType T, APValue &Result) {
4768   bool Success = true;
4769   if (auto *RD = T->getAsCXXRecordDecl()) {
4770     if (RD->isInvalidDecl()) {
4771       Result = APValue();
4772       return false;
4773     }
4774     if (RD->isUnion()) {
4775       Result = APValue((const FieldDecl *)nullptr);
4776       return true;
4777     }
4778     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4779                      std::distance(RD->field_begin(), RD->field_end()));
4780 
4781     unsigned Index = 0;
4782     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4783                                                   End = RD->bases_end();
4784          I != End; ++I, ++Index)
4785       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4786 
4787     for (const auto *I : RD->fields()) {
4788       if (I->isUnnamedBitfield())
4789         continue;
4790       Success &= getDefaultInitValue(I->getType(),
4791                                      Result.getStructField(I->getFieldIndex()));
4792     }
4793     return Success;
4794   }
4795 
4796   if (auto *AT =
4797           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4798     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4799     if (Result.hasArrayFiller())
4800       Success &=
4801           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4802 
4803     return Success;
4804   }
4805 
4806   Result = APValue::IndeterminateValue();
4807   return true;
4808 }
4809 
4810 namespace {
4811 enum EvalStmtResult {
4812   /// Evaluation failed.
4813   ESR_Failed,
4814   /// Hit a 'return' statement.
4815   ESR_Returned,
4816   /// Evaluation succeeded.
4817   ESR_Succeeded,
4818   /// Hit a 'continue' statement.
4819   ESR_Continue,
4820   /// Hit a 'break' statement.
4821   ESR_Break,
4822   /// Still scanning for 'case' or 'default' statement.
4823   ESR_CaseNotFound
4824 };
4825 }
4826 
4827 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4828   // We don't need to evaluate the initializer for a static local.
4829   if (!VD->hasLocalStorage())
4830     return true;
4831 
4832   LValue Result;
4833   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4834                                                    ScopeKind::Block, Result);
4835 
4836   const Expr *InitE = VD->getInit();
4837   if (!InitE) {
4838     if (VD->getType()->isDependentType())
4839       return Info.noteSideEffect();
4840     return getDefaultInitValue(VD->getType(), Val);
4841   }
4842   if (InitE->isValueDependent())
4843     return false;
4844 
4845   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4846     // Wipe out any partially-computed value, to allow tracking that this
4847     // evaluation failed.
4848     Val = APValue();
4849     return false;
4850   }
4851 
4852   return true;
4853 }
4854 
4855 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4856   bool OK = true;
4857 
4858   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4859     OK &= EvaluateVarDecl(Info, VD);
4860 
4861   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4862     for (auto *BD : DD->bindings())
4863       if (auto *VD = BD->getHoldingVar())
4864         OK &= EvaluateDecl(Info, VD);
4865 
4866   return OK;
4867 }
4868 
4869 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4870   assert(E->isValueDependent());
4871   if (Info.noteSideEffect())
4872     return true;
4873   assert(E->containsErrors() && "valid value-dependent expression should never "
4874                                 "reach invalid code path.");
4875   return false;
4876 }
4877 
4878 /// Evaluate a condition (either a variable declaration or an expression).
4879 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4880                          const Expr *Cond, bool &Result) {
4881   if (Cond->isValueDependent())
4882     return false;
4883   FullExpressionRAII Scope(Info);
4884   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4885     return false;
4886   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4887     return false;
4888   return Scope.destroy();
4889 }
4890 
4891 namespace {
4892 /// A location where the result (returned value) of evaluating a
4893 /// statement should be stored.
4894 struct StmtResult {
4895   /// The APValue that should be filled in with the returned value.
4896   APValue &Value;
4897   /// The location containing the result, if any (used to support RVO).
4898   const LValue *Slot;
4899 };
4900 
4901 struct TempVersionRAII {
4902   CallStackFrame &Frame;
4903 
4904   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4905     Frame.pushTempVersion();
4906   }
4907 
4908   ~TempVersionRAII() {
4909     Frame.popTempVersion();
4910   }
4911 };
4912 
4913 }
4914 
4915 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4916                                    const Stmt *S,
4917                                    const SwitchCase *SC = nullptr);
4918 
4919 /// Evaluate the body of a loop, and translate the result as appropriate.
4920 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4921                                        const Stmt *Body,
4922                                        const SwitchCase *Case = nullptr) {
4923   BlockScopeRAII Scope(Info);
4924 
4925   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4926   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4927     ESR = ESR_Failed;
4928 
4929   switch (ESR) {
4930   case ESR_Break:
4931     return ESR_Succeeded;
4932   case ESR_Succeeded:
4933   case ESR_Continue:
4934     return ESR_Continue;
4935   case ESR_Failed:
4936   case ESR_Returned:
4937   case ESR_CaseNotFound:
4938     return ESR;
4939   }
4940   llvm_unreachable("Invalid EvalStmtResult!");
4941 }
4942 
4943 /// Evaluate a switch statement.
4944 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4945                                      const SwitchStmt *SS) {
4946   BlockScopeRAII Scope(Info);
4947 
4948   // Evaluate the switch condition.
4949   APSInt Value;
4950   {
4951     if (const Stmt *Init = SS->getInit()) {
4952       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4953       if (ESR != ESR_Succeeded) {
4954         if (ESR != ESR_Failed && !Scope.destroy())
4955           ESR = ESR_Failed;
4956         return ESR;
4957       }
4958     }
4959 
4960     FullExpressionRAII CondScope(Info);
4961     if (SS->getConditionVariable() &&
4962         !EvaluateDecl(Info, SS->getConditionVariable()))
4963       return ESR_Failed;
4964     if (SS->getCond()->isValueDependent()) {
4965       if (!EvaluateDependentExpr(SS->getCond(), Info))
4966         return ESR_Failed;
4967     } else {
4968       if (!EvaluateInteger(SS->getCond(), Value, Info))
4969         return ESR_Failed;
4970     }
4971     if (!CondScope.destroy())
4972       return ESR_Failed;
4973   }
4974 
4975   // Find the switch case corresponding to the value of the condition.
4976   // FIXME: Cache this lookup.
4977   const SwitchCase *Found = nullptr;
4978   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4979        SC = SC->getNextSwitchCase()) {
4980     if (isa<DefaultStmt>(SC)) {
4981       Found = SC;
4982       continue;
4983     }
4984 
4985     const CaseStmt *CS = cast<CaseStmt>(SC);
4986     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4987     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4988                               : LHS;
4989     if (LHS <= Value && Value <= RHS) {
4990       Found = SC;
4991       break;
4992     }
4993   }
4994 
4995   if (!Found)
4996     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4997 
4998   // Search the switch body for the switch case and evaluate it from there.
4999   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5000   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5001     return ESR_Failed;
5002 
5003   switch (ESR) {
5004   case ESR_Break:
5005     return ESR_Succeeded;
5006   case ESR_Succeeded:
5007   case ESR_Continue:
5008   case ESR_Failed:
5009   case ESR_Returned:
5010     return ESR;
5011   case ESR_CaseNotFound:
5012     // This can only happen if the switch case is nested within a statement
5013     // expression. We have no intention of supporting that.
5014     Info.FFDiag(Found->getBeginLoc(),
5015                 diag::note_constexpr_stmt_expr_unsupported);
5016     return ESR_Failed;
5017   }
5018   llvm_unreachable("Invalid EvalStmtResult!");
5019 }
5020 
5021 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5022   // An expression E is a core constant expression unless the evaluation of E
5023   // would evaluate one of the following: [C++2b] - a control flow that passes
5024   // through a declaration of a variable with static or thread storage duration.
5025   if (VD->isLocalVarDecl() && VD->isStaticLocal()) {
5026     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5027         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5028     return false;
5029   }
5030   return true;
5031 }
5032 
5033 // Evaluate a statement.
5034 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5035                                    const Stmt *S, const SwitchCase *Case) {
5036   if (!Info.nextStep(S))
5037     return ESR_Failed;
5038 
5039   // If we're hunting down a 'case' or 'default' label, recurse through
5040   // substatements until we hit the label.
5041   if (Case) {
5042     switch (S->getStmtClass()) {
5043     case Stmt::CompoundStmtClass:
5044       // FIXME: Precompute which substatement of a compound statement we
5045       // would jump to, and go straight there rather than performing a
5046       // linear scan each time.
5047     case Stmt::LabelStmtClass:
5048     case Stmt::AttributedStmtClass:
5049     case Stmt::DoStmtClass:
5050       break;
5051 
5052     case Stmt::CaseStmtClass:
5053     case Stmt::DefaultStmtClass:
5054       if (Case == S)
5055         Case = nullptr;
5056       break;
5057 
5058     case Stmt::IfStmtClass: {
5059       // FIXME: Precompute which side of an 'if' we would jump to, and go
5060       // straight there rather than scanning both sides.
5061       const IfStmt *IS = cast<IfStmt>(S);
5062 
5063       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5064       // preceded by our switch label.
5065       BlockScopeRAII Scope(Info);
5066 
5067       // Step into the init statement in case it brings an (uninitialized)
5068       // variable into scope.
5069       if (const Stmt *Init = IS->getInit()) {
5070         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5071         if (ESR != ESR_CaseNotFound) {
5072           assert(ESR != ESR_Succeeded);
5073           return ESR;
5074         }
5075       }
5076 
5077       // Condition variable must be initialized if it exists.
5078       // FIXME: We can skip evaluating the body if there's a condition
5079       // variable, as there can't be any case labels within it.
5080       // (The same is true for 'for' statements.)
5081 
5082       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5083       if (ESR == ESR_Failed)
5084         return ESR;
5085       if (ESR != ESR_CaseNotFound)
5086         return Scope.destroy() ? ESR : ESR_Failed;
5087       if (!IS->getElse())
5088         return ESR_CaseNotFound;
5089 
5090       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5091       if (ESR == ESR_Failed)
5092         return ESR;
5093       if (ESR != ESR_CaseNotFound)
5094         return Scope.destroy() ? ESR : ESR_Failed;
5095       return ESR_CaseNotFound;
5096     }
5097 
5098     case Stmt::WhileStmtClass: {
5099       EvalStmtResult ESR =
5100           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5101       if (ESR != ESR_Continue)
5102         return ESR;
5103       break;
5104     }
5105 
5106     case Stmt::ForStmtClass: {
5107       const ForStmt *FS = cast<ForStmt>(S);
5108       BlockScopeRAII Scope(Info);
5109 
5110       // Step into the init statement in case it brings an (uninitialized)
5111       // variable into scope.
5112       if (const Stmt *Init = FS->getInit()) {
5113         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5114         if (ESR != ESR_CaseNotFound) {
5115           assert(ESR != ESR_Succeeded);
5116           return ESR;
5117         }
5118       }
5119 
5120       EvalStmtResult ESR =
5121           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5122       if (ESR != ESR_Continue)
5123         return ESR;
5124       if (const auto *Inc = FS->getInc()) {
5125         if (Inc->isValueDependent()) {
5126           if (!EvaluateDependentExpr(Inc, Info))
5127             return ESR_Failed;
5128         } else {
5129           FullExpressionRAII IncScope(Info);
5130           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5131             return ESR_Failed;
5132         }
5133       }
5134       break;
5135     }
5136 
5137     case Stmt::DeclStmtClass: {
5138       // Start the lifetime of any uninitialized variables we encounter. They
5139       // might be used by the selected branch of the switch.
5140       const DeclStmt *DS = cast<DeclStmt>(S);
5141       for (const auto *D : DS->decls()) {
5142         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5143           if (!CheckLocalVariableDeclaration(Info, VD))
5144             return ESR_Failed;
5145           if (VD->hasLocalStorage() && !VD->getInit())
5146             if (!EvaluateVarDecl(Info, VD))
5147               return ESR_Failed;
5148           // FIXME: If the variable has initialization that can't be jumped
5149           // over, bail out of any immediately-surrounding compound-statement
5150           // too. There can't be any case labels here.
5151         }
5152       }
5153       return ESR_CaseNotFound;
5154     }
5155 
5156     default:
5157       return ESR_CaseNotFound;
5158     }
5159   }
5160 
5161   switch (S->getStmtClass()) {
5162   default:
5163     if (const Expr *E = dyn_cast<Expr>(S)) {
5164       if (E->isValueDependent()) {
5165         if (!EvaluateDependentExpr(E, Info))
5166           return ESR_Failed;
5167       } else {
5168         // Don't bother evaluating beyond an expression-statement which couldn't
5169         // be evaluated.
5170         // FIXME: Do we need the FullExpressionRAII object here?
5171         // VisitExprWithCleanups should create one when necessary.
5172         FullExpressionRAII Scope(Info);
5173         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5174           return ESR_Failed;
5175       }
5176       return ESR_Succeeded;
5177     }
5178 
5179     Info.FFDiag(S->getBeginLoc());
5180     return ESR_Failed;
5181 
5182   case Stmt::NullStmtClass:
5183     return ESR_Succeeded;
5184 
5185   case Stmt::DeclStmtClass: {
5186     const DeclStmt *DS = cast<DeclStmt>(S);
5187     for (const auto *D : DS->decls()) {
5188       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5189       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5190         return ESR_Failed;
5191       // Each declaration initialization is its own full-expression.
5192       FullExpressionRAII Scope(Info);
5193       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5194         return ESR_Failed;
5195       if (!Scope.destroy())
5196         return ESR_Failed;
5197     }
5198     return ESR_Succeeded;
5199   }
5200 
5201   case Stmt::ReturnStmtClass: {
5202     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5203     FullExpressionRAII Scope(Info);
5204     if (RetExpr && RetExpr->isValueDependent()) {
5205       EvaluateDependentExpr(RetExpr, Info);
5206       // We know we returned, but we don't know what the value is.
5207       return ESR_Failed;
5208     }
5209     if (RetExpr &&
5210         !(Result.Slot
5211               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5212               : Evaluate(Result.Value, Info, RetExpr)))
5213       return ESR_Failed;
5214     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5215   }
5216 
5217   case Stmt::CompoundStmtClass: {
5218     BlockScopeRAII Scope(Info);
5219 
5220     const CompoundStmt *CS = cast<CompoundStmt>(S);
5221     for (const auto *BI : CS->body()) {
5222       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5223       if (ESR == ESR_Succeeded)
5224         Case = nullptr;
5225       else if (ESR != ESR_CaseNotFound) {
5226         if (ESR != ESR_Failed && !Scope.destroy())
5227           return ESR_Failed;
5228         return ESR;
5229       }
5230     }
5231     if (Case)
5232       return ESR_CaseNotFound;
5233     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5234   }
5235 
5236   case Stmt::IfStmtClass: {
5237     const IfStmt *IS = cast<IfStmt>(S);
5238 
5239     // Evaluate the condition, as either a var decl or as an expression.
5240     BlockScopeRAII Scope(Info);
5241     if (const Stmt *Init = IS->getInit()) {
5242       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5243       if (ESR != ESR_Succeeded) {
5244         if (ESR != ESR_Failed && !Scope.destroy())
5245           return ESR_Failed;
5246         return ESR;
5247       }
5248     }
5249     bool Cond;
5250     if (IS->isConsteval())
5251       Cond = IS->isNonNegatedConsteval();
5252     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5253                            Cond))
5254       return ESR_Failed;
5255 
5256     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5257       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5258       if (ESR != ESR_Succeeded) {
5259         if (ESR != ESR_Failed && !Scope.destroy())
5260           return ESR_Failed;
5261         return ESR;
5262       }
5263     }
5264     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5265   }
5266 
5267   case Stmt::WhileStmtClass: {
5268     const WhileStmt *WS = cast<WhileStmt>(S);
5269     while (true) {
5270       BlockScopeRAII Scope(Info);
5271       bool Continue;
5272       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5273                         Continue))
5274         return ESR_Failed;
5275       if (!Continue)
5276         break;
5277 
5278       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5279       if (ESR != ESR_Continue) {
5280         if (ESR != ESR_Failed && !Scope.destroy())
5281           return ESR_Failed;
5282         return ESR;
5283       }
5284       if (!Scope.destroy())
5285         return ESR_Failed;
5286     }
5287     return ESR_Succeeded;
5288   }
5289 
5290   case Stmt::DoStmtClass: {
5291     const DoStmt *DS = cast<DoStmt>(S);
5292     bool Continue;
5293     do {
5294       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5295       if (ESR != ESR_Continue)
5296         return ESR;
5297       Case = nullptr;
5298 
5299       if (DS->getCond()->isValueDependent()) {
5300         EvaluateDependentExpr(DS->getCond(), Info);
5301         // Bailout as we don't know whether to keep going or terminate the loop.
5302         return ESR_Failed;
5303       }
5304       FullExpressionRAII CondScope(Info);
5305       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5306           !CondScope.destroy())
5307         return ESR_Failed;
5308     } while (Continue);
5309     return ESR_Succeeded;
5310   }
5311 
5312   case Stmt::ForStmtClass: {
5313     const ForStmt *FS = cast<ForStmt>(S);
5314     BlockScopeRAII ForScope(Info);
5315     if (FS->getInit()) {
5316       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5317       if (ESR != ESR_Succeeded) {
5318         if (ESR != ESR_Failed && !ForScope.destroy())
5319           return ESR_Failed;
5320         return ESR;
5321       }
5322     }
5323     while (true) {
5324       BlockScopeRAII IterScope(Info);
5325       bool Continue = true;
5326       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5327                                          FS->getCond(), Continue))
5328         return ESR_Failed;
5329       if (!Continue)
5330         break;
5331 
5332       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5333       if (ESR != ESR_Continue) {
5334         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5335           return ESR_Failed;
5336         return ESR;
5337       }
5338 
5339       if (const auto *Inc = FS->getInc()) {
5340         if (Inc->isValueDependent()) {
5341           if (!EvaluateDependentExpr(Inc, Info))
5342             return ESR_Failed;
5343         } else {
5344           FullExpressionRAII IncScope(Info);
5345           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5346             return ESR_Failed;
5347         }
5348       }
5349 
5350       if (!IterScope.destroy())
5351         return ESR_Failed;
5352     }
5353     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5354   }
5355 
5356   case Stmt::CXXForRangeStmtClass: {
5357     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5358     BlockScopeRAII Scope(Info);
5359 
5360     // Evaluate the init-statement if present.
5361     if (FS->getInit()) {
5362       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5363       if (ESR != ESR_Succeeded) {
5364         if (ESR != ESR_Failed && !Scope.destroy())
5365           return ESR_Failed;
5366         return ESR;
5367       }
5368     }
5369 
5370     // Initialize the __range variable.
5371     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5372     if (ESR != ESR_Succeeded) {
5373       if (ESR != ESR_Failed && !Scope.destroy())
5374         return ESR_Failed;
5375       return ESR;
5376     }
5377 
5378     // In error-recovery cases it's possible to get here even if we failed to
5379     // synthesize the __begin and __end variables.
5380     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5381       return ESR_Failed;
5382 
5383     // Create the __begin and __end iterators.
5384     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5385     if (ESR != ESR_Succeeded) {
5386       if (ESR != ESR_Failed && !Scope.destroy())
5387         return ESR_Failed;
5388       return ESR;
5389     }
5390     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5391     if (ESR != ESR_Succeeded) {
5392       if (ESR != ESR_Failed && !Scope.destroy())
5393         return ESR_Failed;
5394       return ESR;
5395     }
5396 
5397     while (true) {
5398       // Condition: __begin != __end.
5399       {
5400         if (FS->getCond()->isValueDependent()) {
5401           EvaluateDependentExpr(FS->getCond(), Info);
5402           // We don't know whether to keep going or terminate the loop.
5403           return ESR_Failed;
5404         }
5405         bool Continue = true;
5406         FullExpressionRAII CondExpr(Info);
5407         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5408           return ESR_Failed;
5409         if (!Continue)
5410           break;
5411       }
5412 
5413       // User's variable declaration, initialized by *__begin.
5414       BlockScopeRAII InnerScope(Info);
5415       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5416       if (ESR != ESR_Succeeded) {
5417         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5418           return ESR_Failed;
5419         return ESR;
5420       }
5421 
5422       // Loop body.
5423       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5424       if (ESR != ESR_Continue) {
5425         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5426           return ESR_Failed;
5427         return ESR;
5428       }
5429       if (FS->getInc()->isValueDependent()) {
5430         if (!EvaluateDependentExpr(FS->getInc(), Info))
5431           return ESR_Failed;
5432       } else {
5433         // Increment: ++__begin
5434         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5435           return ESR_Failed;
5436       }
5437 
5438       if (!InnerScope.destroy())
5439         return ESR_Failed;
5440     }
5441 
5442     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5443   }
5444 
5445   case Stmt::SwitchStmtClass:
5446     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5447 
5448   case Stmt::ContinueStmtClass:
5449     return ESR_Continue;
5450 
5451   case Stmt::BreakStmtClass:
5452     return ESR_Break;
5453 
5454   case Stmt::LabelStmtClass:
5455     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5456 
5457   case Stmt::AttributedStmtClass:
5458     // As a general principle, C++11 attributes can be ignored without
5459     // any semantic impact.
5460     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5461                         Case);
5462 
5463   case Stmt::CaseStmtClass:
5464   case Stmt::DefaultStmtClass:
5465     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5466   case Stmt::CXXTryStmtClass:
5467     // Evaluate try blocks by evaluating all sub statements.
5468     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5469   }
5470 }
5471 
5472 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5473 /// default constructor. If so, we'll fold it whether or not it's marked as
5474 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5475 /// so we need special handling.
5476 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5477                                            const CXXConstructorDecl *CD,
5478                                            bool IsValueInitialization) {
5479   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5480     return false;
5481 
5482   // Value-initialization does not call a trivial default constructor, so such a
5483   // call is a core constant expression whether or not the constructor is
5484   // constexpr.
5485   if (!CD->isConstexpr() && !IsValueInitialization) {
5486     if (Info.getLangOpts().CPlusPlus11) {
5487       // FIXME: If DiagDecl is an implicitly-declared special member function,
5488       // we should be much more explicit about why it's not constexpr.
5489       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5490         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5491       Info.Note(CD->getLocation(), diag::note_declared_at);
5492     } else {
5493       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5494     }
5495   }
5496   return true;
5497 }
5498 
5499 /// CheckConstexprFunction - Check that a function can be called in a constant
5500 /// expression.
5501 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5502                                    const FunctionDecl *Declaration,
5503                                    const FunctionDecl *Definition,
5504                                    const Stmt *Body) {
5505   // Potential constant expressions can contain calls to declared, but not yet
5506   // defined, constexpr functions.
5507   if (Info.checkingPotentialConstantExpression() && !Definition &&
5508       Declaration->isConstexpr())
5509     return false;
5510 
5511   // Bail out if the function declaration itself is invalid.  We will
5512   // have produced a relevant diagnostic while parsing it, so just
5513   // note the problematic sub-expression.
5514   if (Declaration->isInvalidDecl()) {
5515     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5516     return false;
5517   }
5518 
5519   // DR1872: An instantiated virtual constexpr function can't be called in a
5520   // constant expression (prior to C++20). We can still constant-fold such a
5521   // call.
5522   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5523       cast<CXXMethodDecl>(Declaration)->isVirtual())
5524     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5525 
5526   if (Definition && Definition->isInvalidDecl()) {
5527     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5528     return false;
5529   }
5530 
5531   // Can we evaluate this function call?
5532   if (Definition && Definition->isConstexpr() && Body)
5533     return true;
5534 
5535   if (Info.getLangOpts().CPlusPlus11) {
5536     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5537 
5538     // If this function is not constexpr because it is an inherited
5539     // non-constexpr constructor, diagnose that directly.
5540     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5541     if (CD && CD->isInheritingConstructor()) {
5542       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5543       if (!Inherited->isConstexpr())
5544         DiagDecl = CD = Inherited;
5545     }
5546 
5547     // FIXME: If DiagDecl is an implicitly-declared special member function
5548     // or an inheriting constructor, we should be much more explicit about why
5549     // it's not constexpr.
5550     if (CD && CD->isInheritingConstructor())
5551       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5552         << CD->getInheritedConstructor().getConstructor()->getParent();
5553     else
5554       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5555         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5556     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5557   } else {
5558     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5559   }
5560   return false;
5561 }
5562 
5563 namespace {
5564 struct CheckDynamicTypeHandler {
5565   AccessKinds AccessKind;
5566   typedef bool result_type;
5567   bool failed() { return false; }
5568   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5569   bool found(APSInt &Value, QualType SubobjType) { return true; }
5570   bool found(APFloat &Value, QualType SubobjType) { return true; }
5571 };
5572 } // end anonymous namespace
5573 
5574 /// Check that we can access the notional vptr of an object / determine its
5575 /// dynamic type.
5576 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5577                              AccessKinds AK, bool Polymorphic) {
5578   if (This.Designator.Invalid)
5579     return false;
5580 
5581   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5582 
5583   if (!Obj)
5584     return false;
5585 
5586   if (!Obj.Value) {
5587     // The object is not usable in constant expressions, so we can't inspect
5588     // its value to see if it's in-lifetime or what the active union members
5589     // are. We can still check for a one-past-the-end lvalue.
5590     if (This.Designator.isOnePastTheEnd() ||
5591         This.Designator.isMostDerivedAnUnsizedArray()) {
5592       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5593                          ? diag::note_constexpr_access_past_end
5594                          : diag::note_constexpr_access_unsized_array)
5595           << AK;
5596       return false;
5597     } else if (Polymorphic) {
5598       // Conservatively refuse to perform a polymorphic operation if we would
5599       // not be able to read a notional 'vptr' value.
5600       APValue Val;
5601       This.moveInto(Val);
5602       QualType StarThisType =
5603           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5604       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5605           << AK << Val.getAsString(Info.Ctx, StarThisType);
5606       return false;
5607     }
5608     return true;
5609   }
5610 
5611   CheckDynamicTypeHandler Handler{AK};
5612   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5613 }
5614 
5615 /// Check that the pointee of the 'this' pointer in a member function call is
5616 /// either within its lifetime or in its period of construction or destruction.
5617 static bool
5618 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5619                                      const LValue &This,
5620                                      const CXXMethodDecl *NamedMember) {
5621   return checkDynamicType(
5622       Info, E, This,
5623       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5624 }
5625 
5626 struct DynamicType {
5627   /// The dynamic class type of the object.
5628   const CXXRecordDecl *Type;
5629   /// The corresponding path length in the lvalue.
5630   unsigned PathLength;
5631 };
5632 
5633 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5634                                              unsigned PathLength) {
5635   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5636       Designator.Entries.size() && "invalid path length");
5637   return (PathLength == Designator.MostDerivedPathLength)
5638              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5639              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5640 }
5641 
5642 /// Determine the dynamic type of an object.
5643 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5644                                                 LValue &This, AccessKinds AK) {
5645   // If we don't have an lvalue denoting an object of class type, there is no
5646   // meaningful dynamic type. (We consider objects of non-class type to have no
5647   // dynamic type.)
5648   if (!checkDynamicType(Info, E, This, AK, true))
5649     return None;
5650 
5651   // Refuse to compute a dynamic type in the presence of virtual bases. This
5652   // shouldn't happen other than in constant-folding situations, since literal
5653   // types can't have virtual bases.
5654   //
5655   // Note that consumers of DynamicType assume that the type has no virtual
5656   // bases, and will need modifications if this restriction is relaxed.
5657   const CXXRecordDecl *Class =
5658       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5659   if (!Class || Class->getNumVBases()) {
5660     Info.FFDiag(E);
5661     return None;
5662   }
5663 
5664   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5665   // binary search here instead. But the overwhelmingly common case is that
5666   // we're not in the middle of a constructor, so it probably doesn't matter
5667   // in practice.
5668   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5669   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5670        PathLength <= Path.size(); ++PathLength) {
5671     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5672                                       Path.slice(0, PathLength))) {
5673     case ConstructionPhase::Bases:
5674     case ConstructionPhase::DestroyingBases:
5675       // We're constructing or destroying a base class. This is not the dynamic
5676       // type.
5677       break;
5678 
5679     case ConstructionPhase::None:
5680     case ConstructionPhase::AfterBases:
5681     case ConstructionPhase::AfterFields:
5682     case ConstructionPhase::Destroying:
5683       // We've finished constructing the base classes and not yet started
5684       // destroying them again, so this is the dynamic type.
5685       return DynamicType{getBaseClassType(This.Designator, PathLength),
5686                          PathLength};
5687     }
5688   }
5689 
5690   // CWG issue 1517: we're constructing a base class of the object described by
5691   // 'This', so that object has not yet begun its period of construction and
5692   // any polymorphic operation on it results in undefined behavior.
5693   Info.FFDiag(E);
5694   return None;
5695 }
5696 
5697 /// Perform virtual dispatch.
5698 static const CXXMethodDecl *HandleVirtualDispatch(
5699     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5700     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5701   Optional<DynamicType> DynType = ComputeDynamicType(
5702       Info, E, This,
5703       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5704   if (!DynType)
5705     return nullptr;
5706 
5707   // Find the final overrider. It must be declared in one of the classes on the
5708   // path from the dynamic type to the static type.
5709   // FIXME: If we ever allow literal types to have virtual base classes, that
5710   // won't be true.
5711   const CXXMethodDecl *Callee = Found;
5712   unsigned PathLength = DynType->PathLength;
5713   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5714     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5715     const CXXMethodDecl *Overrider =
5716         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5717     if (Overrider) {
5718       Callee = Overrider;
5719       break;
5720     }
5721   }
5722 
5723   // C++2a [class.abstract]p6:
5724   //   the effect of making a virtual call to a pure virtual function [...] is
5725   //   undefined
5726   if (Callee->isPure()) {
5727     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5728     Info.Note(Callee->getLocation(), diag::note_declared_at);
5729     return nullptr;
5730   }
5731 
5732   // If necessary, walk the rest of the path to determine the sequence of
5733   // covariant adjustment steps to apply.
5734   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5735                                        Found->getReturnType())) {
5736     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5737     for (unsigned CovariantPathLength = PathLength + 1;
5738          CovariantPathLength != This.Designator.Entries.size();
5739          ++CovariantPathLength) {
5740       const CXXRecordDecl *NextClass =
5741           getBaseClassType(This.Designator, CovariantPathLength);
5742       const CXXMethodDecl *Next =
5743           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5744       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5745                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5746         CovariantAdjustmentPath.push_back(Next->getReturnType());
5747     }
5748     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5749                                          CovariantAdjustmentPath.back()))
5750       CovariantAdjustmentPath.push_back(Found->getReturnType());
5751   }
5752 
5753   // Perform 'this' adjustment.
5754   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5755     return nullptr;
5756 
5757   return Callee;
5758 }
5759 
5760 /// Perform the adjustment from a value returned by a virtual function to
5761 /// a value of the statically expected type, which may be a pointer or
5762 /// reference to a base class of the returned type.
5763 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5764                                             APValue &Result,
5765                                             ArrayRef<QualType> Path) {
5766   assert(Result.isLValue() &&
5767          "unexpected kind of APValue for covariant return");
5768   if (Result.isNullPointer())
5769     return true;
5770 
5771   LValue LVal;
5772   LVal.setFrom(Info.Ctx, Result);
5773 
5774   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5775   for (unsigned I = 1; I != Path.size(); ++I) {
5776     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5777     assert(OldClass && NewClass && "unexpected kind of covariant return");
5778     if (OldClass != NewClass &&
5779         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5780       return false;
5781     OldClass = NewClass;
5782   }
5783 
5784   LVal.moveInto(Result);
5785   return true;
5786 }
5787 
5788 /// Determine whether \p Base, which is known to be a direct base class of
5789 /// \p Derived, is a public base class.
5790 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5791                               const CXXRecordDecl *Base) {
5792   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5793     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5794     if (BaseClass && declaresSameEntity(BaseClass, Base))
5795       return BaseSpec.getAccessSpecifier() == AS_public;
5796   }
5797   llvm_unreachable("Base is not a direct base of Derived");
5798 }
5799 
5800 /// Apply the given dynamic cast operation on the provided lvalue.
5801 ///
5802 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5803 /// to find a suitable target subobject.
5804 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5805                               LValue &Ptr) {
5806   // We can't do anything with a non-symbolic pointer value.
5807   SubobjectDesignator &D = Ptr.Designator;
5808   if (D.Invalid)
5809     return false;
5810 
5811   // C++ [expr.dynamic.cast]p6:
5812   //   If v is a null pointer value, the result is a null pointer value.
5813   if (Ptr.isNullPointer() && !E->isGLValue())
5814     return true;
5815 
5816   // For all the other cases, we need the pointer to point to an object within
5817   // its lifetime / period of construction / destruction, and we need to know
5818   // its dynamic type.
5819   Optional<DynamicType> DynType =
5820       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5821   if (!DynType)
5822     return false;
5823 
5824   // C++ [expr.dynamic.cast]p7:
5825   //   If T is "pointer to cv void", then the result is a pointer to the most
5826   //   derived object
5827   if (E->getType()->isVoidPointerType())
5828     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5829 
5830   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5831   assert(C && "dynamic_cast target is not void pointer nor class");
5832   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5833 
5834   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5835     // C++ [expr.dynamic.cast]p9:
5836     if (!E->isGLValue()) {
5837       //   The value of a failed cast to pointer type is the null pointer value
5838       //   of the required result type.
5839       Ptr.setNull(Info.Ctx, E->getType());
5840       return true;
5841     }
5842 
5843     //   A failed cast to reference type throws [...] std::bad_cast.
5844     unsigned DiagKind;
5845     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5846                    DynType->Type->isDerivedFrom(C)))
5847       DiagKind = 0;
5848     else if (!Paths || Paths->begin() == Paths->end())
5849       DiagKind = 1;
5850     else if (Paths->isAmbiguous(CQT))
5851       DiagKind = 2;
5852     else {
5853       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5854       DiagKind = 3;
5855     }
5856     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5857         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5858         << Info.Ctx.getRecordType(DynType->Type)
5859         << E->getType().getUnqualifiedType();
5860     return false;
5861   };
5862 
5863   // Runtime check, phase 1:
5864   //   Walk from the base subobject towards the derived object looking for the
5865   //   target type.
5866   for (int PathLength = Ptr.Designator.Entries.size();
5867        PathLength >= (int)DynType->PathLength; --PathLength) {
5868     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5869     if (declaresSameEntity(Class, C))
5870       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5871     // We can only walk across public inheritance edges.
5872     if (PathLength > (int)DynType->PathLength &&
5873         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5874                            Class))
5875       return RuntimeCheckFailed(nullptr);
5876   }
5877 
5878   // Runtime check, phase 2:
5879   //   Search the dynamic type for an unambiguous public base of type C.
5880   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5881                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5882   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5883       Paths.front().Access == AS_public) {
5884     // Downcast to the dynamic type...
5885     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5886       return false;
5887     // ... then upcast to the chosen base class subobject.
5888     for (CXXBasePathElement &Elem : Paths.front())
5889       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5890         return false;
5891     return true;
5892   }
5893 
5894   // Otherwise, the runtime check fails.
5895   return RuntimeCheckFailed(&Paths);
5896 }
5897 
5898 namespace {
5899 struct StartLifetimeOfUnionMemberHandler {
5900   EvalInfo &Info;
5901   const Expr *LHSExpr;
5902   const FieldDecl *Field;
5903   bool DuringInit;
5904   bool Failed = false;
5905   static const AccessKinds AccessKind = AK_Assign;
5906 
5907   typedef bool result_type;
5908   bool failed() { return Failed; }
5909   bool found(APValue &Subobj, QualType SubobjType) {
5910     // We are supposed to perform no initialization but begin the lifetime of
5911     // the object. We interpret that as meaning to do what default
5912     // initialization of the object would do if all constructors involved were
5913     // trivial:
5914     //  * All base, non-variant member, and array element subobjects' lifetimes
5915     //    begin
5916     //  * No variant members' lifetimes begin
5917     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5918     assert(SubobjType->isUnionType());
5919     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5920       // This union member is already active. If it's also in-lifetime, there's
5921       // nothing to do.
5922       if (Subobj.getUnionValue().hasValue())
5923         return true;
5924     } else if (DuringInit) {
5925       // We're currently in the process of initializing a different union
5926       // member.  If we carried on, that initialization would attempt to
5927       // store to an inactive union member, resulting in undefined behavior.
5928       Info.FFDiag(LHSExpr,
5929                   diag::note_constexpr_union_member_change_during_init);
5930       return false;
5931     }
5932     APValue Result;
5933     Failed = !getDefaultInitValue(Field->getType(), Result);
5934     Subobj.setUnion(Field, Result);
5935     return true;
5936   }
5937   bool found(APSInt &Value, QualType SubobjType) {
5938     llvm_unreachable("wrong value kind for union object");
5939   }
5940   bool found(APFloat &Value, QualType SubobjType) {
5941     llvm_unreachable("wrong value kind for union object");
5942   }
5943 };
5944 } // end anonymous namespace
5945 
5946 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5947 
5948 /// Handle a builtin simple-assignment or a call to a trivial assignment
5949 /// operator whose left-hand side might involve a union member access. If it
5950 /// does, implicitly start the lifetime of any accessed union elements per
5951 /// C++20 [class.union]5.
5952 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5953                                           const LValue &LHS) {
5954   if (LHS.InvalidBase || LHS.Designator.Invalid)
5955     return false;
5956 
5957   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5958   // C++ [class.union]p5:
5959   //   define the set S(E) of subexpressions of E as follows:
5960   unsigned PathLength = LHS.Designator.Entries.size();
5961   for (const Expr *E = LHSExpr; E != nullptr;) {
5962     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5963     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5964       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5965       // Note that we can't implicitly start the lifetime of a reference,
5966       // so we don't need to proceed any further if we reach one.
5967       if (!FD || FD->getType()->isReferenceType())
5968         break;
5969 
5970       //    ... and also contains A.B if B names a union member ...
5971       if (FD->getParent()->isUnion()) {
5972         //    ... of a non-class, non-array type, or of a class type with a
5973         //    trivial default constructor that is not deleted, or an array of
5974         //    such types.
5975         auto *RD =
5976             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5977         if (!RD || RD->hasTrivialDefaultConstructor())
5978           UnionPathLengths.push_back({PathLength - 1, FD});
5979       }
5980 
5981       E = ME->getBase();
5982       --PathLength;
5983       assert(declaresSameEntity(FD,
5984                                 LHS.Designator.Entries[PathLength]
5985                                     .getAsBaseOrMember().getPointer()));
5986 
5987       //   -- If E is of the form A[B] and is interpreted as a built-in array
5988       //      subscripting operator, S(E) is [S(the array operand, if any)].
5989     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5990       // Step over an ArrayToPointerDecay implicit cast.
5991       auto *Base = ASE->getBase()->IgnoreImplicit();
5992       if (!Base->getType()->isArrayType())
5993         break;
5994 
5995       E = Base;
5996       --PathLength;
5997 
5998     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5999       // Step over a derived-to-base conversion.
6000       E = ICE->getSubExpr();
6001       if (ICE->getCastKind() == CK_NoOp)
6002         continue;
6003       if (ICE->getCastKind() != CK_DerivedToBase &&
6004           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6005         break;
6006       // Walk path backwards as we walk up from the base to the derived class.
6007       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6008         --PathLength;
6009         (void)Elt;
6010         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6011                                   LHS.Designator.Entries[PathLength]
6012                                       .getAsBaseOrMember().getPointer()));
6013       }
6014 
6015     //   -- Otherwise, S(E) is empty.
6016     } else {
6017       break;
6018     }
6019   }
6020 
6021   // Common case: no unions' lifetimes are started.
6022   if (UnionPathLengths.empty())
6023     return true;
6024 
6025   //   if modification of X [would access an inactive union member], an object
6026   //   of the type of X is implicitly created
6027   CompleteObject Obj =
6028       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6029   if (!Obj)
6030     return false;
6031   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6032            llvm::reverse(UnionPathLengths)) {
6033     // Form a designator for the union object.
6034     SubobjectDesignator D = LHS.Designator;
6035     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6036 
6037     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6038                       ConstructionPhase::AfterBases;
6039     StartLifetimeOfUnionMemberHandler StartLifetime{
6040         Info, LHSExpr, LengthAndField.second, DuringInit};
6041     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6042       return false;
6043   }
6044 
6045   return true;
6046 }
6047 
6048 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6049                             CallRef Call, EvalInfo &Info,
6050                             bool NonNull = false) {
6051   LValue LV;
6052   // Create the parameter slot and register its destruction. For a vararg
6053   // argument, create a temporary.
6054   // FIXME: For calling conventions that destroy parameters in the callee,
6055   // should we consider performing destruction when the function returns
6056   // instead?
6057   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6058                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6059                                                        ScopeKind::Call, LV);
6060   if (!EvaluateInPlace(V, Info, LV, Arg))
6061     return false;
6062 
6063   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6064   // undefined behavior, so is non-constant.
6065   if (NonNull && V.isLValue() && V.isNullPointer()) {
6066     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6067     return false;
6068   }
6069 
6070   return true;
6071 }
6072 
6073 /// Evaluate the arguments to a function call.
6074 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6075                          EvalInfo &Info, const FunctionDecl *Callee,
6076                          bool RightToLeft = false) {
6077   bool Success = true;
6078   llvm::SmallBitVector ForbiddenNullArgs;
6079   if (Callee->hasAttr<NonNullAttr>()) {
6080     ForbiddenNullArgs.resize(Args.size());
6081     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6082       if (!Attr->args_size()) {
6083         ForbiddenNullArgs.set();
6084         break;
6085       } else
6086         for (auto Idx : Attr->args()) {
6087           unsigned ASTIdx = Idx.getASTIndex();
6088           if (ASTIdx >= Args.size())
6089             continue;
6090           ForbiddenNullArgs[ASTIdx] = true;
6091         }
6092     }
6093   }
6094   for (unsigned I = 0; I < Args.size(); I++) {
6095     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6096     const ParmVarDecl *PVD =
6097         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6098     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6099     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6100       // If we're checking for a potential constant expression, evaluate all
6101       // initializers even if some of them fail.
6102       if (!Info.noteFailure())
6103         return false;
6104       Success = false;
6105     }
6106   }
6107   return Success;
6108 }
6109 
6110 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6111 /// constructor or assignment operator.
6112 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6113                               const Expr *E, APValue &Result,
6114                               bool CopyObjectRepresentation) {
6115   // Find the reference argument.
6116   CallStackFrame *Frame = Info.CurrentCall;
6117   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6118   if (!RefValue) {
6119     Info.FFDiag(E);
6120     return false;
6121   }
6122 
6123   // Copy out the contents of the RHS object.
6124   LValue RefLValue;
6125   RefLValue.setFrom(Info.Ctx, *RefValue);
6126   return handleLValueToRValueConversion(
6127       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6128       CopyObjectRepresentation);
6129 }
6130 
6131 /// Evaluate a function call.
6132 static bool HandleFunctionCall(SourceLocation CallLoc,
6133                                const FunctionDecl *Callee, const LValue *This,
6134                                ArrayRef<const Expr *> Args, CallRef Call,
6135                                const Stmt *Body, EvalInfo &Info,
6136                                APValue &Result, const LValue *ResultSlot) {
6137   if (!Info.CheckCallLimit(CallLoc))
6138     return false;
6139 
6140   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6141 
6142   // For a trivial copy or move assignment, perform an APValue copy. This is
6143   // essential for unions, where the operations performed by the assignment
6144   // operator cannot be represented as statements.
6145   //
6146   // Skip this for non-union classes with no fields; in that case, the defaulted
6147   // copy/move does not actually read the object.
6148   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6149   if (MD && MD->isDefaulted() &&
6150       (MD->getParent()->isUnion() ||
6151        (MD->isTrivial() &&
6152         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6153     assert(This &&
6154            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6155     APValue RHSValue;
6156     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6157                            MD->getParent()->isUnion()))
6158       return false;
6159     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6160                           RHSValue))
6161       return false;
6162     This->moveInto(Result);
6163     return true;
6164   } else if (MD && isLambdaCallOperator(MD)) {
6165     // We're in a lambda; determine the lambda capture field maps unless we're
6166     // just constexpr checking a lambda's call operator. constexpr checking is
6167     // done before the captures have been added to the closure object (unless
6168     // we're inferring constexpr-ness), so we don't have access to them in this
6169     // case. But since we don't need the captures to constexpr check, we can
6170     // just ignore them.
6171     if (!Info.checkingPotentialConstantExpression())
6172       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6173                                         Frame.LambdaThisCaptureField);
6174   }
6175 
6176   StmtResult Ret = {Result, ResultSlot};
6177   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6178   if (ESR == ESR_Succeeded) {
6179     if (Callee->getReturnType()->isVoidType())
6180       return true;
6181     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6182   }
6183   return ESR == ESR_Returned;
6184 }
6185 
6186 /// Evaluate a constructor call.
6187 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6188                                   CallRef Call,
6189                                   const CXXConstructorDecl *Definition,
6190                                   EvalInfo &Info, APValue &Result) {
6191   SourceLocation CallLoc = E->getExprLoc();
6192   if (!Info.CheckCallLimit(CallLoc))
6193     return false;
6194 
6195   const CXXRecordDecl *RD = Definition->getParent();
6196   if (RD->getNumVBases()) {
6197     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6198     return false;
6199   }
6200 
6201   EvalInfo::EvaluatingConstructorRAII EvalObj(
6202       Info,
6203       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6204       RD->getNumBases());
6205   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6206 
6207   // FIXME: Creating an APValue just to hold a nonexistent return value is
6208   // wasteful.
6209   APValue RetVal;
6210   StmtResult Ret = {RetVal, nullptr};
6211 
6212   // If it's a delegating constructor, delegate.
6213   if (Definition->isDelegatingConstructor()) {
6214     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6215     if ((*I)->getInit()->isValueDependent()) {
6216       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6217         return false;
6218     } else {
6219       FullExpressionRAII InitScope(Info);
6220       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6221           !InitScope.destroy())
6222         return false;
6223     }
6224     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6225   }
6226 
6227   // For a trivial copy or move constructor, perform an APValue copy. This is
6228   // essential for unions (or classes with anonymous union members), where the
6229   // operations performed by the constructor cannot be represented by
6230   // ctor-initializers.
6231   //
6232   // Skip this for empty non-union classes; we should not perform an
6233   // lvalue-to-rvalue conversion on them because their copy constructor does not
6234   // actually read them.
6235   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6236       (Definition->getParent()->isUnion() ||
6237        (Definition->isTrivial() &&
6238         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6239     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6240                              Definition->getParent()->isUnion());
6241   }
6242 
6243   // Reserve space for the struct members.
6244   if (!Result.hasValue()) {
6245     if (!RD->isUnion())
6246       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6247                        std::distance(RD->field_begin(), RD->field_end()));
6248     else
6249       // A union starts with no active member.
6250       Result = APValue((const FieldDecl*)nullptr);
6251   }
6252 
6253   if (RD->isInvalidDecl()) return false;
6254   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6255 
6256   // A scope for temporaries lifetime-extended by reference members.
6257   BlockScopeRAII LifetimeExtendedScope(Info);
6258 
6259   bool Success = true;
6260   unsigned BasesSeen = 0;
6261 #ifndef NDEBUG
6262   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6263 #endif
6264   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6265   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6266     // We might be initializing the same field again if this is an indirect
6267     // field initialization.
6268     if (FieldIt == RD->field_end() ||
6269         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6270       assert(Indirect && "fields out of order?");
6271       return;
6272     }
6273 
6274     // Default-initialize any fields with no explicit initializer.
6275     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6276       assert(FieldIt != RD->field_end() && "missing field?");
6277       if (!FieldIt->isUnnamedBitfield())
6278         Success &= getDefaultInitValue(
6279             FieldIt->getType(),
6280             Result.getStructField(FieldIt->getFieldIndex()));
6281     }
6282     ++FieldIt;
6283   };
6284   for (const auto *I : Definition->inits()) {
6285     LValue Subobject = This;
6286     LValue SubobjectParent = This;
6287     APValue *Value = &Result;
6288 
6289     // Determine the subobject to initialize.
6290     FieldDecl *FD = nullptr;
6291     if (I->isBaseInitializer()) {
6292       QualType BaseType(I->getBaseClass(), 0);
6293 #ifndef NDEBUG
6294       // Non-virtual base classes are initialized in the order in the class
6295       // definition. We have already checked for virtual base classes.
6296       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6297       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6298              "base class initializers not in expected order");
6299       ++BaseIt;
6300 #endif
6301       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6302                                   BaseType->getAsCXXRecordDecl(), &Layout))
6303         return false;
6304       Value = &Result.getStructBase(BasesSeen++);
6305     } else if ((FD = I->getMember())) {
6306       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6307         return false;
6308       if (RD->isUnion()) {
6309         Result = APValue(FD);
6310         Value = &Result.getUnionValue();
6311       } else {
6312         SkipToField(FD, false);
6313         Value = &Result.getStructField(FD->getFieldIndex());
6314       }
6315     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6316       // Walk the indirect field decl's chain to find the object to initialize,
6317       // and make sure we've initialized every step along it.
6318       auto IndirectFieldChain = IFD->chain();
6319       for (auto *C : IndirectFieldChain) {
6320         FD = cast<FieldDecl>(C);
6321         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6322         // Switch the union field if it differs. This happens if we had
6323         // preceding zero-initialization, and we're now initializing a union
6324         // subobject other than the first.
6325         // FIXME: In this case, the values of the other subobjects are
6326         // specified, since zero-initialization sets all padding bits to zero.
6327         if (!Value->hasValue() ||
6328             (Value->isUnion() && Value->getUnionField() != FD)) {
6329           if (CD->isUnion())
6330             *Value = APValue(FD);
6331           else
6332             // FIXME: This immediately starts the lifetime of all members of
6333             // an anonymous struct. It would be preferable to strictly start
6334             // member lifetime in initialization order.
6335             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6336         }
6337         // Store Subobject as its parent before updating it for the last element
6338         // in the chain.
6339         if (C == IndirectFieldChain.back())
6340           SubobjectParent = Subobject;
6341         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6342           return false;
6343         if (CD->isUnion())
6344           Value = &Value->getUnionValue();
6345         else {
6346           if (C == IndirectFieldChain.front() && !RD->isUnion())
6347             SkipToField(FD, true);
6348           Value = &Value->getStructField(FD->getFieldIndex());
6349         }
6350       }
6351     } else {
6352       llvm_unreachable("unknown base initializer kind");
6353     }
6354 
6355     // Need to override This for implicit field initializers as in this case
6356     // This refers to innermost anonymous struct/union containing initializer,
6357     // not to currently constructed class.
6358     const Expr *Init = I->getInit();
6359     if (Init->isValueDependent()) {
6360       if (!EvaluateDependentExpr(Init, Info))
6361         return false;
6362     } else {
6363       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6364                                     isa<CXXDefaultInitExpr>(Init));
6365       FullExpressionRAII InitScope(Info);
6366       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6367           (FD && FD->isBitField() &&
6368            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6369         // If we're checking for a potential constant expression, evaluate all
6370         // initializers even if some of them fail.
6371         if (!Info.noteFailure())
6372           return false;
6373         Success = false;
6374       }
6375     }
6376 
6377     // This is the point at which the dynamic type of the object becomes this
6378     // class type.
6379     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6380       EvalObj.finishedConstructingBases();
6381   }
6382 
6383   // Default-initialize any remaining fields.
6384   if (!RD->isUnion()) {
6385     for (; FieldIt != RD->field_end(); ++FieldIt) {
6386       if (!FieldIt->isUnnamedBitfield())
6387         Success &= getDefaultInitValue(
6388             FieldIt->getType(),
6389             Result.getStructField(FieldIt->getFieldIndex()));
6390     }
6391   }
6392 
6393   EvalObj.finishedConstructingFields();
6394 
6395   return Success &&
6396          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6397          LifetimeExtendedScope.destroy();
6398 }
6399 
6400 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6401                                   ArrayRef<const Expr*> Args,
6402                                   const CXXConstructorDecl *Definition,
6403                                   EvalInfo &Info, APValue &Result) {
6404   CallScopeRAII CallScope(Info);
6405   CallRef Call = Info.CurrentCall->createCall(Definition);
6406   if (!EvaluateArgs(Args, Call, Info, Definition))
6407     return false;
6408 
6409   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6410          CallScope.destroy();
6411 }
6412 
6413 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6414                                   const LValue &This, APValue &Value,
6415                                   QualType T) {
6416   // Objects can only be destroyed while they're within their lifetimes.
6417   // FIXME: We have no representation for whether an object of type nullptr_t
6418   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6419   // as indeterminate instead?
6420   if (Value.isAbsent() && !T->isNullPtrType()) {
6421     APValue Printable;
6422     This.moveInto(Printable);
6423     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6424       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6425     return false;
6426   }
6427 
6428   // Invent an expression for location purposes.
6429   // FIXME: We shouldn't need to do this.
6430   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6431 
6432   // For arrays, destroy elements right-to-left.
6433   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6434     uint64_t Size = CAT->getSize().getZExtValue();
6435     QualType ElemT = CAT->getElementType();
6436 
6437     LValue ElemLV = This;
6438     ElemLV.addArray(Info, &LocE, CAT);
6439     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6440       return false;
6441 
6442     // Ensure that we have actual array elements available to destroy; the
6443     // destructors might mutate the value, so we can't run them on the array
6444     // filler.
6445     if (Size && Size > Value.getArrayInitializedElts())
6446       expandArray(Value, Value.getArraySize() - 1);
6447 
6448     for (; Size != 0; --Size) {
6449       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6450       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6451           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6452         return false;
6453     }
6454 
6455     // End the lifetime of this array now.
6456     Value = APValue();
6457     return true;
6458   }
6459 
6460   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6461   if (!RD) {
6462     if (T.isDestructedType()) {
6463       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6464       return false;
6465     }
6466 
6467     Value = APValue();
6468     return true;
6469   }
6470 
6471   if (RD->getNumVBases()) {
6472     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6473     return false;
6474   }
6475 
6476   const CXXDestructorDecl *DD = RD->getDestructor();
6477   if (!DD && !RD->hasTrivialDestructor()) {
6478     Info.FFDiag(CallLoc);
6479     return false;
6480   }
6481 
6482   if (!DD || DD->isTrivial() ||
6483       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6484     // A trivial destructor just ends the lifetime of the object. Check for
6485     // this case before checking for a body, because we might not bother
6486     // building a body for a trivial destructor. Note that it doesn't matter
6487     // whether the destructor is constexpr in this case; all trivial
6488     // destructors are constexpr.
6489     //
6490     // If an anonymous union would be destroyed, some enclosing destructor must
6491     // have been explicitly defined, and the anonymous union destruction should
6492     // have no effect.
6493     Value = APValue();
6494     return true;
6495   }
6496 
6497   if (!Info.CheckCallLimit(CallLoc))
6498     return false;
6499 
6500   const FunctionDecl *Definition = nullptr;
6501   const Stmt *Body = DD->getBody(Definition);
6502 
6503   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6504     return false;
6505 
6506   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6507 
6508   // We're now in the period of destruction of this object.
6509   unsigned BasesLeft = RD->getNumBases();
6510   EvalInfo::EvaluatingDestructorRAII EvalObj(
6511       Info,
6512       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6513   if (!EvalObj.DidInsert) {
6514     // C++2a [class.dtor]p19:
6515     //   the behavior is undefined if the destructor is invoked for an object
6516     //   whose lifetime has ended
6517     // (Note that formally the lifetime ends when the period of destruction
6518     // begins, even though certain uses of the object remain valid until the
6519     // period of destruction ends.)
6520     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6521     return false;
6522   }
6523 
6524   // FIXME: Creating an APValue just to hold a nonexistent return value is
6525   // wasteful.
6526   APValue RetVal;
6527   StmtResult Ret = {RetVal, nullptr};
6528   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6529     return false;
6530 
6531   // A union destructor does not implicitly destroy its members.
6532   if (RD->isUnion())
6533     return true;
6534 
6535   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6536 
6537   // We don't have a good way to iterate fields in reverse, so collect all the
6538   // fields first and then walk them backwards.
6539   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6540   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6541     if (FD->isUnnamedBitfield())
6542       continue;
6543 
6544     LValue Subobject = This;
6545     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6546       return false;
6547 
6548     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6549     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6550                                FD->getType()))
6551       return false;
6552   }
6553 
6554   if (BasesLeft != 0)
6555     EvalObj.startedDestroyingBases();
6556 
6557   // Destroy base classes in reverse order.
6558   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6559     --BasesLeft;
6560 
6561     QualType BaseType = Base.getType();
6562     LValue Subobject = This;
6563     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6564                                 BaseType->getAsCXXRecordDecl(), &Layout))
6565       return false;
6566 
6567     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6568     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6569                                BaseType))
6570       return false;
6571   }
6572   assert(BasesLeft == 0 && "NumBases was wrong?");
6573 
6574   // The period of destruction ends now. The object is gone.
6575   Value = APValue();
6576   return true;
6577 }
6578 
6579 namespace {
6580 struct DestroyObjectHandler {
6581   EvalInfo &Info;
6582   const Expr *E;
6583   const LValue &This;
6584   const AccessKinds AccessKind;
6585 
6586   typedef bool result_type;
6587   bool failed() { return false; }
6588   bool found(APValue &Subobj, QualType SubobjType) {
6589     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6590                                  SubobjType);
6591   }
6592   bool found(APSInt &Value, QualType SubobjType) {
6593     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6594     return false;
6595   }
6596   bool found(APFloat &Value, QualType SubobjType) {
6597     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6598     return false;
6599   }
6600 };
6601 }
6602 
6603 /// Perform a destructor or pseudo-destructor call on the given object, which
6604 /// might in general not be a complete object.
6605 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6606                               const LValue &This, QualType ThisType) {
6607   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6608   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6609   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6610 }
6611 
6612 /// Destroy and end the lifetime of the given complete object.
6613 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6614                               APValue::LValueBase LVBase, APValue &Value,
6615                               QualType T) {
6616   // If we've had an unmodeled side-effect, we can't rely on mutable state
6617   // (such as the object we're about to destroy) being correct.
6618   if (Info.EvalStatus.HasSideEffects)
6619     return false;
6620 
6621   LValue LV;
6622   LV.set({LVBase});
6623   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6624 }
6625 
6626 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6627 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6628                                   LValue &Result) {
6629   if (Info.checkingPotentialConstantExpression() ||
6630       Info.SpeculativeEvaluationDepth)
6631     return false;
6632 
6633   // This is permitted only within a call to std::allocator<T>::allocate.
6634   auto Caller = Info.getStdAllocatorCaller("allocate");
6635   if (!Caller) {
6636     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6637                                      ? diag::note_constexpr_new_untyped
6638                                      : diag::note_constexpr_new);
6639     return false;
6640   }
6641 
6642   QualType ElemType = Caller.ElemType;
6643   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6644     Info.FFDiag(E->getExprLoc(),
6645                 diag::note_constexpr_new_not_complete_object_type)
6646         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6647     return false;
6648   }
6649 
6650   APSInt ByteSize;
6651   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6652     return false;
6653   bool IsNothrow = false;
6654   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6655     EvaluateIgnoredValue(Info, E->getArg(I));
6656     IsNothrow |= E->getType()->isNothrowT();
6657   }
6658 
6659   CharUnits ElemSize;
6660   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6661     return false;
6662   APInt Size, Remainder;
6663   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6664   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6665   if (Remainder != 0) {
6666     // This likely indicates a bug in the implementation of 'std::allocator'.
6667     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6668         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6669     return false;
6670   }
6671 
6672   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6673     if (IsNothrow) {
6674       Result.setNull(Info.Ctx, E->getType());
6675       return true;
6676     }
6677 
6678     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6679     return false;
6680   }
6681 
6682   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6683                                                      ArrayType::Normal, 0);
6684   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6685   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6686   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6687   return true;
6688 }
6689 
6690 static bool hasVirtualDestructor(QualType T) {
6691   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6692     if (CXXDestructorDecl *DD = RD->getDestructor())
6693       return DD->isVirtual();
6694   return false;
6695 }
6696 
6697 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6698   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6699     if (CXXDestructorDecl *DD = RD->getDestructor())
6700       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6701   return nullptr;
6702 }
6703 
6704 /// Check that the given object is a suitable pointer to a heap allocation that
6705 /// still exists and is of the right kind for the purpose of a deletion.
6706 ///
6707 /// On success, returns the heap allocation to deallocate. On failure, produces
6708 /// a diagnostic and returns None.
6709 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6710                                             const LValue &Pointer,
6711                                             DynAlloc::Kind DeallocKind) {
6712   auto PointerAsString = [&] {
6713     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6714   };
6715 
6716   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6717   if (!DA) {
6718     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6719         << PointerAsString();
6720     if (Pointer.Base)
6721       NoteLValueLocation(Info, Pointer.Base);
6722     return None;
6723   }
6724 
6725   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6726   if (!Alloc) {
6727     Info.FFDiag(E, diag::note_constexpr_double_delete);
6728     return None;
6729   }
6730 
6731   QualType AllocType = Pointer.Base.getDynamicAllocType();
6732   if (DeallocKind != (*Alloc)->getKind()) {
6733     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6734         << DeallocKind << (*Alloc)->getKind() << AllocType;
6735     NoteLValueLocation(Info, Pointer.Base);
6736     return None;
6737   }
6738 
6739   bool Subobject = false;
6740   if (DeallocKind == DynAlloc::New) {
6741     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6742                 Pointer.Designator.isOnePastTheEnd();
6743   } else {
6744     Subobject = Pointer.Designator.Entries.size() != 1 ||
6745                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6746   }
6747   if (Subobject) {
6748     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6749         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6750     return None;
6751   }
6752 
6753   return Alloc;
6754 }
6755 
6756 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6757 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6758   if (Info.checkingPotentialConstantExpression() ||
6759       Info.SpeculativeEvaluationDepth)
6760     return false;
6761 
6762   // This is permitted only within a call to std::allocator<T>::deallocate.
6763   if (!Info.getStdAllocatorCaller("deallocate")) {
6764     Info.FFDiag(E->getExprLoc());
6765     return true;
6766   }
6767 
6768   LValue Pointer;
6769   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6770     return false;
6771   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6772     EvaluateIgnoredValue(Info, E->getArg(I));
6773 
6774   if (Pointer.Designator.Invalid)
6775     return false;
6776 
6777   // Deleting a null pointer would have no effect, but it's not permitted by
6778   // std::allocator<T>::deallocate's contract.
6779   if (Pointer.isNullPointer()) {
6780     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6781     return true;
6782   }
6783 
6784   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6785     return false;
6786 
6787   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6788   return true;
6789 }
6790 
6791 //===----------------------------------------------------------------------===//
6792 // Generic Evaluation
6793 //===----------------------------------------------------------------------===//
6794 namespace {
6795 
6796 class BitCastBuffer {
6797   // FIXME: We're going to need bit-level granularity when we support
6798   // bit-fields.
6799   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6800   // we don't support a host or target where that is the case. Still, we should
6801   // use a more generic type in case we ever do.
6802   SmallVector<Optional<unsigned char>, 32> Bytes;
6803 
6804   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6805                 "Need at least 8 bit unsigned char");
6806 
6807   bool TargetIsLittleEndian;
6808 
6809 public:
6810   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6811       : Bytes(Width.getQuantity()),
6812         TargetIsLittleEndian(TargetIsLittleEndian) {}
6813 
6814   LLVM_NODISCARD
6815   bool readObject(CharUnits Offset, CharUnits Width,
6816                   SmallVectorImpl<unsigned char> &Output) const {
6817     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6818       // If a byte of an integer is uninitialized, then the whole integer is
6819       // uninitialized.
6820       if (!Bytes[I.getQuantity()])
6821         return false;
6822       Output.push_back(*Bytes[I.getQuantity()]);
6823     }
6824     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6825       std::reverse(Output.begin(), Output.end());
6826     return true;
6827   }
6828 
6829   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6830     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6831       std::reverse(Input.begin(), Input.end());
6832 
6833     size_t Index = 0;
6834     for (unsigned char Byte : Input) {
6835       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6836       Bytes[Offset.getQuantity() + Index] = Byte;
6837       ++Index;
6838     }
6839   }
6840 
6841   size_t size() { return Bytes.size(); }
6842 };
6843 
6844 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6845 /// target would represent the value at runtime.
6846 class APValueToBufferConverter {
6847   EvalInfo &Info;
6848   BitCastBuffer Buffer;
6849   const CastExpr *BCE;
6850 
6851   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6852                            const CastExpr *BCE)
6853       : Info(Info),
6854         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6855         BCE(BCE) {}
6856 
6857   bool visit(const APValue &Val, QualType Ty) {
6858     return visit(Val, Ty, CharUnits::fromQuantity(0));
6859   }
6860 
6861   // Write out Val with type Ty into Buffer starting at Offset.
6862   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6863     assert((size_t)Offset.getQuantity() <= Buffer.size());
6864 
6865     // As a special case, nullptr_t has an indeterminate value.
6866     if (Ty->isNullPtrType())
6867       return true;
6868 
6869     // Dig through Src to find the byte at SrcOffset.
6870     switch (Val.getKind()) {
6871     case APValue::Indeterminate:
6872     case APValue::None:
6873       return true;
6874 
6875     case APValue::Int:
6876       return visitInt(Val.getInt(), Ty, Offset);
6877     case APValue::Float:
6878       return visitFloat(Val.getFloat(), Ty, Offset);
6879     case APValue::Array:
6880       return visitArray(Val, Ty, Offset);
6881     case APValue::Struct:
6882       return visitRecord(Val, Ty, Offset);
6883 
6884     case APValue::ComplexInt:
6885     case APValue::ComplexFloat:
6886     case APValue::Vector:
6887     case APValue::FixedPoint:
6888       // FIXME: We should support these.
6889 
6890     case APValue::Union:
6891     case APValue::MemberPointer:
6892     case APValue::AddrLabelDiff: {
6893       Info.FFDiag(BCE->getBeginLoc(),
6894                   diag::note_constexpr_bit_cast_unsupported_type)
6895           << Ty;
6896       return false;
6897     }
6898 
6899     case APValue::LValue:
6900       llvm_unreachable("LValue subobject in bit_cast?");
6901     }
6902     llvm_unreachable("Unhandled APValue::ValueKind");
6903   }
6904 
6905   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6906     const RecordDecl *RD = Ty->getAsRecordDecl();
6907     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6908 
6909     // Visit the base classes.
6910     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6911       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6912         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6913         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6914 
6915         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6916                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6917           return false;
6918       }
6919     }
6920 
6921     // Visit the fields.
6922     unsigned FieldIdx = 0;
6923     for (FieldDecl *FD : RD->fields()) {
6924       if (FD->isBitField()) {
6925         Info.FFDiag(BCE->getBeginLoc(),
6926                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6927         return false;
6928       }
6929 
6930       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6931 
6932       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6933              "only bit-fields can have sub-char alignment");
6934       CharUnits FieldOffset =
6935           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6936       QualType FieldTy = FD->getType();
6937       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6938         return false;
6939       ++FieldIdx;
6940     }
6941 
6942     return true;
6943   }
6944 
6945   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6946     const auto *CAT =
6947         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6948     if (!CAT)
6949       return false;
6950 
6951     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6952     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6953     unsigned ArraySize = Val.getArraySize();
6954     // First, initialize the initialized elements.
6955     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6956       const APValue &SubObj = Val.getArrayInitializedElt(I);
6957       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6958         return false;
6959     }
6960 
6961     // Next, initialize the rest of the array using the filler.
6962     if (Val.hasArrayFiller()) {
6963       const APValue &Filler = Val.getArrayFiller();
6964       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6965         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6966           return false;
6967       }
6968     }
6969 
6970     return true;
6971   }
6972 
6973   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6974     APSInt AdjustedVal = Val;
6975     unsigned Width = AdjustedVal.getBitWidth();
6976     if (Ty->isBooleanType()) {
6977       Width = Info.Ctx.getTypeSize(Ty);
6978       AdjustedVal = AdjustedVal.extend(Width);
6979     }
6980 
6981     SmallVector<unsigned char, 8> Bytes(Width / 8);
6982     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6983     Buffer.writeObject(Offset, Bytes);
6984     return true;
6985   }
6986 
6987   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6988     APSInt AsInt(Val.bitcastToAPInt());
6989     return visitInt(AsInt, Ty, Offset);
6990   }
6991 
6992 public:
6993   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6994                                          const CastExpr *BCE) {
6995     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6996     APValueToBufferConverter Converter(Info, DstSize, BCE);
6997     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6998       return None;
6999     return Converter.Buffer;
7000   }
7001 };
7002 
7003 /// Write an BitCastBuffer into an APValue.
7004 class BufferToAPValueConverter {
7005   EvalInfo &Info;
7006   const BitCastBuffer &Buffer;
7007   const CastExpr *BCE;
7008 
7009   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7010                            const CastExpr *BCE)
7011       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7012 
7013   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7014   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7015   // Ideally this will be unreachable.
7016   llvm::NoneType unsupportedType(QualType Ty) {
7017     Info.FFDiag(BCE->getBeginLoc(),
7018                 diag::note_constexpr_bit_cast_unsupported_type)
7019         << Ty;
7020     return None;
7021   }
7022 
7023   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
7024     Info.FFDiag(BCE->getBeginLoc(),
7025                 diag::note_constexpr_bit_cast_unrepresentable_value)
7026         << Ty << toString(Val, /*Radix=*/10);
7027     return None;
7028   }
7029 
7030   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7031                           const EnumType *EnumSugar = nullptr) {
7032     if (T->isNullPtrType()) {
7033       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7034       return APValue((Expr *)nullptr,
7035                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7036                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7037     }
7038 
7039     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7040 
7041     // Work around floating point types that contain unused padding bytes. This
7042     // is really just `long double` on x86, which is the only fundamental type
7043     // with padding bytes.
7044     if (T->isRealFloatingType()) {
7045       const llvm::fltSemantics &Semantics =
7046           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7047       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7048       assert(NumBits % 8 == 0);
7049       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7050       if (NumBytes != SizeOf)
7051         SizeOf = NumBytes;
7052     }
7053 
7054     SmallVector<uint8_t, 8> Bytes;
7055     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7056       // If this is std::byte or unsigned char, then its okay to store an
7057       // indeterminate value.
7058       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7059       bool IsUChar =
7060           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7061                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7062       if (!IsStdByte && !IsUChar) {
7063         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7064         Info.FFDiag(BCE->getExprLoc(),
7065                     diag::note_constexpr_bit_cast_indet_dest)
7066             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7067         return None;
7068       }
7069 
7070       return APValue::IndeterminateValue();
7071     }
7072 
7073     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7074     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7075 
7076     if (T->isIntegralOrEnumerationType()) {
7077       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7078 
7079       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7080       if (IntWidth != Val.getBitWidth()) {
7081         APSInt Truncated = Val.trunc(IntWidth);
7082         if (Truncated.extend(Val.getBitWidth()) != Val)
7083           return unrepresentableValue(QualType(T, 0), Val);
7084         Val = Truncated;
7085       }
7086 
7087       return APValue(Val);
7088     }
7089 
7090     if (T->isRealFloatingType()) {
7091       const llvm::fltSemantics &Semantics =
7092           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7093       return APValue(APFloat(Semantics, Val));
7094     }
7095 
7096     return unsupportedType(QualType(T, 0));
7097   }
7098 
7099   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7100     const RecordDecl *RD = RTy->getAsRecordDecl();
7101     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7102 
7103     unsigned NumBases = 0;
7104     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7105       NumBases = CXXRD->getNumBases();
7106 
7107     APValue ResultVal(APValue::UninitStruct(), NumBases,
7108                       std::distance(RD->field_begin(), RD->field_end()));
7109 
7110     // Visit the base classes.
7111     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7112       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7113         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7114         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7115         if (BaseDecl->isEmpty() ||
7116             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7117           continue;
7118 
7119         Optional<APValue> SubObj = visitType(
7120             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7121         if (!SubObj)
7122           return None;
7123         ResultVal.getStructBase(I) = *SubObj;
7124       }
7125     }
7126 
7127     // Visit the fields.
7128     unsigned FieldIdx = 0;
7129     for (FieldDecl *FD : RD->fields()) {
7130       // FIXME: We don't currently support bit-fields. A lot of the logic for
7131       // this is in CodeGen, so we need to factor it around.
7132       if (FD->isBitField()) {
7133         Info.FFDiag(BCE->getBeginLoc(),
7134                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7135         return None;
7136       }
7137 
7138       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7139       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7140 
7141       CharUnits FieldOffset =
7142           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7143           Offset;
7144       QualType FieldTy = FD->getType();
7145       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7146       if (!SubObj)
7147         return None;
7148       ResultVal.getStructField(FieldIdx) = *SubObj;
7149       ++FieldIdx;
7150     }
7151 
7152     return ResultVal;
7153   }
7154 
7155   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7156     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7157     assert(!RepresentationType.isNull() &&
7158            "enum forward decl should be caught by Sema");
7159     const auto *AsBuiltin =
7160         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7161     // Recurse into the underlying type. Treat std::byte transparently as
7162     // unsigned char.
7163     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7164   }
7165 
7166   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7167     size_t Size = Ty->getSize().getLimitedValue();
7168     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7169 
7170     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7171     for (size_t I = 0; I != Size; ++I) {
7172       Optional<APValue> ElementValue =
7173           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7174       if (!ElementValue)
7175         return None;
7176       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7177     }
7178 
7179     return ArrayValue;
7180   }
7181 
7182   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7183     return unsupportedType(QualType(Ty, 0));
7184   }
7185 
7186   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7187     QualType Can = Ty.getCanonicalType();
7188 
7189     switch (Can->getTypeClass()) {
7190 #define TYPE(Class, Base)                                                      \
7191   case Type::Class:                                                            \
7192     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7193 #define ABSTRACT_TYPE(Class, Base)
7194 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7195   case Type::Class:                                                            \
7196     llvm_unreachable("non-canonical type should be impossible!");
7197 #define DEPENDENT_TYPE(Class, Base)                                            \
7198   case Type::Class:                                                            \
7199     llvm_unreachable(                                                          \
7200         "dependent types aren't supported in the constant evaluator!");
7201 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7202   case Type::Class:                                                            \
7203     llvm_unreachable("either dependent or not canonical!");
7204 #include "clang/AST/TypeNodes.inc"
7205     }
7206     llvm_unreachable("Unhandled Type::TypeClass");
7207   }
7208 
7209 public:
7210   // Pull out a full value of type DstType.
7211   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7212                                    const CastExpr *BCE) {
7213     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7214     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7215   }
7216 };
7217 
7218 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7219                                                  QualType Ty, EvalInfo *Info,
7220                                                  const ASTContext &Ctx,
7221                                                  bool CheckingDest) {
7222   Ty = Ty.getCanonicalType();
7223 
7224   auto diag = [&](int Reason) {
7225     if (Info)
7226       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7227           << CheckingDest << (Reason == 4) << Reason;
7228     return false;
7229   };
7230   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7231     if (Info)
7232       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7233           << NoteTy << Construct << Ty;
7234     return false;
7235   };
7236 
7237   if (Ty->isUnionType())
7238     return diag(0);
7239   if (Ty->isPointerType())
7240     return diag(1);
7241   if (Ty->isMemberPointerType())
7242     return diag(2);
7243   if (Ty.isVolatileQualified())
7244     return diag(3);
7245 
7246   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7247     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7248       for (CXXBaseSpecifier &BS : CXXRD->bases())
7249         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7250                                                   CheckingDest))
7251           return note(1, BS.getType(), BS.getBeginLoc());
7252     }
7253     for (FieldDecl *FD : Record->fields()) {
7254       if (FD->getType()->isReferenceType())
7255         return diag(4);
7256       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7257                                                 CheckingDest))
7258         return note(0, FD->getType(), FD->getBeginLoc());
7259     }
7260   }
7261 
7262   if (Ty->isArrayType() &&
7263       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7264                                             Info, Ctx, CheckingDest))
7265     return false;
7266 
7267   return true;
7268 }
7269 
7270 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7271                                              const ASTContext &Ctx,
7272                                              const CastExpr *BCE) {
7273   bool DestOK = checkBitCastConstexprEligibilityType(
7274       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7275   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7276                                 BCE->getBeginLoc(),
7277                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7278   return SourceOK;
7279 }
7280 
7281 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7282                                         APValue &SourceValue,
7283                                         const CastExpr *BCE) {
7284   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7285          "no host or target supports non 8-bit chars");
7286   assert(SourceValue.isLValue() &&
7287          "LValueToRValueBitcast requires an lvalue operand!");
7288 
7289   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7290     return false;
7291 
7292   LValue SourceLValue;
7293   APValue SourceRValue;
7294   SourceLValue.setFrom(Info.Ctx, SourceValue);
7295   if (!handleLValueToRValueConversion(
7296           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7297           SourceRValue, /*WantObjectRepresentation=*/true))
7298     return false;
7299 
7300   // Read out SourceValue into a char buffer.
7301   Optional<BitCastBuffer> Buffer =
7302       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7303   if (!Buffer)
7304     return false;
7305 
7306   // Write out the buffer into a new APValue.
7307   Optional<APValue> MaybeDestValue =
7308       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7309   if (!MaybeDestValue)
7310     return false;
7311 
7312   DestValue = std::move(*MaybeDestValue);
7313   return true;
7314 }
7315 
7316 template <class Derived>
7317 class ExprEvaluatorBase
7318   : public ConstStmtVisitor<Derived, bool> {
7319 private:
7320   Derived &getDerived() { return static_cast<Derived&>(*this); }
7321   bool DerivedSuccess(const APValue &V, const Expr *E) {
7322     return getDerived().Success(V, E);
7323   }
7324   bool DerivedZeroInitialization(const Expr *E) {
7325     return getDerived().ZeroInitialization(E);
7326   }
7327 
7328   // Check whether a conditional operator with a non-constant condition is a
7329   // potential constant expression. If neither arm is a potential constant
7330   // expression, then the conditional operator is not either.
7331   template<typename ConditionalOperator>
7332   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7333     assert(Info.checkingPotentialConstantExpression());
7334 
7335     // Speculatively evaluate both arms.
7336     SmallVector<PartialDiagnosticAt, 8> Diag;
7337     {
7338       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7339       StmtVisitorTy::Visit(E->getFalseExpr());
7340       if (Diag.empty())
7341         return;
7342     }
7343 
7344     {
7345       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7346       Diag.clear();
7347       StmtVisitorTy::Visit(E->getTrueExpr());
7348       if (Diag.empty())
7349         return;
7350     }
7351 
7352     Error(E, diag::note_constexpr_conditional_never_const);
7353   }
7354 
7355 
7356   template<typename ConditionalOperator>
7357   bool HandleConditionalOperator(const ConditionalOperator *E) {
7358     bool BoolResult;
7359     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7360       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7361         CheckPotentialConstantConditional(E);
7362         return false;
7363       }
7364       if (Info.noteFailure()) {
7365         StmtVisitorTy::Visit(E->getTrueExpr());
7366         StmtVisitorTy::Visit(E->getFalseExpr());
7367       }
7368       return false;
7369     }
7370 
7371     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7372     return StmtVisitorTy::Visit(EvalExpr);
7373   }
7374 
7375 protected:
7376   EvalInfo &Info;
7377   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7378   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7379 
7380   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7381     return Info.CCEDiag(E, D);
7382   }
7383 
7384   bool ZeroInitialization(const Expr *E) { return Error(E); }
7385 
7386 public:
7387   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7388 
7389   EvalInfo &getEvalInfo() { return Info; }
7390 
7391   /// Report an evaluation error. This should only be called when an error is
7392   /// first discovered. When propagating an error, just return false.
7393   bool Error(const Expr *E, diag::kind D) {
7394     Info.FFDiag(E, D);
7395     return false;
7396   }
7397   bool Error(const Expr *E) {
7398     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7399   }
7400 
7401   bool VisitStmt(const Stmt *) {
7402     llvm_unreachable("Expression evaluator should not be called on stmts");
7403   }
7404   bool VisitExpr(const Expr *E) {
7405     return Error(E);
7406   }
7407 
7408   bool VisitConstantExpr(const ConstantExpr *E) {
7409     if (E->hasAPValueResult())
7410       return DerivedSuccess(E->getAPValueResult(), E);
7411 
7412     return StmtVisitorTy::Visit(E->getSubExpr());
7413   }
7414 
7415   bool VisitParenExpr(const ParenExpr *E)
7416     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7417   bool VisitUnaryExtension(const UnaryOperator *E)
7418     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7419   bool VisitUnaryPlus(const UnaryOperator *E)
7420     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7421   bool VisitChooseExpr(const ChooseExpr *E)
7422     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7423   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7424     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7425   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7426     { return StmtVisitorTy::Visit(E->getReplacement()); }
7427   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7428     TempVersionRAII RAII(*Info.CurrentCall);
7429     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7430     return StmtVisitorTy::Visit(E->getExpr());
7431   }
7432   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7433     TempVersionRAII RAII(*Info.CurrentCall);
7434     // The initializer may not have been parsed yet, or might be erroneous.
7435     if (!E->getExpr())
7436       return Error(E);
7437     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7438     return StmtVisitorTy::Visit(E->getExpr());
7439   }
7440 
7441   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7442     FullExpressionRAII Scope(Info);
7443     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7444   }
7445 
7446   // Temporaries are registered when created, so we don't care about
7447   // CXXBindTemporaryExpr.
7448   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7449     return StmtVisitorTy::Visit(E->getSubExpr());
7450   }
7451 
7452   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7453     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7454     return static_cast<Derived*>(this)->VisitCastExpr(E);
7455   }
7456   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7457     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7458       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7459     return static_cast<Derived*>(this)->VisitCastExpr(E);
7460   }
7461   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7462     return static_cast<Derived*>(this)->VisitCastExpr(E);
7463   }
7464 
7465   bool VisitBinaryOperator(const BinaryOperator *E) {
7466     switch (E->getOpcode()) {
7467     default:
7468       return Error(E);
7469 
7470     case BO_Comma:
7471       VisitIgnoredValue(E->getLHS());
7472       return StmtVisitorTy::Visit(E->getRHS());
7473 
7474     case BO_PtrMemD:
7475     case BO_PtrMemI: {
7476       LValue Obj;
7477       if (!HandleMemberPointerAccess(Info, E, Obj))
7478         return false;
7479       APValue Result;
7480       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7481         return false;
7482       return DerivedSuccess(Result, E);
7483     }
7484     }
7485   }
7486 
7487   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7488     return StmtVisitorTy::Visit(E->getSemanticForm());
7489   }
7490 
7491   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7492     // Evaluate and cache the common expression. We treat it as a temporary,
7493     // even though it's not quite the same thing.
7494     LValue CommonLV;
7495     if (!Evaluate(Info.CurrentCall->createTemporary(
7496                       E->getOpaqueValue(),
7497                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7498                       ScopeKind::FullExpression, CommonLV),
7499                   Info, E->getCommon()))
7500       return false;
7501 
7502     return HandleConditionalOperator(E);
7503   }
7504 
7505   bool VisitConditionalOperator(const ConditionalOperator *E) {
7506     bool IsBcpCall = false;
7507     // If the condition (ignoring parens) is a __builtin_constant_p call,
7508     // the result is a constant expression if it can be folded without
7509     // side-effects. This is an important GNU extension. See GCC PR38377
7510     // for discussion.
7511     if (const CallExpr *CallCE =
7512           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7513       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7514         IsBcpCall = true;
7515 
7516     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7517     // constant expression; we can't check whether it's potentially foldable.
7518     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7519     // it would return 'false' in this mode.
7520     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7521       return false;
7522 
7523     FoldConstant Fold(Info, IsBcpCall);
7524     if (!HandleConditionalOperator(E)) {
7525       Fold.keepDiagnostics();
7526       return false;
7527     }
7528 
7529     return true;
7530   }
7531 
7532   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7533     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7534       return DerivedSuccess(*Value, E);
7535 
7536     const Expr *Source = E->getSourceExpr();
7537     if (!Source)
7538       return Error(E);
7539     if (Source == E) {
7540       assert(0 && "OpaqueValueExpr recursively refers to itself");
7541       return Error(E);
7542     }
7543     return StmtVisitorTy::Visit(Source);
7544   }
7545 
7546   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7547     for (const Expr *SemE : E->semantics()) {
7548       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7549         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7550         // result expression: there could be two different LValues that would
7551         // refer to the same object in that case, and we can't model that.
7552         if (SemE == E->getResultExpr())
7553           return Error(E);
7554 
7555         // Unique OVEs get evaluated if and when we encounter them when
7556         // emitting the rest of the semantic form, rather than eagerly.
7557         if (OVE->isUnique())
7558           continue;
7559 
7560         LValue LV;
7561         if (!Evaluate(Info.CurrentCall->createTemporary(
7562                           OVE, getStorageType(Info.Ctx, OVE),
7563                           ScopeKind::FullExpression, LV),
7564                       Info, OVE->getSourceExpr()))
7565           return false;
7566       } else if (SemE == E->getResultExpr()) {
7567         if (!StmtVisitorTy::Visit(SemE))
7568           return false;
7569       } else {
7570         if (!EvaluateIgnoredValue(Info, SemE))
7571           return false;
7572       }
7573     }
7574     return true;
7575   }
7576 
7577   bool VisitCallExpr(const CallExpr *E) {
7578     APValue Result;
7579     if (!handleCallExpr(E, Result, nullptr))
7580       return false;
7581     return DerivedSuccess(Result, E);
7582   }
7583 
7584   bool handleCallExpr(const CallExpr *E, APValue &Result,
7585                      const LValue *ResultSlot) {
7586     CallScopeRAII CallScope(Info);
7587 
7588     const Expr *Callee = E->getCallee()->IgnoreParens();
7589     QualType CalleeType = Callee->getType();
7590 
7591     const FunctionDecl *FD = nullptr;
7592     LValue *This = nullptr, ThisVal;
7593     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7594     bool HasQualifier = false;
7595 
7596     CallRef Call;
7597 
7598     // Extract function decl and 'this' pointer from the callee.
7599     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7600       const CXXMethodDecl *Member = nullptr;
7601       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7602         // Explicit bound member calls, such as x.f() or p->g();
7603         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7604           return false;
7605         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7606         if (!Member)
7607           return Error(Callee);
7608         This = &ThisVal;
7609         HasQualifier = ME->hasQualifier();
7610       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7611         // Indirect bound member calls ('.*' or '->*').
7612         const ValueDecl *D =
7613             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7614         if (!D)
7615           return false;
7616         Member = dyn_cast<CXXMethodDecl>(D);
7617         if (!Member)
7618           return Error(Callee);
7619         This = &ThisVal;
7620       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7621         if (!Info.getLangOpts().CPlusPlus20)
7622           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7623         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7624                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7625       } else
7626         return Error(Callee);
7627       FD = Member;
7628     } else if (CalleeType->isFunctionPointerType()) {
7629       LValue CalleeLV;
7630       if (!EvaluatePointer(Callee, CalleeLV, Info))
7631         return false;
7632 
7633       if (!CalleeLV.getLValueOffset().isZero())
7634         return Error(Callee);
7635       FD = dyn_cast_or_null<FunctionDecl>(
7636           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7637       if (!FD)
7638         return Error(Callee);
7639       // Don't call function pointers which have been cast to some other type.
7640       // Per DR (no number yet), the caller and callee can differ in noexcept.
7641       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7642         CalleeType->getPointeeType(), FD->getType())) {
7643         return Error(E);
7644       }
7645 
7646       // For an (overloaded) assignment expression, evaluate the RHS before the
7647       // LHS.
7648       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7649       if (OCE && OCE->isAssignmentOp()) {
7650         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7651         Call = Info.CurrentCall->createCall(FD);
7652         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7653                           Info, FD, /*RightToLeft=*/true))
7654           return false;
7655       }
7656 
7657       // Overloaded operator calls to member functions are represented as normal
7658       // calls with '*this' as the first argument.
7659       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7660       if (MD && !MD->isStatic()) {
7661         // FIXME: When selecting an implicit conversion for an overloaded
7662         // operator delete, we sometimes try to evaluate calls to conversion
7663         // operators without a 'this' parameter!
7664         if (Args.empty())
7665           return Error(E);
7666 
7667         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7668           return false;
7669         This = &ThisVal;
7670 
7671         // If this is syntactically a simple assignment using a trivial
7672         // assignment operator, start the lifetimes of union members as needed,
7673         // per C++20 [class.union]5.
7674         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7675             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7676             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7677           return false;
7678 
7679         Args = Args.slice(1);
7680       } else if (MD && MD->isLambdaStaticInvoker()) {
7681         // Map the static invoker for the lambda back to the call operator.
7682         // Conveniently, we don't have to slice out the 'this' argument (as is
7683         // being done for the non-static case), since a static member function
7684         // doesn't have an implicit argument passed in.
7685         const CXXRecordDecl *ClosureClass = MD->getParent();
7686         assert(
7687             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7688             "Number of captures must be zero for conversion to function-ptr");
7689 
7690         const CXXMethodDecl *LambdaCallOp =
7691             ClosureClass->getLambdaCallOperator();
7692 
7693         // Set 'FD', the function that will be called below, to the call
7694         // operator.  If the closure object represents a generic lambda, find
7695         // the corresponding specialization of the call operator.
7696 
7697         if (ClosureClass->isGenericLambda()) {
7698           assert(MD->isFunctionTemplateSpecialization() &&
7699                  "A generic lambda's static-invoker function must be a "
7700                  "template specialization");
7701           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7702           FunctionTemplateDecl *CallOpTemplate =
7703               LambdaCallOp->getDescribedFunctionTemplate();
7704           void *InsertPos = nullptr;
7705           FunctionDecl *CorrespondingCallOpSpecialization =
7706               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7707           assert(CorrespondingCallOpSpecialization &&
7708                  "We must always have a function call operator specialization "
7709                  "that corresponds to our static invoker specialization");
7710           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7711         } else
7712           FD = LambdaCallOp;
7713       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7714         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7715             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7716           LValue Ptr;
7717           if (!HandleOperatorNewCall(Info, E, Ptr))
7718             return false;
7719           Ptr.moveInto(Result);
7720           return CallScope.destroy();
7721         } else {
7722           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7723         }
7724       }
7725     } else
7726       return Error(E);
7727 
7728     // Evaluate the arguments now if we've not already done so.
7729     if (!Call) {
7730       Call = Info.CurrentCall->createCall(FD);
7731       if (!EvaluateArgs(Args, Call, Info, FD))
7732         return false;
7733     }
7734 
7735     SmallVector<QualType, 4> CovariantAdjustmentPath;
7736     if (This) {
7737       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7738       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7739         // Perform virtual dispatch, if necessary.
7740         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7741                                    CovariantAdjustmentPath);
7742         if (!FD)
7743           return false;
7744       } else {
7745         // Check that the 'this' pointer points to an object of the right type.
7746         // FIXME: If this is an assignment operator call, we may need to change
7747         // the active union member before we check this.
7748         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7749           return false;
7750       }
7751     }
7752 
7753     // Destructor calls are different enough that they have their own codepath.
7754     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7755       assert(This && "no 'this' pointer for destructor call");
7756       return HandleDestruction(Info, E, *This,
7757                                Info.Ctx.getRecordType(DD->getParent())) &&
7758              CallScope.destroy();
7759     }
7760 
7761     const FunctionDecl *Definition = nullptr;
7762     Stmt *Body = FD->getBody(Definition);
7763 
7764     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7765         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7766                             Body, Info, Result, ResultSlot))
7767       return false;
7768 
7769     if (!CovariantAdjustmentPath.empty() &&
7770         !HandleCovariantReturnAdjustment(Info, E, Result,
7771                                          CovariantAdjustmentPath))
7772       return false;
7773 
7774     return CallScope.destroy();
7775   }
7776 
7777   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7778     return StmtVisitorTy::Visit(E->getInitializer());
7779   }
7780   bool VisitInitListExpr(const InitListExpr *E) {
7781     if (E->getNumInits() == 0)
7782       return DerivedZeroInitialization(E);
7783     if (E->getNumInits() == 1)
7784       return StmtVisitorTy::Visit(E->getInit(0));
7785     return Error(E);
7786   }
7787   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7788     return DerivedZeroInitialization(E);
7789   }
7790   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7791     return DerivedZeroInitialization(E);
7792   }
7793   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7794     return DerivedZeroInitialization(E);
7795   }
7796 
7797   /// A member expression where the object is a prvalue is itself a prvalue.
7798   bool VisitMemberExpr(const MemberExpr *E) {
7799     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7800            "missing temporary materialization conversion");
7801     assert(!E->isArrow() && "missing call to bound member function?");
7802 
7803     APValue Val;
7804     if (!Evaluate(Val, Info, E->getBase()))
7805       return false;
7806 
7807     QualType BaseTy = E->getBase()->getType();
7808 
7809     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7810     if (!FD) return Error(E);
7811     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7812     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7813            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7814 
7815     // Note: there is no lvalue base here. But this case should only ever
7816     // happen in C or in C++98, where we cannot be evaluating a constexpr
7817     // constructor, which is the only case the base matters.
7818     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7819     SubobjectDesignator Designator(BaseTy);
7820     Designator.addDeclUnchecked(FD);
7821 
7822     APValue Result;
7823     return extractSubobject(Info, E, Obj, Designator, Result) &&
7824            DerivedSuccess(Result, E);
7825   }
7826 
7827   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7828     APValue Val;
7829     if (!Evaluate(Val, Info, E->getBase()))
7830       return false;
7831 
7832     if (Val.isVector()) {
7833       SmallVector<uint32_t, 4> Indices;
7834       E->getEncodedElementAccess(Indices);
7835       if (Indices.size() == 1) {
7836         // Return scalar.
7837         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7838       } else {
7839         // Construct new APValue vector.
7840         SmallVector<APValue, 4> Elts;
7841         for (unsigned I = 0; I < Indices.size(); ++I) {
7842           Elts.push_back(Val.getVectorElt(Indices[I]));
7843         }
7844         APValue VecResult(Elts.data(), Indices.size());
7845         return DerivedSuccess(VecResult, E);
7846       }
7847     }
7848 
7849     return false;
7850   }
7851 
7852   bool VisitCastExpr(const CastExpr *E) {
7853     switch (E->getCastKind()) {
7854     default:
7855       break;
7856 
7857     case CK_AtomicToNonAtomic: {
7858       APValue AtomicVal;
7859       // This does not need to be done in place even for class/array types:
7860       // atomic-to-non-atomic conversion implies copying the object
7861       // representation.
7862       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7863         return false;
7864       return DerivedSuccess(AtomicVal, E);
7865     }
7866 
7867     case CK_NoOp:
7868     case CK_UserDefinedConversion:
7869       return StmtVisitorTy::Visit(E->getSubExpr());
7870 
7871     case CK_LValueToRValue: {
7872       LValue LVal;
7873       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7874         return false;
7875       APValue RVal;
7876       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7877       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7878                                           LVal, RVal))
7879         return false;
7880       return DerivedSuccess(RVal, E);
7881     }
7882     case CK_LValueToRValueBitCast: {
7883       APValue DestValue, SourceValue;
7884       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7885         return false;
7886       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7887         return false;
7888       return DerivedSuccess(DestValue, E);
7889     }
7890 
7891     case CK_AddressSpaceConversion: {
7892       APValue Value;
7893       if (!Evaluate(Value, Info, E->getSubExpr()))
7894         return false;
7895       return DerivedSuccess(Value, E);
7896     }
7897     }
7898 
7899     return Error(E);
7900   }
7901 
7902   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7903     return VisitUnaryPostIncDec(UO);
7904   }
7905   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7906     return VisitUnaryPostIncDec(UO);
7907   }
7908   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7909     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7910       return Error(UO);
7911 
7912     LValue LVal;
7913     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7914       return false;
7915     APValue RVal;
7916     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7917                       UO->isIncrementOp(), &RVal))
7918       return false;
7919     return DerivedSuccess(RVal, UO);
7920   }
7921 
7922   bool VisitStmtExpr(const StmtExpr *E) {
7923     // We will have checked the full-expressions inside the statement expression
7924     // when they were completed, and don't need to check them again now.
7925     llvm::SaveAndRestore<bool> NotCheckingForUB(
7926         Info.CheckingForUndefinedBehavior, false);
7927 
7928     const CompoundStmt *CS = E->getSubStmt();
7929     if (CS->body_empty())
7930       return true;
7931 
7932     BlockScopeRAII Scope(Info);
7933     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7934                                            BE = CS->body_end();
7935          /**/; ++BI) {
7936       if (BI + 1 == BE) {
7937         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7938         if (!FinalExpr) {
7939           Info.FFDiag((*BI)->getBeginLoc(),
7940                       diag::note_constexpr_stmt_expr_unsupported);
7941           return false;
7942         }
7943         return this->Visit(FinalExpr) && Scope.destroy();
7944       }
7945 
7946       APValue ReturnValue;
7947       StmtResult Result = { ReturnValue, nullptr };
7948       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7949       if (ESR != ESR_Succeeded) {
7950         // FIXME: If the statement-expression terminated due to 'return',
7951         // 'break', or 'continue', it would be nice to propagate that to
7952         // the outer statement evaluation rather than bailing out.
7953         if (ESR != ESR_Failed)
7954           Info.FFDiag((*BI)->getBeginLoc(),
7955                       diag::note_constexpr_stmt_expr_unsupported);
7956         return false;
7957       }
7958     }
7959 
7960     llvm_unreachable("Return from function from the loop above.");
7961   }
7962 
7963   /// Visit a value which is evaluated, but whose value is ignored.
7964   void VisitIgnoredValue(const Expr *E) {
7965     EvaluateIgnoredValue(Info, E);
7966   }
7967 
7968   /// Potentially visit a MemberExpr's base expression.
7969   void VisitIgnoredBaseExpression(const Expr *E) {
7970     // While MSVC doesn't evaluate the base expression, it does diagnose the
7971     // presence of side-effecting behavior.
7972     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7973       return;
7974     VisitIgnoredValue(E);
7975   }
7976 };
7977 
7978 } // namespace
7979 
7980 //===----------------------------------------------------------------------===//
7981 // Common base class for lvalue and temporary evaluation.
7982 //===----------------------------------------------------------------------===//
7983 namespace {
7984 template<class Derived>
7985 class LValueExprEvaluatorBase
7986   : public ExprEvaluatorBase<Derived> {
7987 protected:
7988   LValue &Result;
7989   bool InvalidBaseOK;
7990   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7991   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7992 
7993   bool Success(APValue::LValueBase B) {
7994     Result.set(B);
7995     return true;
7996   }
7997 
7998   bool evaluatePointer(const Expr *E, LValue &Result) {
7999     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8000   }
8001 
8002 public:
8003   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8004       : ExprEvaluatorBaseTy(Info), Result(Result),
8005         InvalidBaseOK(InvalidBaseOK) {}
8006 
8007   bool Success(const APValue &V, const Expr *E) {
8008     Result.setFrom(this->Info.Ctx, V);
8009     return true;
8010   }
8011 
8012   bool VisitMemberExpr(const MemberExpr *E) {
8013     // Handle non-static data members.
8014     QualType BaseTy;
8015     bool EvalOK;
8016     if (E->isArrow()) {
8017       EvalOK = evaluatePointer(E->getBase(), Result);
8018       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8019     } else if (E->getBase()->isPRValue()) {
8020       assert(E->getBase()->getType()->isRecordType());
8021       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8022       BaseTy = E->getBase()->getType();
8023     } else {
8024       EvalOK = this->Visit(E->getBase());
8025       BaseTy = E->getBase()->getType();
8026     }
8027     if (!EvalOK) {
8028       if (!InvalidBaseOK)
8029         return false;
8030       Result.setInvalid(E);
8031       return true;
8032     }
8033 
8034     const ValueDecl *MD = E->getMemberDecl();
8035     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8036       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8037              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8038       (void)BaseTy;
8039       if (!HandleLValueMember(this->Info, E, Result, FD))
8040         return false;
8041     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8042       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8043         return false;
8044     } else
8045       return this->Error(E);
8046 
8047     if (MD->getType()->isReferenceType()) {
8048       APValue RefValue;
8049       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8050                                           RefValue))
8051         return false;
8052       return Success(RefValue, E);
8053     }
8054     return true;
8055   }
8056 
8057   bool VisitBinaryOperator(const BinaryOperator *E) {
8058     switch (E->getOpcode()) {
8059     default:
8060       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8061 
8062     case BO_PtrMemD:
8063     case BO_PtrMemI:
8064       return HandleMemberPointerAccess(this->Info, E, Result);
8065     }
8066   }
8067 
8068   bool VisitCastExpr(const CastExpr *E) {
8069     switch (E->getCastKind()) {
8070     default:
8071       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8072 
8073     case CK_DerivedToBase:
8074     case CK_UncheckedDerivedToBase:
8075       if (!this->Visit(E->getSubExpr()))
8076         return false;
8077 
8078       // Now figure out the necessary offset to add to the base LV to get from
8079       // the derived class to the base class.
8080       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8081                                   Result);
8082     }
8083   }
8084 };
8085 }
8086 
8087 //===----------------------------------------------------------------------===//
8088 // LValue Evaluation
8089 //
8090 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8091 // function designators (in C), decl references to void objects (in C), and
8092 // temporaries (if building with -Wno-address-of-temporary).
8093 //
8094 // LValue evaluation produces values comprising a base expression of one of the
8095 // following types:
8096 // - Declarations
8097 //  * VarDecl
8098 //  * FunctionDecl
8099 // - Literals
8100 //  * CompoundLiteralExpr in C (and in global scope in C++)
8101 //  * StringLiteral
8102 //  * PredefinedExpr
8103 //  * ObjCStringLiteralExpr
8104 //  * ObjCEncodeExpr
8105 //  * AddrLabelExpr
8106 //  * BlockExpr
8107 //  * CallExpr for a MakeStringConstant builtin
8108 // - typeid(T) expressions, as TypeInfoLValues
8109 // - Locals and temporaries
8110 //  * MaterializeTemporaryExpr
8111 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8112 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8113 //    from the AST (FIXME).
8114 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8115 //    CallIndex, for a lifetime-extended temporary.
8116 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8117 //    immediate invocation.
8118 // plus an offset in bytes.
8119 //===----------------------------------------------------------------------===//
8120 namespace {
8121 class LValueExprEvaluator
8122   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8123 public:
8124   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8125     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8126 
8127   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8128   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8129 
8130   bool VisitDeclRefExpr(const DeclRefExpr *E);
8131   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8132   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8133   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8134   bool VisitMemberExpr(const MemberExpr *E);
8135   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8136   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8137   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8138   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8139   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8140   bool VisitUnaryDeref(const UnaryOperator *E);
8141   bool VisitUnaryReal(const UnaryOperator *E);
8142   bool VisitUnaryImag(const UnaryOperator *E);
8143   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8144     return VisitUnaryPreIncDec(UO);
8145   }
8146   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8147     return VisitUnaryPreIncDec(UO);
8148   }
8149   bool VisitBinAssign(const BinaryOperator *BO);
8150   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8151 
8152   bool VisitCastExpr(const CastExpr *E) {
8153     switch (E->getCastKind()) {
8154     default:
8155       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8156 
8157     case CK_LValueBitCast:
8158       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8159       if (!Visit(E->getSubExpr()))
8160         return false;
8161       Result.Designator.setInvalid();
8162       return true;
8163 
8164     case CK_BaseToDerived:
8165       if (!Visit(E->getSubExpr()))
8166         return false;
8167       return HandleBaseToDerivedCast(Info, E, Result);
8168 
8169     case CK_Dynamic:
8170       if (!Visit(E->getSubExpr()))
8171         return false;
8172       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8173     }
8174   }
8175 };
8176 } // end anonymous namespace
8177 
8178 /// Evaluate an expression as an lvalue. This can be legitimately called on
8179 /// expressions which are not glvalues, in three cases:
8180 ///  * function designators in C, and
8181 ///  * "extern void" objects
8182 ///  * @selector() expressions in Objective-C
8183 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8184                            bool InvalidBaseOK) {
8185   assert(!E->isValueDependent());
8186   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8187          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8188   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8189 }
8190 
8191 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8192   const NamedDecl *D = E->getDecl();
8193   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8194           UnnamedGlobalConstantDecl>(D))
8195     return Success(cast<ValueDecl>(D));
8196   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8197     return VisitVarDecl(E, VD);
8198   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8199     return Visit(BD->getBinding());
8200   return Error(E);
8201 }
8202 
8203 
8204 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8205 
8206   // If we are within a lambda's call operator, check whether the 'VD' referred
8207   // to within 'E' actually represents a lambda-capture that maps to a
8208   // data-member/field within the closure object, and if so, evaluate to the
8209   // field or what the field refers to.
8210   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8211       isa<DeclRefExpr>(E) &&
8212       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8213     // We don't always have a complete capture-map when checking or inferring if
8214     // the function call operator meets the requirements of a constexpr function
8215     // - but we don't need to evaluate the captures to determine constexprness
8216     // (dcl.constexpr C++17).
8217     if (Info.checkingPotentialConstantExpression())
8218       return false;
8219 
8220     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8221       // Start with 'Result' referring to the complete closure object...
8222       Result = *Info.CurrentCall->This;
8223       // ... then update it to refer to the field of the closure object
8224       // that represents the capture.
8225       if (!HandleLValueMember(Info, E, Result, FD))
8226         return false;
8227       // And if the field is of reference type, update 'Result' to refer to what
8228       // the field refers to.
8229       if (FD->getType()->isReferenceType()) {
8230         APValue RVal;
8231         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8232                                             RVal))
8233           return false;
8234         Result.setFrom(Info.Ctx, RVal);
8235       }
8236       return true;
8237     }
8238   }
8239 
8240   CallStackFrame *Frame = nullptr;
8241   unsigned Version = 0;
8242   if (VD->hasLocalStorage()) {
8243     // Only if a local variable was declared in the function currently being
8244     // evaluated, do we expect to be able to find its value in the current
8245     // frame. (Otherwise it was likely declared in an enclosing context and
8246     // could either have a valid evaluatable value (for e.g. a constexpr
8247     // variable) or be ill-formed (and trigger an appropriate evaluation
8248     // diagnostic)).
8249     CallStackFrame *CurrFrame = Info.CurrentCall;
8250     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8251       // Function parameters are stored in some caller's frame. (Usually the
8252       // immediate caller, but for an inherited constructor they may be more
8253       // distant.)
8254       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8255         if (CurrFrame->Arguments) {
8256           VD = CurrFrame->Arguments.getOrigParam(PVD);
8257           Frame =
8258               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8259           Version = CurrFrame->Arguments.Version;
8260         }
8261       } else {
8262         Frame = CurrFrame;
8263         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8264       }
8265     }
8266   }
8267 
8268   if (!VD->getType()->isReferenceType()) {
8269     if (Frame) {
8270       Result.set({VD, Frame->Index, Version});
8271       return true;
8272     }
8273     return Success(VD);
8274   }
8275 
8276   if (!Info.getLangOpts().CPlusPlus11) {
8277     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8278         << VD << VD->getType();
8279     Info.Note(VD->getLocation(), diag::note_declared_at);
8280   }
8281 
8282   APValue *V;
8283   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8284     return false;
8285   if (!V->hasValue()) {
8286     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8287     // adjust the diagnostic to say that.
8288     if (!Info.checkingPotentialConstantExpression())
8289       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8290     return false;
8291   }
8292   return Success(*V, E);
8293 }
8294 
8295 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8296     const MaterializeTemporaryExpr *E) {
8297   // Walk through the expression to find the materialized temporary itself.
8298   SmallVector<const Expr *, 2> CommaLHSs;
8299   SmallVector<SubobjectAdjustment, 2> Adjustments;
8300   const Expr *Inner =
8301       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8302 
8303   // If we passed any comma operators, evaluate their LHSs.
8304   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8305     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8306       return false;
8307 
8308   // A materialized temporary with static storage duration can appear within the
8309   // result of a constant expression evaluation, so we need to preserve its
8310   // value for use outside this evaluation.
8311   APValue *Value;
8312   if (E->getStorageDuration() == SD_Static) {
8313     // FIXME: What about SD_Thread?
8314     Value = E->getOrCreateValue(true);
8315     *Value = APValue();
8316     Result.set(E);
8317   } else {
8318     Value = &Info.CurrentCall->createTemporary(
8319         E, E->getType(),
8320         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8321                                                      : ScopeKind::Block,
8322         Result);
8323   }
8324 
8325   QualType Type = Inner->getType();
8326 
8327   // Materialize the temporary itself.
8328   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8329     *Value = APValue();
8330     return false;
8331   }
8332 
8333   // Adjust our lvalue to refer to the desired subobject.
8334   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8335     --I;
8336     switch (Adjustments[I].Kind) {
8337     case SubobjectAdjustment::DerivedToBaseAdjustment:
8338       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8339                                 Type, Result))
8340         return false;
8341       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8342       break;
8343 
8344     case SubobjectAdjustment::FieldAdjustment:
8345       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8346         return false;
8347       Type = Adjustments[I].Field->getType();
8348       break;
8349 
8350     case SubobjectAdjustment::MemberPointerAdjustment:
8351       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8352                                      Adjustments[I].Ptr.RHS))
8353         return false;
8354       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8355       break;
8356     }
8357   }
8358 
8359   return true;
8360 }
8361 
8362 bool
8363 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8364   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8365          "lvalue compound literal in c++?");
8366   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8367   // only see this when folding in C, so there's no standard to follow here.
8368   return Success(E);
8369 }
8370 
8371 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8372   TypeInfoLValue TypeInfo;
8373 
8374   if (!E->isPotentiallyEvaluated()) {
8375     if (E->isTypeOperand())
8376       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8377     else
8378       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8379   } else {
8380     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8381       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8382         << E->getExprOperand()->getType()
8383         << E->getExprOperand()->getSourceRange();
8384     }
8385 
8386     if (!Visit(E->getExprOperand()))
8387       return false;
8388 
8389     Optional<DynamicType> DynType =
8390         ComputeDynamicType(Info, E, Result, AK_TypeId);
8391     if (!DynType)
8392       return false;
8393 
8394     TypeInfo =
8395         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8396   }
8397 
8398   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8399 }
8400 
8401 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8402   return Success(E->getGuidDecl());
8403 }
8404 
8405 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8406   // Handle static data members.
8407   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8408     VisitIgnoredBaseExpression(E->getBase());
8409     return VisitVarDecl(E, VD);
8410   }
8411 
8412   // Handle static member functions.
8413   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8414     if (MD->isStatic()) {
8415       VisitIgnoredBaseExpression(E->getBase());
8416       return Success(MD);
8417     }
8418   }
8419 
8420   // Handle non-static data members.
8421   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8422 }
8423 
8424 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8425   // FIXME: Deal with vectors as array subscript bases.
8426   if (E->getBase()->getType()->isVectorType())
8427     return Error(E);
8428 
8429   APSInt Index;
8430   bool Success = true;
8431 
8432   // C++17's rules require us to evaluate the LHS first, regardless of which
8433   // side is the base.
8434   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8435     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8436                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8437       if (!Info.noteFailure())
8438         return false;
8439       Success = false;
8440     }
8441   }
8442 
8443   return Success &&
8444          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8445 }
8446 
8447 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8448   return evaluatePointer(E->getSubExpr(), Result);
8449 }
8450 
8451 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8452   if (!Visit(E->getSubExpr()))
8453     return false;
8454   // __real is a no-op on scalar lvalues.
8455   if (E->getSubExpr()->getType()->isAnyComplexType())
8456     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8457   return true;
8458 }
8459 
8460 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8461   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8462          "lvalue __imag__ on scalar?");
8463   if (!Visit(E->getSubExpr()))
8464     return false;
8465   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8466   return true;
8467 }
8468 
8469 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8470   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8471     return Error(UO);
8472 
8473   if (!this->Visit(UO->getSubExpr()))
8474     return false;
8475 
8476   return handleIncDec(
8477       this->Info, UO, Result, UO->getSubExpr()->getType(),
8478       UO->isIncrementOp(), nullptr);
8479 }
8480 
8481 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8482     const CompoundAssignOperator *CAO) {
8483   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8484     return Error(CAO);
8485 
8486   bool Success = true;
8487 
8488   // C++17 onwards require that we evaluate the RHS first.
8489   APValue RHS;
8490   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8491     if (!Info.noteFailure())
8492       return false;
8493     Success = false;
8494   }
8495 
8496   // The overall lvalue result is the result of evaluating the LHS.
8497   if (!this->Visit(CAO->getLHS()) || !Success)
8498     return false;
8499 
8500   return handleCompoundAssignment(
8501       this->Info, CAO,
8502       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8503       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8504 }
8505 
8506 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8507   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8508     return Error(E);
8509 
8510   bool Success = true;
8511 
8512   // C++17 onwards require that we evaluate the RHS first.
8513   APValue NewVal;
8514   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8515     if (!Info.noteFailure())
8516       return false;
8517     Success = false;
8518   }
8519 
8520   if (!this->Visit(E->getLHS()) || !Success)
8521     return false;
8522 
8523   if (Info.getLangOpts().CPlusPlus20 &&
8524       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8525     return false;
8526 
8527   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8528                           NewVal);
8529 }
8530 
8531 //===----------------------------------------------------------------------===//
8532 // Pointer Evaluation
8533 //===----------------------------------------------------------------------===//
8534 
8535 /// Attempts to compute the number of bytes available at the pointer
8536 /// returned by a function with the alloc_size attribute. Returns true if we
8537 /// were successful. Places an unsigned number into `Result`.
8538 ///
8539 /// This expects the given CallExpr to be a call to a function with an
8540 /// alloc_size attribute.
8541 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8542                                             const CallExpr *Call,
8543                                             llvm::APInt &Result) {
8544   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8545 
8546   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8547   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8548   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8549   if (Call->getNumArgs() <= SizeArgNo)
8550     return false;
8551 
8552   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8553     Expr::EvalResult ExprResult;
8554     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8555       return false;
8556     Into = ExprResult.Val.getInt();
8557     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8558       return false;
8559     Into = Into.zextOrSelf(BitsInSizeT);
8560     return true;
8561   };
8562 
8563   APSInt SizeOfElem;
8564   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8565     return false;
8566 
8567   if (!AllocSize->getNumElemsParam().isValid()) {
8568     Result = std::move(SizeOfElem);
8569     return true;
8570   }
8571 
8572   APSInt NumberOfElems;
8573   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8574   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8575     return false;
8576 
8577   bool Overflow;
8578   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8579   if (Overflow)
8580     return false;
8581 
8582   Result = std::move(BytesAvailable);
8583   return true;
8584 }
8585 
8586 /// Convenience function. LVal's base must be a call to an alloc_size
8587 /// function.
8588 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8589                                             const LValue &LVal,
8590                                             llvm::APInt &Result) {
8591   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8592          "Can't get the size of a non alloc_size function");
8593   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8594   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8595   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8596 }
8597 
8598 /// Attempts to evaluate the given LValueBase as the result of a call to
8599 /// a function with the alloc_size attribute. If it was possible to do so, this
8600 /// function will return true, make Result's Base point to said function call,
8601 /// and mark Result's Base as invalid.
8602 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8603                                       LValue &Result) {
8604   if (Base.isNull())
8605     return false;
8606 
8607   // Because we do no form of static analysis, we only support const variables.
8608   //
8609   // Additionally, we can't support parameters, nor can we support static
8610   // variables (in the latter case, use-before-assign isn't UB; in the former,
8611   // we have no clue what they'll be assigned to).
8612   const auto *VD =
8613       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8614   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8615     return false;
8616 
8617   const Expr *Init = VD->getAnyInitializer();
8618   if (!Init)
8619     return false;
8620 
8621   const Expr *E = Init->IgnoreParens();
8622   if (!tryUnwrapAllocSizeCall(E))
8623     return false;
8624 
8625   // Store E instead of E unwrapped so that the type of the LValue's base is
8626   // what the user wanted.
8627   Result.setInvalid(E);
8628 
8629   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8630   Result.addUnsizedArray(Info, E, Pointee);
8631   return true;
8632 }
8633 
8634 namespace {
8635 class PointerExprEvaluator
8636   : public ExprEvaluatorBase<PointerExprEvaluator> {
8637   LValue &Result;
8638   bool InvalidBaseOK;
8639 
8640   bool Success(const Expr *E) {
8641     Result.set(E);
8642     return true;
8643   }
8644 
8645   bool evaluateLValue(const Expr *E, LValue &Result) {
8646     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8647   }
8648 
8649   bool evaluatePointer(const Expr *E, LValue &Result) {
8650     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8651   }
8652 
8653   bool visitNonBuiltinCallExpr(const CallExpr *E);
8654 public:
8655 
8656   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8657       : ExprEvaluatorBaseTy(info), Result(Result),
8658         InvalidBaseOK(InvalidBaseOK) {}
8659 
8660   bool Success(const APValue &V, const Expr *E) {
8661     Result.setFrom(Info.Ctx, V);
8662     return true;
8663   }
8664   bool ZeroInitialization(const Expr *E) {
8665     Result.setNull(Info.Ctx, E->getType());
8666     return true;
8667   }
8668 
8669   bool VisitBinaryOperator(const BinaryOperator *E);
8670   bool VisitCastExpr(const CastExpr* E);
8671   bool VisitUnaryAddrOf(const UnaryOperator *E);
8672   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8673       { return Success(E); }
8674   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8675     if (E->isExpressibleAsConstantInitializer())
8676       return Success(E);
8677     if (Info.noteFailure())
8678       EvaluateIgnoredValue(Info, E->getSubExpr());
8679     return Error(E);
8680   }
8681   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8682       { return Success(E); }
8683   bool VisitCallExpr(const CallExpr *E);
8684   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8685   bool VisitBlockExpr(const BlockExpr *E) {
8686     if (!E->getBlockDecl()->hasCaptures())
8687       return Success(E);
8688     return Error(E);
8689   }
8690   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8691     // Can't look at 'this' when checking a potential constant expression.
8692     if (Info.checkingPotentialConstantExpression())
8693       return false;
8694     if (!Info.CurrentCall->This) {
8695       if (Info.getLangOpts().CPlusPlus11)
8696         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8697       else
8698         Info.FFDiag(E);
8699       return false;
8700     }
8701     Result = *Info.CurrentCall->This;
8702     // If we are inside a lambda's call operator, the 'this' expression refers
8703     // to the enclosing '*this' object (either by value or reference) which is
8704     // either copied into the closure object's field that represents the '*this'
8705     // or refers to '*this'.
8706     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8707       // Ensure we actually have captured 'this'. (an error will have
8708       // been previously reported if not).
8709       if (!Info.CurrentCall->LambdaThisCaptureField)
8710         return false;
8711 
8712       // Update 'Result' to refer to the data member/field of the closure object
8713       // that represents the '*this' capture.
8714       if (!HandleLValueMember(Info, E, Result,
8715                              Info.CurrentCall->LambdaThisCaptureField))
8716         return false;
8717       // If we captured '*this' by reference, replace the field with its referent.
8718       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8719               ->isPointerType()) {
8720         APValue RVal;
8721         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8722                                             RVal))
8723           return false;
8724 
8725         Result.setFrom(Info.Ctx, RVal);
8726       }
8727     }
8728     return true;
8729   }
8730 
8731   bool VisitCXXNewExpr(const CXXNewExpr *E);
8732 
8733   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8734     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8735     APValue LValResult = E->EvaluateInContext(
8736         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8737     Result.setFrom(Info.Ctx, LValResult);
8738     return true;
8739   }
8740 
8741   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8742     std::string ResultStr = E->ComputeName(Info.Ctx);
8743 
8744     QualType CharTy = Info.Ctx.CharTy.withConst();
8745     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8746                ResultStr.size() + 1);
8747     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8748                                                      ArrayType::Normal, 0);
8749 
8750     StringLiteral *SL =
8751         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8752                               /*Pascal*/ false, ArrayTy, E->getLocation());
8753 
8754     evaluateLValue(SL, Result);
8755     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8756     return true;
8757   }
8758 
8759   // FIXME: Missing: @protocol, @selector
8760 };
8761 } // end anonymous namespace
8762 
8763 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8764                             bool InvalidBaseOK) {
8765   assert(!E->isValueDependent());
8766   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8767   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8768 }
8769 
8770 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8771   if (E->getOpcode() != BO_Add &&
8772       E->getOpcode() != BO_Sub)
8773     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8774 
8775   const Expr *PExp = E->getLHS();
8776   const Expr *IExp = E->getRHS();
8777   if (IExp->getType()->isPointerType())
8778     std::swap(PExp, IExp);
8779 
8780   bool EvalPtrOK = evaluatePointer(PExp, Result);
8781   if (!EvalPtrOK && !Info.noteFailure())
8782     return false;
8783 
8784   llvm::APSInt Offset;
8785   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8786     return false;
8787 
8788   if (E->getOpcode() == BO_Sub)
8789     negateAsSigned(Offset);
8790 
8791   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8792   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8793 }
8794 
8795 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8796   return evaluateLValue(E->getSubExpr(), Result);
8797 }
8798 
8799 // Is the provided decl 'std::source_location::current'?
8800 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8801   if (!FD)
8802     return false;
8803   const IdentifierInfo *FnII = FD->getIdentifier();
8804   if (!FnII || !FnII->isStr("current"))
8805     return false;
8806 
8807   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8808   if (!RD)
8809     return false;
8810 
8811   const IdentifierInfo *ClassII = RD->getIdentifier();
8812   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8813 }
8814 
8815 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8816   const Expr *SubExpr = E->getSubExpr();
8817 
8818   switch (E->getCastKind()) {
8819   default:
8820     break;
8821   case CK_BitCast:
8822   case CK_CPointerToObjCPointerCast:
8823   case CK_BlockPointerToObjCPointerCast:
8824   case CK_AnyPointerToBlockPointerCast:
8825   case CK_AddressSpaceConversion:
8826     if (!Visit(SubExpr))
8827       return false;
8828     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8829     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8830     // also static_casts, but we disallow them as a resolution to DR1312.
8831     if (!E->getType()->isVoidPointerType()) {
8832       // In some circumstances, we permit casting from void* to cv1 T*, when the
8833       // actual pointee object is actually a cv2 T.
8834       bool VoidPtrCastMaybeOK =
8835           !Result.InvalidBase && !Result.Designator.Invalid &&
8836           !Result.IsNullPtr &&
8837           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8838                                           E->getType()->getPointeeType());
8839       // 1. We'll allow it in std::allocator::allocate, and anything which that
8840       //    calls.
8841       // 2. We'll allow it in the body of std::source_location:current.  This is
8842       //    necessary for libstdc++'s <source_location>, which gave its
8843       //    parameter the type void*, and cast from that back to `const __impl*`
8844       //    in the body. (Fixed for new versions in gcc.gnu.org/PR104602).
8845       if (VoidPtrCastMaybeOK &&
8846           (Info.getStdAllocatorCaller("allocate") ||
8847            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8848         // Permitted.
8849       } else {
8850         Result.Designator.setInvalid();
8851         if (SubExpr->getType()->isVoidPointerType())
8852           CCEDiag(E, diag::note_constexpr_invalid_cast)
8853             << 3 << SubExpr->getType();
8854         else
8855           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8856       }
8857     }
8858     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8859       ZeroInitialization(E);
8860     return true;
8861 
8862   case CK_DerivedToBase:
8863   case CK_UncheckedDerivedToBase:
8864     if (!evaluatePointer(E->getSubExpr(), Result))
8865       return false;
8866     if (!Result.Base && Result.Offset.isZero())
8867       return true;
8868 
8869     // Now figure out the necessary offset to add to the base LV to get from
8870     // the derived class to the base class.
8871     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8872                                   castAs<PointerType>()->getPointeeType(),
8873                                 Result);
8874 
8875   case CK_BaseToDerived:
8876     if (!Visit(E->getSubExpr()))
8877       return false;
8878     if (!Result.Base && Result.Offset.isZero())
8879       return true;
8880     return HandleBaseToDerivedCast(Info, E, Result);
8881 
8882   case CK_Dynamic:
8883     if (!Visit(E->getSubExpr()))
8884       return false;
8885     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8886 
8887   case CK_NullToPointer:
8888     VisitIgnoredValue(E->getSubExpr());
8889     return ZeroInitialization(E);
8890 
8891   case CK_IntegralToPointer: {
8892     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8893 
8894     APValue Value;
8895     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8896       break;
8897 
8898     if (Value.isInt()) {
8899       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8900       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8901       Result.Base = (Expr*)nullptr;
8902       Result.InvalidBase = false;
8903       Result.Offset = CharUnits::fromQuantity(N);
8904       Result.Designator.setInvalid();
8905       Result.IsNullPtr = false;
8906       return true;
8907     } else {
8908       // Cast is of an lvalue, no need to change value.
8909       Result.setFrom(Info.Ctx, Value);
8910       return true;
8911     }
8912   }
8913 
8914   case CK_ArrayToPointerDecay: {
8915     if (SubExpr->isGLValue()) {
8916       if (!evaluateLValue(SubExpr, Result))
8917         return false;
8918     } else {
8919       APValue &Value = Info.CurrentCall->createTemporary(
8920           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8921       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8922         return false;
8923     }
8924     // The result is a pointer to the first element of the array.
8925     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8926     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8927       Result.addArray(Info, E, CAT);
8928     else
8929       Result.addUnsizedArray(Info, E, AT->getElementType());
8930     return true;
8931   }
8932 
8933   case CK_FunctionToPointerDecay:
8934     return evaluateLValue(SubExpr, Result);
8935 
8936   case CK_LValueToRValue: {
8937     LValue LVal;
8938     if (!evaluateLValue(E->getSubExpr(), LVal))
8939       return false;
8940 
8941     APValue RVal;
8942     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8943     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8944                                         LVal, RVal))
8945       return InvalidBaseOK &&
8946              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8947     return Success(RVal, E);
8948   }
8949   }
8950 
8951   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8952 }
8953 
8954 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8955                                 UnaryExprOrTypeTrait ExprKind) {
8956   // C++ [expr.alignof]p3:
8957   //     When alignof is applied to a reference type, the result is the
8958   //     alignment of the referenced type.
8959   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8960     T = Ref->getPointeeType();
8961 
8962   if (T.getQualifiers().hasUnaligned())
8963     return CharUnits::One();
8964 
8965   const bool AlignOfReturnsPreferred =
8966       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8967 
8968   // __alignof is defined to return the preferred alignment.
8969   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8970   // as well.
8971   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8972     return Info.Ctx.toCharUnitsFromBits(
8973       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8974   // alignof and _Alignof are defined to return the ABI alignment.
8975   else if (ExprKind == UETT_AlignOf)
8976     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8977   else
8978     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8979 }
8980 
8981 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8982                                 UnaryExprOrTypeTrait ExprKind) {
8983   E = E->IgnoreParens();
8984 
8985   // The kinds of expressions that we have special-case logic here for
8986   // should be kept up to date with the special checks for those
8987   // expressions in Sema.
8988 
8989   // alignof decl is always accepted, even if it doesn't make sense: we default
8990   // to 1 in those cases.
8991   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8992     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8993                                  /*RefAsPointee*/true);
8994 
8995   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8996     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8997                                  /*RefAsPointee*/true);
8998 
8999   return GetAlignOfType(Info, E->getType(), ExprKind);
9000 }
9001 
9002 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9003   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9004     return Info.Ctx.getDeclAlign(VD);
9005   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9006     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9007   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9008 }
9009 
9010 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9011 /// __builtin_is_aligned and __builtin_assume_aligned.
9012 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9013                                  EvalInfo &Info, APSInt &Alignment) {
9014   if (!EvaluateInteger(E, Alignment, Info))
9015     return false;
9016   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9017     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9018     return false;
9019   }
9020   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9021   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9022   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9023     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9024         << MaxValue << ForType << Alignment;
9025     return false;
9026   }
9027   // Ensure both alignment and source value have the same bit width so that we
9028   // don't assert when computing the resulting value.
9029   APSInt ExtAlignment =
9030       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9031   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9032          "Alignment should not be changed by ext/trunc");
9033   Alignment = ExtAlignment;
9034   assert(Alignment.getBitWidth() == SrcWidth);
9035   return true;
9036 }
9037 
9038 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9039 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9040   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9041     return true;
9042 
9043   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9044     return false;
9045 
9046   Result.setInvalid(E);
9047   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9048   Result.addUnsizedArray(Info, E, PointeeTy);
9049   return true;
9050 }
9051 
9052 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9053   if (IsConstantCall(E))
9054     return Success(E);
9055 
9056   if (unsigned BuiltinOp = E->getBuiltinCallee())
9057     return VisitBuiltinCallExpr(E, BuiltinOp);
9058 
9059   return visitNonBuiltinCallExpr(E);
9060 }
9061 
9062 // Determine if T is a character type for which we guarantee that
9063 // sizeof(T) == 1.
9064 static bool isOneByteCharacterType(QualType T) {
9065   return T->isCharType() || T->isChar8Type();
9066 }
9067 
9068 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9069                                                 unsigned BuiltinOp) {
9070   switch (BuiltinOp) {
9071   case Builtin::BI__builtin_addressof:
9072     return evaluateLValue(E->getArg(0), Result);
9073   case Builtin::BI__builtin_assume_aligned: {
9074     // We need to be very careful here because: if the pointer does not have the
9075     // asserted alignment, then the behavior is undefined, and undefined
9076     // behavior is non-constant.
9077     if (!evaluatePointer(E->getArg(0), Result))
9078       return false;
9079 
9080     LValue OffsetResult(Result);
9081     APSInt Alignment;
9082     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9083                               Alignment))
9084       return false;
9085     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9086 
9087     if (E->getNumArgs() > 2) {
9088       APSInt Offset;
9089       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9090         return false;
9091 
9092       int64_t AdditionalOffset = -Offset.getZExtValue();
9093       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9094     }
9095 
9096     // If there is a base object, then it must have the correct alignment.
9097     if (OffsetResult.Base) {
9098       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9099 
9100       if (BaseAlignment < Align) {
9101         Result.Designator.setInvalid();
9102         // FIXME: Add support to Diagnostic for long / long long.
9103         CCEDiag(E->getArg(0),
9104                 diag::note_constexpr_baa_insufficient_alignment) << 0
9105           << (unsigned)BaseAlignment.getQuantity()
9106           << (unsigned)Align.getQuantity();
9107         return false;
9108       }
9109     }
9110 
9111     // The offset must also have the correct alignment.
9112     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9113       Result.Designator.setInvalid();
9114 
9115       (OffsetResult.Base
9116            ? CCEDiag(E->getArg(0),
9117                      diag::note_constexpr_baa_insufficient_alignment) << 1
9118            : CCEDiag(E->getArg(0),
9119                      diag::note_constexpr_baa_value_insufficient_alignment))
9120         << (int)OffsetResult.Offset.getQuantity()
9121         << (unsigned)Align.getQuantity();
9122       return false;
9123     }
9124 
9125     return true;
9126   }
9127   case Builtin::BI__builtin_align_up:
9128   case Builtin::BI__builtin_align_down: {
9129     if (!evaluatePointer(E->getArg(0), Result))
9130       return false;
9131     APSInt Alignment;
9132     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9133                               Alignment))
9134       return false;
9135     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9136     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9137     // For align_up/align_down, we can return the same value if the alignment
9138     // is known to be greater or equal to the requested value.
9139     if (PtrAlign.getQuantity() >= Alignment)
9140       return true;
9141 
9142     // The alignment could be greater than the minimum at run-time, so we cannot
9143     // infer much about the resulting pointer value. One case is possible:
9144     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9145     // can infer the correct index if the requested alignment is smaller than
9146     // the base alignment so we can perform the computation on the offset.
9147     if (BaseAlignment.getQuantity() >= Alignment) {
9148       assert(Alignment.getBitWidth() <= 64 &&
9149              "Cannot handle > 64-bit address-space");
9150       uint64_t Alignment64 = Alignment.getZExtValue();
9151       CharUnits NewOffset = CharUnits::fromQuantity(
9152           BuiltinOp == Builtin::BI__builtin_align_down
9153               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9154               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9155       Result.adjustOffset(NewOffset - Result.Offset);
9156       // TODO: diagnose out-of-bounds values/only allow for arrays?
9157       return true;
9158     }
9159     // Otherwise, we cannot constant-evaluate the result.
9160     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9161         << Alignment;
9162     return false;
9163   }
9164   case Builtin::BI__builtin_operator_new:
9165     return HandleOperatorNewCall(Info, E, Result);
9166   case Builtin::BI__builtin_launder:
9167     return evaluatePointer(E->getArg(0), Result);
9168   case Builtin::BIstrchr:
9169   case Builtin::BIwcschr:
9170   case Builtin::BImemchr:
9171   case Builtin::BIwmemchr:
9172     if (Info.getLangOpts().CPlusPlus11)
9173       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9174         << /*isConstexpr*/0 << /*isConstructor*/0
9175         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9176     else
9177       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9178     LLVM_FALLTHROUGH;
9179   case Builtin::BI__builtin_strchr:
9180   case Builtin::BI__builtin_wcschr:
9181   case Builtin::BI__builtin_memchr:
9182   case Builtin::BI__builtin_char_memchr:
9183   case Builtin::BI__builtin_wmemchr: {
9184     if (!Visit(E->getArg(0)))
9185       return false;
9186     APSInt Desired;
9187     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9188       return false;
9189     uint64_t MaxLength = uint64_t(-1);
9190     if (BuiltinOp != Builtin::BIstrchr &&
9191         BuiltinOp != Builtin::BIwcschr &&
9192         BuiltinOp != Builtin::BI__builtin_strchr &&
9193         BuiltinOp != Builtin::BI__builtin_wcschr) {
9194       APSInt N;
9195       if (!EvaluateInteger(E->getArg(2), N, Info))
9196         return false;
9197       MaxLength = N.getExtValue();
9198     }
9199     // We cannot find the value if there are no candidates to match against.
9200     if (MaxLength == 0u)
9201       return ZeroInitialization(E);
9202     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9203         Result.Designator.Invalid)
9204       return false;
9205     QualType CharTy = Result.Designator.getType(Info.Ctx);
9206     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9207                      BuiltinOp == Builtin::BI__builtin_memchr;
9208     assert(IsRawByte ||
9209            Info.Ctx.hasSameUnqualifiedType(
9210                CharTy, E->getArg(0)->getType()->getPointeeType()));
9211     // Pointers to const void may point to objects of incomplete type.
9212     if (IsRawByte && CharTy->isIncompleteType()) {
9213       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9214       return false;
9215     }
9216     // Give up on byte-oriented matching against multibyte elements.
9217     // FIXME: We can compare the bytes in the correct order.
9218     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9219       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9220           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9221           << CharTy;
9222       return false;
9223     }
9224     // Figure out what value we're actually looking for (after converting to
9225     // the corresponding unsigned type if necessary).
9226     uint64_t DesiredVal;
9227     bool StopAtNull = false;
9228     switch (BuiltinOp) {
9229     case Builtin::BIstrchr:
9230     case Builtin::BI__builtin_strchr:
9231       // strchr compares directly to the passed integer, and therefore
9232       // always fails if given an int that is not a char.
9233       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9234                                                   E->getArg(1)->getType(),
9235                                                   Desired),
9236                                Desired))
9237         return ZeroInitialization(E);
9238       StopAtNull = true;
9239       LLVM_FALLTHROUGH;
9240     case Builtin::BImemchr:
9241     case Builtin::BI__builtin_memchr:
9242     case Builtin::BI__builtin_char_memchr:
9243       // memchr compares by converting both sides to unsigned char. That's also
9244       // correct for strchr if we get this far (to cope with plain char being
9245       // unsigned in the strchr case).
9246       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9247       break;
9248 
9249     case Builtin::BIwcschr:
9250     case Builtin::BI__builtin_wcschr:
9251       StopAtNull = true;
9252       LLVM_FALLTHROUGH;
9253     case Builtin::BIwmemchr:
9254     case Builtin::BI__builtin_wmemchr:
9255       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9256       DesiredVal = Desired.getZExtValue();
9257       break;
9258     }
9259 
9260     for (; MaxLength; --MaxLength) {
9261       APValue Char;
9262       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9263           !Char.isInt())
9264         return false;
9265       if (Char.getInt().getZExtValue() == DesiredVal)
9266         return true;
9267       if (StopAtNull && !Char.getInt())
9268         break;
9269       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9270         return false;
9271     }
9272     // Not found: return nullptr.
9273     return ZeroInitialization(E);
9274   }
9275 
9276   case Builtin::BImemcpy:
9277   case Builtin::BImemmove:
9278   case Builtin::BIwmemcpy:
9279   case Builtin::BIwmemmove:
9280     if (Info.getLangOpts().CPlusPlus11)
9281       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9282         << /*isConstexpr*/0 << /*isConstructor*/0
9283         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9284     else
9285       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9286     LLVM_FALLTHROUGH;
9287   case Builtin::BI__builtin_memcpy:
9288   case Builtin::BI__builtin_memmove:
9289   case Builtin::BI__builtin_wmemcpy:
9290   case Builtin::BI__builtin_wmemmove: {
9291     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9292                  BuiltinOp == Builtin::BIwmemmove ||
9293                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9294                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9295     bool Move = BuiltinOp == Builtin::BImemmove ||
9296                 BuiltinOp == Builtin::BIwmemmove ||
9297                 BuiltinOp == Builtin::BI__builtin_memmove ||
9298                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9299 
9300     // The result of mem* is the first argument.
9301     if (!Visit(E->getArg(0)))
9302       return false;
9303     LValue Dest = Result;
9304 
9305     LValue Src;
9306     if (!EvaluatePointer(E->getArg(1), Src, Info))
9307       return false;
9308 
9309     APSInt N;
9310     if (!EvaluateInteger(E->getArg(2), N, Info))
9311       return false;
9312     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9313 
9314     // If the size is zero, we treat this as always being a valid no-op.
9315     // (Even if one of the src and dest pointers is null.)
9316     if (!N)
9317       return true;
9318 
9319     // Otherwise, if either of the operands is null, we can't proceed. Don't
9320     // try to determine the type of the copied objects, because there aren't
9321     // any.
9322     if (!Src.Base || !Dest.Base) {
9323       APValue Val;
9324       (!Src.Base ? Src : Dest).moveInto(Val);
9325       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9326           << Move << WChar << !!Src.Base
9327           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9328       return false;
9329     }
9330     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9331       return false;
9332 
9333     // We require that Src and Dest are both pointers to arrays of
9334     // trivially-copyable type. (For the wide version, the designator will be
9335     // invalid if the designated object is not a wchar_t.)
9336     QualType T = Dest.Designator.getType(Info.Ctx);
9337     QualType SrcT = Src.Designator.getType(Info.Ctx);
9338     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9339       // FIXME: Consider using our bit_cast implementation to support this.
9340       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9341       return false;
9342     }
9343     if (T->isIncompleteType()) {
9344       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9345       return false;
9346     }
9347     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9348       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9349       return false;
9350     }
9351 
9352     // Figure out how many T's we're copying.
9353     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9354     if (!WChar) {
9355       uint64_t Remainder;
9356       llvm::APInt OrigN = N;
9357       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9358       if (Remainder) {
9359         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9360             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9361             << (unsigned)TSize;
9362         return false;
9363       }
9364     }
9365 
9366     // Check that the copying will remain within the arrays, just so that we
9367     // can give a more meaningful diagnostic. This implicitly also checks that
9368     // N fits into 64 bits.
9369     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9370     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9371     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9372       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9373           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9374           << toString(N, 10, /*Signed*/false);
9375       return false;
9376     }
9377     uint64_t NElems = N.getZExtValue();
9378     uint64_t NBytes = NElems * TSize;
9379 
9380     // Check for overlap.
9381     int Direction = 1;
9382     if (HasSameBase(Src, Dest)) {
9383       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9384       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9385       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9386         // Dest is inside the source region.
9387         if (!Move) {
9388           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9389           return false;
9390         }
9391         // For memmove and friends, copy backwards.
9392         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9393             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9394           return false;
9395         Direction = -1;
9396       } else if (!Move && SrcOffset >= DestOffset &&
9397                  SrcOffset - DestOffset < NBytes) {
9398         // Src is inside the destination region for memcpy: invalid.
9399         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9400         return false;
9401       }
9402     }
9403 
9404     while (true) {
9405       APValue Val;
9406       // FIXME: Set WantObjectRepresentation to true if we're copying a
9407       // char-like type?
9408       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9409           !handleAssignment(Info, E, Dest, T, Val))
9410         return false;
9411       // Do not iterate past the last element; if we're copying backwards, that
9412       // might take us off the start of the array.
9413       if (--NElems == 0)
9414         return true;
9415       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9416           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9417         return false;
9418     }
9419   }
9420 
9421   default:
9422     break;
9423   }
9424 
9425   return visitNonBuiltinCallExpr(E);
9426 }
9427 
9428 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9429                                      APValue &Result, const InitListExpr *ILE,
9430                                      QualType AllocType);
9431 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9432                                           APValue &Result,
9433                                           const CXXConstructExpr *CCE,
9434                                           QualType AllocType);
9435 
9436 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9437   if (!Info.getLangOpts().CPlusPlus20)
9438     Info.CCEDiag(E, diag::note_constexpr_new);
9439 
9440   // We cannot speculatively evaluate a delete expression.
9441   if (Info.SpeculativeEvaluationDepth)
9442     return false;
9443 
9444   FunctionDecl *OperatorNew = E->getOperatorNew();
9445 
9446   bool IsNothrow = false;
9447   bool IsPlacement = false;
9448   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9449       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9450     // FIXME Support array placement new.
9451     assert(E->getNumPlacementArgs() == 1);
9452     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9453       return false;
9454     if (Result.Designator.Invalid)
9455       return false;
9456     IsPlacement = true;
9457   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9458     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9459         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9460     return false;
9461   } else if (E->getNumPlacementArgs()) {
9462     // The only new-placement list we support is of the form (std::nothrow).
9463     //
9464     // FIXME: There is no restriction on this, but it's not clear that any
9465     // other form makes any sense. We get here for cases such as:
9466     //
9467     //   new (std::align_val_t{N}) X(int)
9468     //
9469     // (which should presumably be valid only if N is a multiple of
9470     // alignof(int), and in any case can't be deallocated unless N is
9471     // alignof(X) and X has new-extended alignment).
9472     if (E->getNumPlacementArgs() != 1 ||
9473         !E->getPlacementArg(0)->getType()->isNothrowT())
9474       return Error(E, diag::note_constexpr_new_placement);
9475 
9476     LValue Nothrow;
9477     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9478       return false;
9479     IsNothrow = true;
9480   }
9481 
9482   const Expr *Init = E->getInitializer();
9483   const InitListExpr *ResizedArrayILE = nullptr;
9484   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9485   bool ValueInit = false;
9486 
9487   QualType AllocType = E->getAllocatedType();
9488   if (Optional<const Expr *> ArraySize = E->getArraySize()) {
9489     const Expr *Stripped = *ArraySize;
9490     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9491          Stripped = ICE->getSubExpr())
9492       if (ICE->getCastKind() != CK_NoOp &&
9493           ICE->getCastKind() != CK_IntegralCast)
9494         break;
9495 
9496     llvm::APSInt ArrayBound;
9497     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9498       return false;
9499 
9500     // C++ [expr.new]p9:
9501     //   The expression is erroneous if:
9502     //   -- [...] its value before converting to size_t [or] applying the
9503     //      second standard conversion sequence is less than zero
9504     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9505       if (IsNothrow)
9506         return ZeroInitialization(E);
9507 
9508       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9509           << ArrayBound << (*ArraySize)->getSourceRange();
9510       return false;
9511     }
9512 
9513     //   -- its value is such that the size of the allocated object would
9514     //      exceed the implementation-defined limit
9515     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9516                                                 ArrayBound) >
9517         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9518       if (IsNothrow)
9519         return ZeroInitialization(E);
9520 
9521       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9522         << ArrayBound << (*ArraySize)->getSourceRange();
9523       return false;
9524     }
9525 
9526     //   -- the new-initializer is a braced-init-list and the number of
9527     //      array elements for which initializers are provided [...]
9528     //      exceeds the number of elements to initialize
9529     if (!Init) {
9530       // No initialization is performed.
9531     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9532                isa<ImplicitValueInitExpr>(Init)) {
9533       ValueInit = true;
9534     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9535       ResizedArrayCCE = CCE;
9536     } else {
9537       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9538       assert(CAT && "unexpected type for array initializer");
9539 
9540       unsigned Bits =
9541           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9542       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9543       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9544       if (InitBound.ugt(AllocBound)) {
9545         if (IsNothrow)
9546           return ZeroInitialization(E);
9547 
9548         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9549             << toString(AllocBound, 10, /*Signed=*/false)
9550             << toString(InitBound, 10, /*Signed=*/false)
9551             << (*ArraySize)->getSourceRange();
9552         return false;
9553       }
9554 
9555       // If the sizes differ, we must have an initializer list, and we need
9556       // special handling for this case when we initialize.
9557       if (InitBound != AllocBound)
9558         ResizedArrayILE = cast<InitListExpr>(Init);
9559     }
9560 
9561     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9562                                               ArrayType::Normal, 0);
9563   } else {
9564     assert(!AllocType->isArrayType() &&
9565            "array allocation with non-array new");
9566   }
9567 
9568   APValue *Val;
9569   if (IsPlacement) {
9570     AccessKinds AK = AK_Construct;
9571     struct FindObjectHandler {
9572       EvalInfo &Info;
9573       const Expr *E;
9574       QualType AllocType;
9575       const AccessKinds AccessKind;
9576       APValue *Value;
9577 
9578       typedef bool result_type;
9579       bool failed() { return false; }
9580       bool found(APValue &Subobj, QualType SubobjType) {
9581         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9582         // old name of the object to be used to name the new object.
9583         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9584           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9585             SubobjType << AllocType;
9586           return false;
9587         }
9588         Value = &Subobj;
9589         return true;
9590       }
9591       bool found(APSInt &Value, QualType SubobjType) {
9592         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9593         return false;
9594       }
9595       bool found(APFloat &Value, QualType SubobjType) {
9596         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9597         return false;
9598       }
9599     } Handler = {Info, E, AllocType, AK, nullptr};
9600 
9601     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9602     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9603       return false;
9604 
9605     Val = Handler.Value;
9606 
9607     // [basic.life]p1:
9608     //   The lifetime of an object o of type T ends when [...] the storage
9609     //   which the object occupies is [...] reused by an object that is not
9610     //   nested within o (6.6.2).
9611     *Val = APValue();
9612   } else {
9613     // Perform the allocation and obtain a pointer to the resulting object.
9614     Val = Info.createHeapAlloc(E, AllocType, Result);
9615     if (!Val)
9616       return false;
9617   }
9618 
9619   if (ValueInit) {
9620     ImplicitValueInitExpr VIE(AllocType);
9621     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9622       return false;
9623   } else if (ResizedArrayILE) {
9624     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9625                                   AllocType))
9626       return false;
9627   } else if (ResizedArrayCCE) {
9628     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9629                                        AllocType))
9630       return false;
9631   } else if (Init) {
9632     if (!EvaluateInPlace(*Val, Info, Result, Init))
9633       return false;
9634   } else if (!getDefaultInitValue(AllocType, *Val)) {
9635     return false;
9636   }
9637 
9638   // Array new returns a pointer to the first element, not a pointer to the
9639   // array.
9640   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9641     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9642 
9643   return true;
9644 }
9645 //===----------------------------------------------------------------------===//
9646 // Member Pointer Evaluation
9647 //===----------------------------------------------------------------------===//
9648 
9649 namespace {
9650 class MemberPointerExprEvaluator
9651   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9652   MemberPtr &Result;
9653 
9654   bool Success(const ValueDecl *D) {
9655     Result = MemberPtr(D);
9656     return true;
9657   }
9658 public:
9659 
9660   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9661     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9662 
9663   bool Success(const APValue &V, const Expr *E) {
9664     Result.setFrom(V);
9665     return true;
9666   }
9667   bool ZeroInitialization(const Expr *E) {
9668     return Success((const ValueDecl*)nullptr);
9669   }
9670 
9671   bool VisitCastExpr(const CastExpr *E);
9672   bool VisitUnaryAddrOf(const UnaryOperator *E);
9673 };
9674 } // end anonymous namespace
9675 
9676 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9677                                   EvalInfo &Info) {
9678   assert(!E->isValueDependent());
9679   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9680   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9681 }
9682 
9683 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9684   switch (E->getCastKind()) {
9685   default:
9686     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9687 
9688   case CK_NullToMemberPointer:
9689     VisitIgnoredValue(E->getSubExpr());
9690     return ZeroInitialization(E);
9691 
9692   case CK_BaseToDerivedMemberPointer: {
9693     if (!Visit(E->getSubExpr()))
9694       return false;
9695     if (E->path_empty())
9696       return true;
9697     // Base-to-derived member pointer casts store the path in derived-to-base
9698     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9699     // the wrong end of the derived->base arc, so stagger the path by one class.
9700     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9701     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9702          PathI != PathE; ++PathI) {
9703       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9704       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9705       if (!Result.castToDerived(Derived))
9706         return Error(E);
9707     }
9708     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9709     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9710       return Error(E);
9711     return true;
9712   }
9713 
9714   case CK_DerivedToBaseMemberPointer:
9715     if (!Visit(E->getSubExpr()))
9716       return false;
9717     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9718          PathE = E->path_end(); PathI != PathE; ++PathI) {
9719       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9720       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9721       if (!Result.castToBase(Base))
9722         return Error(E);
9723     }
9724     return true;
9725   }
9726 }
9727 
9728 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9729   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9730   // member can be formed.
9731   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9732 }
9733 
9734 //===----------------------------------------------------------------------===//
9735 // Record Evaluation
9736 //===----------------------------------------------------------------------===//
9737 
9738 namespace {
9739   class RecordExprEvaluator
9740   : public ExprEvaluatorBase<RecordExprEvaluator> {
9741     const LValue &This;
9742     APValue &Result;
9743   public:
9744 
9745     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9746       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9747 
9748     bool Success(const APValue &V, const Expr *E) {
9749       Result = V;
9750       return true;
9751     }
9752     bool ZeroInitialization(const Expr *E) {
9753       return ZeroInitialization(E, E->getType());
9754     }
9755     bool ZeroInitialization(const Expr *E, QualType T);
9756 
9757     bool VisitCallExpr(const CallExpr *E) {
9758       return handleCallExpr(E, Result, &This);
9759     }
9760     bool VisitCastExpr(const CastExpr *E);
9761     bool VisitInitListExpr(const InitListExpr *E);
9762     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9763       return VisitCXXConstructExpr(E, E->getType());
9764     }
9765     bool VisitLambdaExpr(const LambdaExpr *E);
9766     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9767     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9768     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9769     bool VisitBinCmp(const BinaryOperator *E);
9770   };
9771 }
9772 
9773 /// Perform zero-initialization on an object of non-union class type.
9774 /// C++11 [dcl.init]p5:
9775 ///  To zero-initialize an object or reference of type T means:
9776 ///    [...]
9777 ///    -- if T is a (possibly cv-qualified) non-union class type,
9778 ///       each non-static data member and each base-class subobject is
9779 ///       zero-initialized
9780 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9781                                           const RecordDecl *RD,
9782                                           const LValue &This, APValue &Result) {
9783   assert(!RD->isUnion() && "Expected non-union class type");
9784   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9785   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9786                    std::distance(RD->field_begin(), RD->field_end()));
9787 
9788   if (RD->isInvalidDecl()) return false;
9789   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9790 
9791   if (CD) {
9792     unsigned Index = 0;
9793     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9794            End = CD->bases_end(); I != End; ++I, ++Index) {
9795       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9796       LValue Subobject = This;
9797       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9798         return false;
9799       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9800                                          Result.getStructBase(Index)))
9801         return false;
9802     }
9803   }
9804 
9805   for (const auto *I : RD->fields()) {
9806     // -- if T is a reference type, no initialization is performed.
9807     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9808       continue;
9809 
9810     LValue Subobject = This;
9811     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9812       return false;
9813 
9814     ImplicitValueInitExpr VIE(I->getType());
9815     if (!EvaluateInPlace(
9816           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9817       return false;
9818   }
9819 
9820   return true;
9821 }
9822 
9823 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9824   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9825   if (RD->isInvalidDecl()) return false;
9826   if (RD->isUnion()) {
9827     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9828     // object's first non-static named data member is zero-initialized
9829     RecordDecl::field_iterator I = RD->field_begin();
9830     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9831       ++I;
9832     if (I == RD->field_end()) {
9833       Result = APValue((const FieldDecl*)nullptr);
9834       return true;
9835     }
9836 
9837     LValue Subobject = This;
9838     if (!HandleLValueMember(Info, E, Subobject, *I))
9839       return false;
9840     Result = APValue(*I);
9841     ImplicitValueInitExpr VIE(I->getType());
9842     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9843   }
9844 
9845   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9846     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9847     return false;
9848   }
9849 
9850   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9851 }
9852 
9853 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9854   switch (E->getCastKind()) {
9855   default:
9856     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9857 
9858   case CK_ConstructorConversion:
9859     return Visit(E->getSubExpr());
9860 
9861   case CK_DerivedToBase:
9862   case CK_UncheckedDerivedToBase: {
9863     APValue DerivedObject;
9864     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9865       return false;
9866     if (!DerivedObject.isStruct())
9867       return Error(E->getSubExpr());
9868 
9869     // Derived-to-base rvalue conversion: just slice off the derived part.
9870     APValue *Value = &DerivedObject;
9871     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9872     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9873          PathE = E->path_end(); PathI != PathE; ++PathI) {
9874       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9875       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9876       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9877       RD = Base;
9878     }
9879     Result = *Value;
9880     return true;
9881   }
9882   }
9883 }
9884 
9885 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9886   if (E->isTransparent())
9887     return Visit(E->getInit(0));
9888 
9889   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9890   if (RD->isInvalidDecl()) return false;
9891   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9892   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9893 
9894   EvalInfo::EvaluatingConstructorRAII EvalObj(
9895       Info,
9896       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9897       CXXRD && CXXRD->getNumBases());
9898 
9899   if (RD->isUnion()) {
9900     const FieldDecl *Field = E->getInitializedFieldInUnion();
9901     Result = APValue(Field);
9902     if (!Field)
9903       return true;
9904 
9905     // If the initializer list for a union does not contain any elements, the
9906     // first element of the union is value-initialized.
9907     // FIXME: The element should be initialized from an initializer list.
9908     //        Is this difference ever observable for initializer lists which
9909     //        we don't build?
9910     ImplicitValueInitExpr VIE(Field->getType());
9911     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9912 
9913     LValue Subobject = This;
9914     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9915       return false;
9916 
9917     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9918     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9919                                   isa<CXXDefaultInitExpr>(InitExpr));
9920 
9921     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9922       if (Field->isBitField())
9923         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9924                                      Field);
9925       return true;
9926     }
9927 
9928     return false;
9929   }
9930 
9931   if (!Result.hasValue())
9932     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9933                      std::distance(RD->field_begin(), RD->field_end()));
9934   unsigned ElementNo = 0;
9935   bool Success = true;
9936 
9937   // Initialize base classes.
9938   if (CXXRD && CXXRD->getNumBases()) {
9939     for (const auto &Base : CXXRD->bases()) {
9940       assert(ElementNo < E->getNumInits() && "missing init for base class");
9941       const Expr *Init = E->getInit(ElementNo);
9942 
9943       LValue Subobject = This;
9944       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9945         return false;
9946 
9947       APValue &FieldVal = Result.getStructBase(ElementNo);
9948       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9949         if (!Info.noteFailure())
9950           return false;
9951         Success = false;
9952       }
9953       ++ElementNo;
9954     }
9955 
9956     EvalObj.finishedConstructingBases();
9957   }
9958 
9959   // Initialize members.
9960   for (const auto *Field : RD->fields()) {
9961     // Anonymous bit-fields are not considered members of the class for
9962     // purposes of aggregate initialization.
9963     if (Field->isUnnamedBitfield())
9964       continue;
9965 
9966     LValue Subobject = This;
9967 
9968     bool HaveInit = ElementNo < E->getNumInits();
9969 
9970     // FIXME: Diagnostics here should point to the end of the initializer
9971     // list, not the start.
9972     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9973                             Subobject, Field, &Layout))
9974       return false;
9975 
9976     // Perform an implicit value-initialization for members beyond the end of
9977     // the initializer list.
9978     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9979     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9980 
9981     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9982     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9983                                   isa<CXXDefaultInitExpr>(Init));
9984 
9985     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9986     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9987         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9988                                                        FieldVal, Field))) {
9989       if (!Info.noteFailure())
9990         return false;
9991       Success = false;
9992     }
9993   }
9994 
9995   EvalObj.finishedConstructingFields();
9996 
9997   return Success;
9998 }
9999 
10000 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10001                                                 QualType T) {
10002   // Note that E's type is not necessarily the type of our class here; we might
10003   // be initializing an array element instead.
10004   const CXXConstructorDecl *FD = E->getConstructor();
10005   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10006 
10007   bool ZeroInit = E->requiresZeroInitialization();
10008   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10009     // If we've already performed zero-initialization, we're already done.
10010     if (Result.hasValue())
10011       return true;
10012 
10013     if (ZeroInit)
10014       return ZeroInitialization(E, T);
10015 
10016     return getDefaultInitValue(T, Result);
10017   }
10018 
10019   const FunctionDecl *Definition = nullptr;
10020   auto Body = FD->getBody(Definition);
10021 
10022   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10023     return false;
10024 
10025   // Avoid materializing a temporary for an elidable copy/move constructor.
10026   if (E->isElidable() && !ZeroInit) {
10027     // FIXME: This only handles the simplest case, where the source object
10028     //        is passed directly as the first argument to the constructor.
10029     //        This should also handle stepping though implicit casts and
10030     //        and conversion sequences which involve two steps, with a
10031     //        conversion operator followed by a converting constructor.
10032     const Expr *SrcObj = E->getArg(0);
10033     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10034     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10035     if (const MaterializeTemporaryExpr *ME =
10036             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10037       return Visit(ME->getSubExpr());
10038   }
10039 
10040   if (ZeroInit && !ZeroInitialization(E, T))
10041     return false;
10042 
10043   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
10044   return HandleConstructorCall(E, This, Args,
10045                                cast<CXXConstructorDecl>(Definition), Info,
10046                                Result);
10047 }
10048 
10049 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10050     const CXXInheritedCtorInitExpr *E) {
10051   if (!Info.CurrentCall) {
10052     assert(Info.checkingPotentialConstantExpression());
10053     return false;
10054   }
10055 
10056   const CXXConstructorDecl *FD = E->getConstructor();
10057   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10058     return false;
10059 
10060   const FunctionDecl *Definition = nullptr;
10061   auto Body = FD->getBody(Definition);
10062 
10063   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10064     return false;
10065 
10066   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10067                                cast<CXXConstructorDecl>(Definition), Info,
10068                                Result);
10069 }
10070 
10071 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10072     const CXXStdInitializerListExpr *E) {
10073   const ConstantArrayType *ArrayType =
10074       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10075 
10076   LValue Array;
10077   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10078     return false;
10079 
10080   // Get a pointer to the first element of the array.
10081   Array.addArray(Info, E, ArrayType);
10082 
10083   auto InvalidType = [&] {
10084     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10085       << E->getType();
10086     return false;
10087   };
10088 
10089   // FIXME: Perform the checks on the field types in SemaInit.
10090   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10091   RecordDecl::field_iterator Field = Record->field_begin();
10092   if (Field == Record->field_end())
10093     return InvalidType();
10094 
10095   // Start pointer.
10096   if (!Field->getType()->isPointerType() ||
10097       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10098                             ArrayType->getElementType()))
10099     return InvalidType();
10100 
10101   // FIXME: What if the initializer_list type has base classes, etc?
10102   Result = APValue(APValue::UninitStruct(), 0, 2);
10103   Array.moveInto(Result.getStructField(0));
10104 
10105   if (++Field == Record->field_end())
10106     return InvalidType();
10107 
10108   if (Field->getType()->isPointerType() &&
10109       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10110                            ArrayType->getElementType())) {
10111     // End pointer.
10112     if (!HandleLValueArrayAdjustment(Info, E, Array,
10113                                      ArrayType->getElementType(),
10114                                      ArrayType->getSize().getZExtValue()))
10115       return false;
10116     Array.moveInto(Result.getStructField(1));
10117   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10118     // Length.
10119     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10120   else
10121     return InvalidType();
10122 
10123   if (++Field != Record->field_end())
10124     return InvalidType();
10125 
10126   return true;
10127 }
10128 
10129 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10130   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10131   if (ClosureClass->isInvalidDecl())
10132     return false;
10133 
10134   const size_t NumFields =
10135       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10136 
10137   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10138                                             E->capture_init_end()) &&
10139          "The number of lambda capture initializers should equal the number of "
10140          "fields within the closure type");
10141 
10142   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10143   // Iterate through all the lambda's closure object's fields and initialize
10144   // them.
10145   auto *CaptureInitIt = E->capture_init_begin();
10146   bool Success = true;
10147   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10148   for (const auto *Field : ClosureClass->fields()) {
10149     assert(CaptureInitIt != E->capture_init_end());
10150     // Get the initializer for this field
10151     Expr *const CurFieldInit = *CaptureInitIt++;
10152 
10153     // If there is no initializer, either this is a VLA or an error has
10154     // occurred.
10155     if (!CurFieldInit)
10156       return Error(E);
10157 
10158     LValue Subobject = This;
10159 
10160     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10161       return false;
10162 
10163     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10164     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10165       if (!Info.keepEvaluatingAfterFailure())
10166         return false;
10167       Success = false;
10168     }
10169   }
10170   return Success;
10171 }
10172 
10173 static bool EvaluateRecord(const Expr *E, const LValue &This,
10174                            APValue &Result, EvalInfo &Info) {
10175   assert(!E->isValueDependent());
10176   assert(E->isPRValue() && E->getType()->isRecordType() &&
10177          "can't evaluate expression as a record rvalue");
10178   return RecordExprEvaluator(Info, This, Result).Visit(E);
10179 }
10180 
10181 //===----------------------------------------------------------------------===//
10182 // Temporary Evaluation
10183 //
10184 // Temporaries are represented in the AST as rvalues, but generally behave like
10185 // lvalues. The full-object of which the temporary is a subobject is implicitly
10186 // materialized so that a reference can bind to it.
10187 //===----------------------------------------------------------------------===//
10188 namespace {
10189 class TemporaryExprEvaluator
10190   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10191 public:
10192   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10193     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10194 
10195   /// Visit an expression which constructs the value of this temporary.
10196   bool VisitConstructExpr(const Expr *E) {
10197     APValue &Value = Info.CurrentCall->createTemporary(
10198         E, E->getType(), ScopeKind::FullExpression, Result);
10199     return EvaluateInPlace(Value, Info, Result, E);
10200   }
10201 
10202   bool VisitCastExpr(const CastExpr *E) {
10203     switch (E->getCastKind()) {
10204     default:
10205       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10206 
10207     case CK_ConstructorConversion:
10208       return VisitConstructExpr(E->getSubExpr());
10209     }
10210   }
10211   bool VisitInitListExpr(const InitListExpr *E) {
10212     return VisitConstructExpr(E);
10213   }
10214   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10215     return VisitConstructExpr(E);
10216   }
10217   bool VisitCallExpr(const CallExpr *E) {
10218     return VisitConstructExpr(E);
10219   }
10220   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10221     return VisitConstructExpr(E);
10222   }
10223   bool VisitLambdaExpr(const LambdaExpr *E) {
10224     return VisitConstructExpr(E);
10225   }
10226 };
10227 } // end anonymous namespace
10228 
10229 /// Evaluate an expression of record type as a temporary.
10230 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10231   assert(!E->isValueDependent());
10232   assert(E->isPRValue() && E->getType()->isRecordType());
10233   return TemporaryExprEvaluator(Info, Result).Visit(E);
10234 }
10235 
10236 //===----------------------------------------------------------------------===//
10237 // Vector Evaluation
10238 //===----------------------------------------------------------------------===//
10239 
10240 namespace {
10241   class VectorExprEvaluator
10242   : public ExprEvaluatorBase<VectorExprEvaluator> {
10243     APValue &Result;
10244   public:
10245 
10246     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10247       : ExprEvaluatorBaseTy(info), Result(Result) {}
10248 
10249     bool Success(ArrayRef<APValue> V, const Expr *E) {
10250       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10251       // FIXME: remove this APValue copy.
10252       Result = APValue(V.data(), V.size());
10253       return true;
10254     }
10255     bool Success(const APValue &V, const Expr *E) {
10256       assert(V.isVector());
10257       Result = V;
10258       return true;
10259     }
10260     bool ZeroInitialization(const Expr *E);
10261 
10262     bool VisitUnaryReal(const UnaryOperator *E)
10263       { return Visit(E->getSubExpr()); }
10264     bool VisitCastExpr(const CastExpr* E);
10265     bool VisitInitListExpr(const InitListExpr *E);
10266     bool VisitUnaryImag(const UnaryOperator *E);
10267     bool VisitBinaryOperator(const BinaryOperator *E);
10268     bool VisitUnaryOperator(const UnaryOperator *E);
10269     // FIXME: Missing: conditional operator (for GNU
10270     //                 conditional select), shufflevector, ExtVectorElementExpr
10271   };
10272 } // end anonymous namespace
10273 
10274 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10275   assert(E->isPRValue() && E->getType()->isVectorType() &&
10276          "not a vector prvalue");
10277   return VectorExprEvaluator(Info, Result).Visit(E);
10278 }
10279 
10280 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10281   const VectorType *VTy = E->getType()->castAs<VectorType>();
10282   unsigned NElts = VTy->getNumElements();
10283 
10284   const Expr *SE = E->getSubExpr();
10285   QualType SETy = SE->getType();
10286 
10287   switch (E->getCastKind()) {
10288   case CK_VectorSplat: {
10289     APValue Val = APValue();
10290     if (SETy->isIntegerType()) {
10291       APSInt IntResult;
10292       if (!EvaluateInteger(SE, IntResult, Info))
10293         return false;
10294       Val = APValue(std::move(IntResult));
10295     } else if (SETy->isRealFloatingType()) {
10296       APFloat FloatResult(0.0);
10297       if (!EvaluateFloat(SE, FloatResult, Info))
10298         return false;
10299       Val = APValue(std::move(FloatResult));
10300     } else {
10301       return Error(E);
10302     }
10303 
10304     // Splat and create vector APValue.
10305     SmallVector<APValue, 4> Elts(NElts, Val);
10306     return Success(Elts, E);
10307   }
10308   case CK_BitCast: {
10309     // Evaluate the operand into an APInt we can extract from.
10310     llvm::APInt SValInt;
10311     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10312       return false;
10313     // Extract the elements
10314     QualType EltTy = VTy->getElementType();
10315     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10316     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10317     SmallVector<APValue, 4> Elts;
10318     if (EltTy->isRealFloatingType()) {
10319       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10320       unsigned FloatEltSize = EltSize;
10321       if (&Sem == &APFloat::x87DoubleExtended())
10322         FloatEltSize = 80;
10323       for (unsigned i = 0; i < NElts; i++) {
10324         llvm::APInt Elt;
10325         if (BigEndian)
10326           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10327         else
10328           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10329         Elts.push_back(APValue(APFloat(Sem, Elt)));
10330       }
10331     } else if (EltTy->isIntegerType()) {
10332       for (unsigned i = 0; i < NElts; i++) {
10333         llvm::APInt Elt;
10334         if (BigEndian)
10335           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10336         else
10337           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10338         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10339       }
10340     } else {
10341       return Error(E);
10342     }
10343     return Success(Elts, E);
10344   }
10345   default:
10346     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10347   }
10348 }
10349 
10350 bool
10351 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10352   const VectorType *VT = E->getType()->castAs<VectorType>();
10353   unsigned NumInits = E->getNumInits();
10354   unsigned NumElements = VT->getNumElements();
10355 
10356   QualType EltTy = VT->getElementType();
10357   SmallVector<APValue, 4> Elements;
10358 
10359   // The number of initializers can be less than the number of
10360   // vector elements. For OpenCL, this can be due to nested vector
10361   // initialization. For GCC compatibility, missing trailing elements
10362   // should be initialized with zeroes.
10363   unsigned CountInits = 0, CountElts = 0;
10364   while (CountElts < NumElements) {
10365     // Handle nested vector initialization.
10366     if (CountInits < NumInits
10367         && E->getInit(CountInits)->getType()->isVectorType()) {
10368       APValue v;
10369       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10370         return Error(E);
10371       unsigned vlen = v.getVectorLength();
10372       for (unsigned j = 0; j < vlen; j++)
10373         Elements.push_back(v.getVectorElt(j));
10374       CountElts += vlen;
10375     } else if (EltTy->isIntegerType()) {
10376       llvm::APSInt sInt(32);
10377       if (CountInits < NumInits) {
10378         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10379           return false;
10380       } else // trailing integer zero.
10381         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10382       Elements.push_back(APValue(sInt));
10383       CountElts++;
10384     } else {
10385       llvm::APFloat f(0.0);
10386       if (CountInits < NumInits) {
10387         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10388           return false;
10389       } else // trailing float zero.
10390         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10391       Elements.push_back(APValue(f));
10392       CountElts++;
10393     }
10394     CountInits++;
10395   }
10396   return Success(Elements, E);
10397 }
10398 
10399 bool
10400 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10401   const auto *VT = E->getType()->castAs<VectorType>();
10402   QualType EltTy = VT->getElementType();
10403   APValue ZeroElement;
10404   if (EltTy->isIntegerType())
10405     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10406   else
10407     ZeroElement =
10408         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10409 
10410   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10411   return Success(Elements, E);
10412 }
10413 
10414 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10415   VisitIgnoredValue(E->getSubExpr());
10416   return ZeroInitialization(E);
10417 }
10418 
10419 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10420   BinaryOperatorKind Op = E->getOpcode();
10421   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10422          "Operation not supported on vector types");
10423 
10424   if (Op == BO_Comma)
10425     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10426 
10427   Expr *LHS = E->getLHS();
10428   Expr *RHS = E->getRHS();
10429 
10430   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10431          "Must both be vector types");
10432   // Checking JUST the types are the same would be fine, except shifts don't
10433   // need to have their types be the same (since you always shift by an int).
10434   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10435              E->getType()->castAs<VectorType>()->getNumElements() &&
10436          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10437              E->getType()->castAs<VectorType>()->getNumElements() &&
10438          "All operands must be the same size.");
10439 
10440   APValue LHSValue;
10441   APValue RHSValue;
10442   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10443   if (!LHSOK && !Info.noteFailure())
10444     return false;
10445   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10446     return false;
10447 
10448   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10449     return false;
10450 
10451   return Success(LHSValue, E);
10452 }
10453 
10454 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10455                                                          QualType ResultTy,
10456                                                          UnaryOperatorKind Op,
10457                                                          APValue Elt) {
10458   switch (Op) {
10459   case UO_Plus:
10460     // Nothing to do here.
10461     return Elt;
10462   case UO_Minus:
10463     if (Elt.getKind() == APValue::Int) {
10464       Elt.getInt().negate();
10465     } else {
10466       assert(Elt.getKind() == APValue::Float &&
10467              "Vector can only be int or float type");
10468       Elt.getFloat().changeSign();
10469     }
10470     return Elt;
10471   case UO_Not:
10472     // This is only valid for integral types anyway, so we don't have to handle
10473     // float here.
10474     assert(Elt.getKind() == APValue::Int &&
10475            "Vector operator ~ can only be int");
10476     Elt.getInt().flipAllBits();
10477     return Elt;
10478   case UO_LNot: {
10479     if (Elt.getKind() == APValue::Int) {
10480       Elt.getInt() = !Elt.getInt();
10481       // operator ! on vectors returns -1 for 'truth', so negate it.
10482       Elt.getInt().negate();
10483       return Elt;
10484     }
10485     assert(Elt.getKind() == APValue::Float &&
10486            "Vector can only be int or float type");
10487     // Float types result in an int of the same size, but -1 for true, or 0 for
10488     // false.
10489     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10490                      ResultTy->isUnsignedIntegerType()};
10491     if (Elt.getFloat().isZero())
10492       EltResult.setAllBits();
10493     else
10494       EltResult.clearAllBits();
10495 
10496     return APValue{EltResult};
10497   }
10498   default:
10499     // FIXME: Implement the rest of the unary operators.
10500     return llvm::None;
10501   }
10502 }
10503 
10504 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10505   Expr *SubExpr = E->getSubExpr();
10506   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10507   // This result element type differs in the case of negating a floating point
10508   // vector, since the result type is the a vector of the equivilant sized
10509   // integer.
10510   const QualType ResultEltTy = VD->getElementType();
10511   UnaryOperatorKind Op = E->getOpcode();
10512 
10513   APValue SubExprValue;
10514   if (!Evaluate(SubExprValue, Info, SubExpr))
10515     return false;
10516 
10517   // FIXME: This vector evaluator someday needs to be changed to be LValue
10518   // aware/keep LValue information around, rather than dealing with just vector
10519   // types directly. Until then, we cannot handle cases where the operand to
10520   // these unary operators is an LValue. The only case I've been able to see
10521   // cause this is operator++ assigning to a member expression (only valid in
10522   // altivec compilations) in C mode, so this shouldn't limit us too much.
10523   if (SubExprValue.isLValue())
10524     return false;
10525 
10526   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10527          "Vector length doesn't match type?");
10528 
10529   SmallVector<APValue, 4> ResultElements;
10530   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10531     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10532         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10533     if (!Elt)
10534       return false;
10535     ResultElements.push_back(*Elt);
10536   }
10537   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10538 }
10539 
10540 //===----------------------------------------------------------------------===//
10541 // Array Evaluation
10542 //===----------------------------------------------------------------------===//
10543 
10544 namespace {
10545   class ArrayExprEvaluator
10546   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10547     const LValue &This;
10548     APValue &Result;
10549   public:
10550 
10551     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10552       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10553 
10554     bool Success(const APValue &V, const Expr *E) {
10555       assert(V.isArray() && "expected array");
10556       Result = V;
10557       return true;
10558     }
10559 
10560     bool ZeroInitialization(const Expr *E) {
10561       const ConstantArrayType *CAT =
10562           Info.Ctx.getAsConstantArrayType(E->getType());
10563       if (!CAT) {
10564         if (E->getType()->isIncompleteArrayType()) {
10565           // We can be asked to zero-initialize a flexible array member; this
10566           // is represented as an ImplicitValueInitExpr of incomplete array
10567           // type. In this case, the array has zero elements.
10568           Result = APValue(APValue::UninitArray(), 0, 0);
10569           return true;
10570         }
10571         // FIXME: We could handle VLAs here.
10572         return Error(E);
10573       }
10574 
10575       Result = APValue(APValue::UninitArray(), 0,
10576                        CAT->getSize().getZExtValue());
10577       if (!Result.hasArrayFiller())
10578         return true;
10579 
10580       // Zero-initialize all elements.
10581       LValue Subobject = This;
10582       Subobject.addArray(Info, E, CAT);
10583       ImplicitValueInitExpr VIE(CAT->getElementType());
10584       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10585     }
10586 
10587     bool VisitCallExpr(const CallExpr *E) {
10588       return handleCallExpr(E, Result, &This);
10589     }
10590     bool VisitInitListExpr(const InitListExpr *E,
10591                            QualType AllocType = QualType());
10592     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10593     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10594     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10595                                const LValue &Subobject,
10596                                APValue *Value, QualType Type);
10597     bool VisitStringLiteral(const StringLiteral *E,
10598                             QualType AllocType = QualType()) {
10599       expandStringLiteral(Info, E, Result, AllocType);
10600       return true;
10601     }
10602   };
10603 } // end anonymous namespace
10604 
10605 static bool EvaluateArray(const Expr *E, const LValue &This,
10606                           APValue &Result, EvalInfo &Info) {
10607   assert(!E->isValueDependent());
10608   assert(E->isPRValue() && E->getType()->isArrayType() &&
10609          "not an array prvalue");
10610   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10611 }
10612 
10613 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10614                                      APValue &Result, const InitListExpr *ILE,
10615                                      QualType AllocType) {
10616   assert(!ILE->isValueDependent());
10617   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10618          "not an array prvalue");
10619   return ArrayExprEvaluator(Info, This, Result)
10620       .VisitInitListExpr(ILE, AllocType);
10621 }
10622 
10623 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10624                                           APValue &Result,
10625                                           const CXXConstructExpr *CCE,
10626                                           QualType AllocType) {
10627   assert(!CCE->isValueDependent());
10628   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10629          "not an array prvalue");
10630   return ArrayExprEvaluator(Info, This, Result)
10631       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10632 }
10633 
10634 // Return true iff the given array filler may depend on the element index.
10635 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10636   // For now, just allow non-class value-initialization and initialization
10637   // lists comprised of them.
10638   if (isa<ImplicitValueInitExpr>(FillerExpr))
10639     return false;
10640   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10641     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10642       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10643         return true;
10644     }
10645     return false;
10646   }
10647   return true;
10648 }
10649 
10650 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10651                                            QualType AllocType) {
10652   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10653       AllocType.isNull() ? E->getType() : AllocType);
10654   if (!CAT)
10655     return Error(E);
10656 
10657   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10658   // an appropriately-typed string literal enclosed in braces.
10659   if (E->isStringLiteralInit()) {
10660     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10661     // FIXME: Support ObjCEncodeExpr here once we support it in
10662     // ArrayExprEvaluator generally.
10663     if (!SL)
10664       return Error(E);
10665     return VisitStringLiteral(SL, AllocType);
10666   }
10667   // Any other transparent list init will need proper handling of the
10668   // AllocType; we can't just recurse to the inner initializer.
10669   assert(!E->isTransparent() &&
10670          "transparent array list initialization is not string literal init?");
10671 
10672   bool Success = true;
10673 
10674   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10675          "zero-initialized array shouldn't have any initialized elts");
10676   APValue Filler;
10677   if (Result.isArray() && Result.hasArrayFiller())
10678     Filler = Result.getArrayFiller();
10679 
10680   unsigned NumEltsToInit = E->getNumInits();
10681   unsigned NumElts = CAT->getSize().getZExtValue();
10682   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10683 
10684   // If the initializer might depend on the array index, run it for each
10685   // array element.
10686   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10687     NumEltsToInit = NumElts;
10688 
10689   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10690                           << NumEltsToInit << ".\n");
10691 
10692   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10693 
10694   // If the array was previously zero-initialized, preserve the
10695   // zero-initialized values.
10696   if (Filler.hasValue()) {
10697     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10698       Result.getArrayInitializedElt(I) = Filler;
10699     if (Result.hasArrayFiller())
10700       Result.getArrayFiller() = Filler;
10701   }
10702 
10703   LValue Subobject = This;
10704   Subobject.addArray(Info, E, CAT);
10705   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10706     const Expr *Init =
10707         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10708     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10709                          Info, Subobject, Init) ||
10710         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10711                                      CAT->getElementType(), 1)) {
10712       if (!Info.noteFailure())
10713         return false;
10714       Success = false;
10715     }
10716   }
10717 
10718   if (!Result.hasArrayFiller())
10719     return Success;
10720 
10721   // If we get here, we have a trivial filler, which we can just evaluate
10722   // once and splat over the rest of the array elements.
10723   assert(FillerExpr && "no array filler for incomplete init list");
10724   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10725                          FillerExpr) && Success;
10726 }
10727 
10728 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10729   LValue CommonLV;
10730   if (E->getCommonExpr() &&
10731       !Evaluate(Info.CurrentCall->createTemporary(
10732                     E->getCommonExpr(),
10733                     getStorageType(Info.Ctx, E->getCommonExpr()),
10734                     ScopeKind::FullExpression, CommonLV),
10735                 Info, E->getCommonExpr()->getSourceExpr()))
10736     return false;
10737 
10738   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10739 
10740   uint64_t Elements = CAT->getSize().getZExtValue();
10741   Result = APValue(APValue::UninitArray(), Elements, Elements);
10742 
10743   LValue Subobject = This;
10744   Subobject.addArray(Info, E, CAT);
10745 
10746   bool Success = true;
10747   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10748     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10749                          Info, Subobject, E->getSubExpr()) ||
10750         !HandleLValueArrayAdjustment(Info, E, Subobject,
10751                                      CAT->getElementType(), 1)) {
10752       if (!Info.noteFailure())
10753         return false;
10754       Success = false;
10755     }
10756   }
10757 
10758   return Success;
10759 }
10760 
10761 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10762   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10763 }
10764 
10765 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10766                                                const LValue &Subobject,
10767                                                APValue *Value,
10768                                                QualType Type) {
10769   bool HadZeroInit = Value->hasValue();
10770 
10771   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10772     unsigned FinalSize = CAT->getSize().getZExtValue();
10773 
10774     // Preserve the array filler if we had prior zero-initialization.
10775     APValue Filler =
10776       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10777                                              : APValue();
10778 
10779     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10780     if (FinalSize == 0)
10781       return true;
10782 
10783     LValue ArrayElt = Subobject;
10784     ArrayElt.addArray(Info, E, CAT);
10785     // We do the whole initialization in two passes, first for just one element,
10786     // then for the whole array. It's possible we may find out we can't do const
10787     // init in the first pass, in which case we avoid allocating a potentially
10788     // large array. We don't do more passes because expanding array requires
10789     // copying the data, which is wasteful.
10790     for (const unsigned N : {1u, FinalSize}) {
10791       unsigned OldElts = Value->getArrayInitializedElts();
10792       if (OldElts == N)
10793         break;
10794 
10795       // Expand the array to appropriate size.
10796       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10797       for (unsigned I = 0; I < OldElts; ++I)
10798         NewValue.getArrayInitializedElt(I).swap(
10799             Value->getArrayInitializedElt(I));
10800       Value->swap(NewValue);
10801 
10802       if (HadZeroInit)
10803         for (unsigned I = OldElts; I < N; ++I)
10804           Value->getArrayInitializedElt(I) = Filler;
10805 
10806       // Initialize the elements.
10807       for (unsigned I = OldElts; I < N; ++I) {
10808         if (!VisitCXXConstructExpr(E, ArrayElt,
10809                                    &Value->getArrayInitializedElt(I),
10810                                    CAT->getElementType()) ||
10811             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10812                                          CAT->getElementType(), 1))
10813           return false;
10814         // When checking for const initilization any diagnostic is considered
10815         // an error.
10816         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10817             !Info.keepEvaluatingAfterFailure())
10818           return false;
10819       }
10820     }
10821 
10822     return true;
10823   }
10824 
10825   if (!Type->isRecordType())
10826     return Error(E);
10827 
10828   return RecordExprEvaluator(Info, Subobject, *Value)
10829              .VisitCXXConstructExpr(E, Type);
10830 }
10831 
10832 //===----------------------------------------------------------------------===//
10833 // Integer Evaluation
10834 //
10835 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10836 // types and back in constant folding. Integer values are thus represented
10837 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10838 //===----------------------------------------------------------------------===//
10839 
10840 namespace {
10841 class IntExprEvaluator
10842         : public ExprEvaluatorBase<IntExprEvaluator> {
10843   APValue &Result;
10844 public:
10845   IntExprEvaluator(EvalInfo &info, APValue &result)
10846       : ExprEvaluatorBaseTy(info), Result(result) {}
10847 
10848   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10849     assert(E->getType()->isIntegralOrEnumerationType() &&
10850            "Invalid evaluation result.");
10851     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10852            "Invalid evaluation result.");
10853     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10854            "Invalid evaluation result.");
10855     Result = APValue(SI);
10856     return true;
10857   }
10858   bool Success(const llvm::APSInt &SI, const Expr *E) {
10859     return Success(SI, E, Result);
10860   }
10861 
10862   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10863     assert(E->getType()->isIntegralOrEnumerationType() &&
10864            "Invalid evaluation result.");
10865     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10866            "Invalid evaluation result.");
10867     Result = APValue(APSInt(I));
10868     Result.getInt().setIsUnsigned(
10869                             E->getType()->isUnsignedIntegerOrEnumerationType());
10870     return true;
10871   }
10872   bool Success(const llvm::APInt &I, const Expr *E) {
10873     return Success(I, E, Result);
10874   }
10875 
10876   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10877     assert(E->getType()->isIntegralOrEnumerationType() &&
10878            "Invalid evaluation result.");
10879     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10880     return true;
10881   }
10882   bool Success(uint64_t Value, const Expr *E) {
10883     return Success(Value, E, Result);
10884   }
10885 
10886   bool Success(CharUnits Size, const Expr *E) {
10887     return Success(Size.getQuantity(), E);
10888   }
10889 
10890   bool Success(const APValue &V, const Expr *E) {
10891     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10892       Result = V;
10893       return true;
10894     }
10895     return Success(V.getInt(), E);
10896   }
10897 
10898   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10899 
10900   //===--------------------------------------------------------------------===//
10901   //                            Visitor Methods
10902   //===--------------------------------------------------------------------===//
10903 
10904   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10905     return Success(E->getValue(), E);
10906   }
10907   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10908     return Success(E->getValue(), E);
10909   }
10910 
10911   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10912   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10913     if (CheckReferencedDecl(E, E->getDecl()))
10914       return true;
10915 
10916     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10917   }
10918   bool VisitMemberExpr(const MemberExpr *E) {
10919     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10920       VisitIgnoredBaseExpression(E->getBase());
10921       return true;
10922     }
10923 
10924     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10925   }
10926 
10927   bool VisitCallExpr(const CallExpr *E);
10928   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10929   bool VisitBinaryOperator(const BinaryOperator *E);
10930   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10931   bool VisitUnaryOperator(const UnaryOperator *E);
10932 
10933   bool VisitCastExpr(const CastExpr* E);
10934   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10935 
10936   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10937     return Success(E->getValue(), E);
10938   }
10939 
10940   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10941     return Success(E->getValue(), E);
10942   }
10943 
10944   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10945     if (Info.ArrayInitIndex == uint64_t(-1)) {
10946       // We were asked to evaluate this subexpression independent of the
10947       // enclosing ArrayInitLoopExpr. We can't do that.
10948       Info.FFDiag(E);
10949       return false;
10950     }
10951     return Success(Info.ArrayInitIndex, E);
10952   }
10953 
10954   // Note, GNU defines __null as an integer, not a pointer.
10955   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10956     return ZeroInitialization(E);
10957   }
10958 
10959   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10960     return Success(E->getValue(), E);
10961   }
10962 
10963   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10964     return Success(E->getValue(), E);
10965   }
10966 
10967   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10968     return Success(E->getValue(), E);
10969   }
10970 
10971   bool VisitUnaryReal(const UnaryOperator *E);
10972   bool VisitUnaryImag(const UnaryOperator *E);
10973 
10974   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10975   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10976   bool VisitSourceLocExpr(const SourceLocExpr *E);
10977   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10978   bool VisitRequiresExpr(const RequiresExpr *E);
10979   // FIXME: Missing: array subscript of vector, member of vector
10980 };
10981 
10982 class FixedPointExprEvaluator
10983     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10984   APValue &Result;
10985 
10986  public:
10987   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10988       : ExprEvaluatorBaseTy(info), Result(result) {}
10989 
10990   bool Success(const llvm::APInt &I, const Expr *E) {
10991     return Success(
10992         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10993   }
10994 
10995   bool Success(uint64_t Value, const Expr *E) {
10996     return Success(
10997         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10998   }
10999 
11000   bool Success(const APValue &V, const Expr *E) {
11001     return Success(V.getFixedPoint(), E);
11002   }
11003 
11004   bool Success(const APFixedPoint &V, const Expr *E) {
11005     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11006     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11007            "Invalid evaluation result.");
11008     Result = APValue(V);
11009     return true;
11010   }
11011 
11012   //===--------------------------------------------------------------------===//
11013   //                            Visitor Methods
11014   //===--------------------------------------------------------------------===//
11015 
11016   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11017     return Success(E->getValue(), E);
11018   }
11019 
11020   bool VisitCastExpr(const CastExpr *E);
11021   bool VisitUnaryOperator(const UnaryOperator *E);
11022   bool VisitBinaryOperator(const BinaryOperator *E);
11023 };
11024 } // end anonymous namespace
11025 
11026 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11027 /// produce either the integer value or a pointer.
11028 ///
11029 /// GCC has a heinous extension which folds casts between pointer types and
11030 /// pointer-sized integral types. We support this by allowing the evaluation of
11031 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11032 /// Some simple arithmetic on such values is supported (they are treated much
11033 /// like char*).
11034 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11035                                     EvalInfo &Info) {
11036   assert(!E->isValueDependent());
11037   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11038   return IntExprEvaluator(Info, Result).Visit(E);
11039 }
11040 
11041 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11042   assert(!E->isValueDependent());
11043   APValue Val;
11044   if (!EvaluateIntegerOrLValue(E, Val, Info))
11045     return false;
11046   if (!Val.isInt()) {
11047     // FIXME: It would be better to produce the diagnostic for casting
11048     //        a pointer to an integer.
11049     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11050     return false;
11051   }
11052   Result = Val.getInt();
11053   return true;
11054 }
11055 
11056 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11057   APValue Evaluated = E->EvaluateInContext(
11058       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11059   return Success(Evaluated, E);
11060 }
11061 
11062 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11063                                EvalInfo &Info) {
11064   assert(!E->isValueDependent());
11065   if (E->getType()->isFixedPointType()) {
11066     APValue Val;
11067     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11068       return false;
11069     if (!Val.isFixedPoint())
11070       return false;
11071 
11072     Result = Val.getFixedPoint();
11073     return true;
11074   }
11075   return false;
11076 }
11077 
11078 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11079                                         EvalInfo &Info) {
11080   assert(!E->isValueDependent());
11081   if (E->getType()->isIntegerType()) {
11082     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11083     APSInt Val;
11084     if (!EvaluateInteger(E, Val, Info))
11085       return false;
11086     Result = APFixedPoint(Val, FXSema);
11087     return true;
11088   } else if (E->getType()->isFixedPointType()) {
11089     return EvaluateFixedPoint(E, Result, Info);
11090   }
11091   return false;
11092 }
11093 
11094 /// Check whether the given declaration can be directly converted to an integral
11095 /// rvalue. If not, no diagnostic is produced; there are other things we can
11096 /// try.
11097 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11098   // Enums are integer constant exprs.
11099   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11100     // Check for signedness/width mismatches between E type and ECD value.
11101     bool SameSign = (ECD->getInitVal().isSigned()
11102                      == E->getType()->isSignedIntegerOrEnumerationType());
11103     bool SameWidth = (ECD->getInitVal().getBitWidth()
11104                       == Info.Ctx.getIntWidth(E->getType()));
11105     if (SameSign && SameWidth)
11106       return Success(ECD->getInitVal(), E);
11107     else {
11108       // Get rid of mismatch (otherwise Success assertions will fail)
11109       // by computing a new value matching the type of E.
11110       llvm::APSInt Val = ECD->getInitVal();
11111       if (!SameSign)
11112         Val.setIsSigned(!ECD->getInitVal().isSigned());
11113       if (!SameWidth)
11114         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11115       return Success(Val, E);
11116     }
11117   }
11118   return false;
11119 }
11120 
11121 /// Values returned by __builtin_classify_type, chosen to match the values
11122 /// produced by GCC's builtin.
11123 enum class GCCTypeClass {
11124   None = -1,
11125   Void = 0,
11126   Integer = 1,
11127   // GCC reserves 2 for character types, but instead classifies them as
11128   // integers.
11129   Enum = 3,
11130   Bool = 4,
11131   Pointer = 5,
11132   // GCC reserves 6 for references, but appears to never use it (because
11133   // expressions never have reference type, presumably).
11134   PointerToDataMember = 7,
11135   RealFloat = 8,
11136   Complex = 9,
11137   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11138   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11139   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11140   // uses 12 for that purpose, same as for a class or struct. Maybe it
11141   // internally implements a pointer to member as a struct?  Who knows.
11142   PointerToMemberFunction = 12, // Not a bug, see above.
11143   ClassOrStruct = 12,
11144   Union = 13,
11145   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11146   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11147   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11148   // literals.
11149 };
11150 
11151 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11152 /// as GCC.
11153 static GCCTypeClass
11154 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11155   assert(!T->isDependentType() && "unexpected dependent type");
11156 
11157   QualType CanTy = T.getCanonicalType();
11158   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11159 
11160   switch (CanTy->getTypeClass()) {
11161 #define TYPE(ID, BASE)
11162 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11163 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11164 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11165 #include "clang/AST/TypeNodes.inc"
11166   case Type::Auto:
11167   case Type::DeducedTemplateSpecialization:
11168       llvm_unreachable("unexpected non-canonical or dependent type");
11169 
11170   case Type::Builtin:
11171     switch (BT->getKind()) {
11172 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11173 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11174     case BuiltinType::ID: return GCCTypeClass::Integer;
11175 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11176     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11177 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11178     case BuiltinType::ID: break;
11179 #include "clang/AST/BuiltinTypes.def"
11180     case BuiltinType::Void:
11181       return GCCTypeClass::Void;
11182 
11183     case BuiltinType::Bool:
11184       return GCCTypeClass::Bool;
11185 
11186     case BuiltinType::Char_U:
11187     case BuiltinType::UChar:
11188     case BuiltinType::WChar_U:
11189     case BuiltinType::Char8:
11190     case BuiltinType::Char16:
11191     case BuiltinType::Char32:
11192     case BuiltinType::UShort:
11193     case BuiltinType::UInt:
11194     case BuiltinType::ULong:
11195     case BuiltinType::ULongLong:
11196     case BuiltinType::UInt128:
11197       return GCCTypeClass::Integer;
11198 
11199     case BuiltinType::UShortAccum:
11200     case BuiltinType::UAccum:
11201     case BuiltinType::ULongAccum:
11202     case BuiltinType::UShortFract:
11203     case BuiltinType::UFract:
11204     case BuiltinType::ULongFract:
11205     case BuiltinType::SatUShortAccum:
11206     case BuiltinType::SatUAccum:
11207     case BuiltinType::SatULongAccum:
11208     case BuiltinType::SatUShortFract:
11209     case BuiltinType::SatUFract:
11210     case BuiltinType::SatULongFract:
11211       return GCCTypeClass::None;
11212 
11213     case BuiltinType::NullPtr:
11214 
11215     case BuiltinType::ObjCId:
11216     case BuiltinType::ObjCClass:
11217     case BuiltinType::ObjCSel:
11218 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11219     case BuiltinType::Id:
11220 #include "clang/Basic/OpenCLImageTypes.def"
11221 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11222     case BuiltinType::Id:
11223 #include "clang/Basic/OpenCLExtensionTypes.def"
11224     case BuiltinType::OCLSampler:
11225     case BuiltinType::OCLEvent:
11226     case BuiltinType::OCLClkEvent:
11227     case BuiltinType::OCLQueue:
11228     case BuiltinType::OCLReserveID:
11229 #define SVE_TYPE(Name, Id, SingletonId) \
11230     case BuiltinType::Id:
11231 #include "clang/Basic/AArch64SVEACLETypes.def"
11232 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11233     case BuiltinType::Id:
11234 #include "clang/Basic/PPCTypes.def"
11235 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11236 #include "clang/Basic/RISCVVTypes.def"
11237       return GCCTypeClass::None;
11238 
11239     case BuiltinType::Dependent:
11240       llvm_unreachable("unexpected dependent type");
11241     };
11242     llvm_unreachable("unexpected placeholder type");
11243 
11244   case Type::Enum:
11245     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11246 
11247   case Type::Pointer:
11248   case Type::ConstantArray:
11249   case Type::VariableArray:
11250   case Type::IncompleteArray:
11251   case Type::FunctionNoProto:
11252   case Type::FunctionProto:
11253     return GCCTypeClass::Pointer;
11254 
11255   case Type::MemberPointer:
11256     return CanTy->isMemberDataPointerType()
11257                ? GCCTypeClass::PointerToDataMember
11258                : GCCTypeClass::PointerToMemberFunction;
11259 
11260   case Type::Complex:
11261     return GCCTypeClass::Complex;
11262 
11263   case Type::Record:
11264     return CanTy->isUnionType() ? GCCTypeClass::Union
11265                                 : GCCTypeClass::ClassOrStruct;
11266 
11267   case Type::Atomic:
11268     // GCC classifies _Atomic T the same as T.
11269     return EvaluateBuiltinClassifyType(
11270         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11271 
11272   case Type::BlockPointer:
11273   case Type::Vector:
11274   case Type::ExtVector:
11275   case Type::ConstantMatrix:
11276   case Type::ObjCObject:
11277   case Type::ObjCInterface:
11278   case Type::ObjCObjectPointer:
11279   case Type::Pipe:
11280   case Type::BitInt:
11281     // GCC classifies vectors as None. We follow its lead and classify all
11282     // other types that don't fit into the regular classification the same way.
11283     return GCCTypeClass::None;
11284 
11285   case Type::LValueReference:
11286   case Type::RValueReference:
11287     llvm_unreachable("invalid type for expression");
11288   }
11289 
11290   llvm_unreachable("unexpected type class");
11291 }
11292 
11293 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11294 /// as GCC.
11295 static GCCTypeClass
11296 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11297   // If no argument was supplied, default to None. This isn't
11298   // ideal, however it is what gcc does.
11299   if (E->getNumArgs() == 0)
11300     return GCCTypeClass::None;
11301 
11302   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11303   // being an ICE, but still folds it to a constant using the type of the first
11304   // argument.
11305   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11306 }
11307 
11308 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11309 /// __builtin_constant_p when applied to the given pointer.
11310 ///
11311 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11312 /// or it points to the first character of a string literal.
11313 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11314   APValue::LValueBase Base = LV.getLValueBase();
11315   if (Base.isNull()) {
11316     // A null base is acceptable.
11317     return true;
11318   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11319     if (!isa<StringLiteral>(E))
11320       return false;
11321     return LV.getLValueOffset().isZero();
11322   } else if (Base.is<TypeInfoLValue>()) {
11323     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11324     // evaluate to true.
11325     return true;
11326   } else {
11327     // Any other base is not constant enough for GCC.
11328     return false;
11329   }
11330 }
11331 
11332 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11333 /// GCC as we can manage.
11334 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11335   // This evaluation is not permitted to have side-effects, so evaluate it in
11336   // a speculative evaluation context.
11337   SpeculativeEvaluationRAII SpeculativeEval(Info);
11338 
11339   // Constant-folding is always enabled for the operand of __builtin_constant_p
11340   // (even when the enclosing evaluation context otherwise requires a strict
11341   // language-specific constant expression).
11342   FoldConstant Fold(Info, true);
11343 
11344   QualType ArgType = Arg->getType();
11345 
11346   // __builtin_constant_p always has one operand. The rules which gcc follows
11347   // are not precisely documented, but are as follows:
11348   //
11349   //  - If the operand is of integral, floating, complex or enumeration type,
11350   //    and can be folded to a known value of that type, it returns 1.
11351   //  - If the operand can be folded to a pointer to the first character
11352   //    of a string literal (or such a pointer cast to an integral type)
11353   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11354   //
11355   // Otherwise, it returns 0.
11356   //
11357   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11358   // its support for this did not work prior to GCC 9 and is not yet well
11359   // understood.
11360   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11361       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11362       ArgType->isNullPtrType()) {
11363     APValue V;
11364     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11365       Fold.keepDiagnostics();
11366       return false;
11367     }
11368 
11369     // For a pointer (possibly cast to integer), there are special rules.
11370     if (V.getKind() == APValue::LValue)
11371       return EvaluateBuiltinConstantPForLValue(V);
11372 
11373     // Otherwise, any constant value is good enough.
11374     return V.hasValue();
11375   }
11376 
11377   // Anything else isn't considered to be sufficiently constant.
11378   return false;
11379 }
11380 
11381 /// Retrieves the "underlying object type" of the given expression,
11382 /// as used by __builtin_object_size.
11383 static QualType getObjectType(APValue::LValueBase B) {
11384   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11385     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11386       return VD->getType();
11387   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11388     if (isa<CompoundLiteralExpr>(E))
11389       return E->getType();
11390   } else if (B.is<TypeInfoLValue>()) {
11391     return B.getTypeInfoType();
11392   } else if (B.is<DynamicAllocLValue>()) {
11393     return B.getDynamicAllocType();
11394   }
11395 
11396   return QualType();
11397 }
11398 
11399 /// A more selective version of E->IgnoreParenCasts for
11400 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11401 /// to change the type of E.
11402 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11403 ///
11404 /// Always returns an RValue with a pointer representation.
11405 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11406   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11407 
11408   auto *NoParens = E->IgnoreParens();
11409   auto *Cast = dyn_cast<CastExpr>(NoParens);
11410   if (Cast == nullptr)
11411     return NoParens;
11412 
11413   // We only conservatively allow a few kinds of casts, because this code is
11414   // inherently a simple solution that seeks to support the common case.
11415   auto CastKind = Cast->getCastKind();
11416   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11417       CastKind != CK_AddressSpaceConversion)
11418     return NoParens;
11419 
11420   auto *SubExpr = Cast->getSubExpr();
11421   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11422     return NoParens;
11423   return ignorePointerCastsAndParens(SubExpr);
11424 }
11425 
11426 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11427 /// record layout. e.g.
11428 ///   struct { struct { int a, b; } fst, snd; } obj;
11429 ///   obj.fst   // no
11430 ///   obj.snd   // yes
11431 ///   obj.fst.a // no
11432 ///   obj.fst.b // no
11433 ///   obj.snd.a // no
11434 ///   obj.snd.b // yes
11435 ///
11436 /// Please note: this function is specialized for how __builtin_object_size
11437 /// views "objects".
11438 ///
11439 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11440 /// correct result, it will always return true.
11441 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11442   assert(!LVal.Designator.Invalid);
11443 
11444   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11445     const RecordDecl *Parent = FD->getParent();
11446     Invalid = Parent->isInvalidDecl();
11447     if (Invalid || Parent->isUnion())
11448       return true;
11449     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11450     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11451   };
11452 
11453   auto &Base = LVal.getLValueBase();
11454   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11455     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11456       bool Invalid;
11457       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11458         return Invalid;
11459     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11460       for (auto *FD : IFD->chain()) {
11461         bool Invalid;
11462         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11463           return Invalid;
11464       }
11465     }
11466   }
11467 
11468   unsigned I = 0;
11469   QualType BaseType = getType(Base);
11470   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11471     // If we don't know the array bound, conservatively assume we're looking at
11472     // the final array element.
11473     ++I;
11474     if (BaseType->isIncompleteArrayType())
11475       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11476     else
11477       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11478   }
11479 
11480   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11481     const auto &Entry = LVal.Designator.Entries[I];
11482     if (BaseType->isArrayType()) {
11483       // Because __builtin_object_size treats arrays as objects, we can ignore
11484       // the index iff this is the last array in the Designator.
11485       if (I + 1 == E)
11486         return true;
11487       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11488       uint64_t Index = Entry.getAsArrayIndex();
11489       if (Index + 1 != CAT->getSize())
11490         return false;
11491       BaseType = CAT->getElementType();
11492     } else if (BaseType->isAnyComplexType()) {
11493       const auto *CT = BaseType->castAs<ComplexType>();
11494       uint64_t Index = Entry.getAsArrayIndex();
11495       if (Index != 1)
11496         return false;
11497       BaseType = CT->getElementType();
11498     } else if (auto *FD = getAsField(Entry)) {
11499       bool Invalid;
11500       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11501         return Invalid;
11502       BaseType = FD->getType();
11503     } else {
11504       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11505       return false;
11506     }
11507   }
11508   return true;
11509 }
11510 
11511 /// Tests to see if the LValue has a user-specified designator (that isn't
11512 /// necessarily valid). Note that this always returns 'true' if the LValue has
11513 /// an unsized array as its first designator entry, because there's currently no
11514 /// way to tell if the user typed *foo or foo[0].
11515 static bool refersToCompleteObject(const LValue &LVal) {
11516   if (LVal.Designator.Invalid)
11517     return false;
11518 
11519   if (!LVal.Designator.Entries.empty())
11520     return LVal.Designator.isMostDerivedAnUnsizedArray();
11521 
11522   if (!LVal.InvalidBase)
11523     return true;
11524 
11525   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11526   // the LValueBase.
11527   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11528   return !E || !isa<MemberExpr>(E);
11529 }
11530 
11531 /// Attempts to detect a user writing into a piece of memory that's impossible
11532 /// to figure out the size of by just using types.
11533 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11534   const SubobjectDesignator &Designator = LVal.Designator;
11535   // Notes:
11536   // - Users can only write off of the end when we have an invalid base. Invalid
11537   //   bases imply we don't know where the memory came from.
11538   // - We used to be a bit more aggressive here; we'd only be conservative if
11539   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11540   //   broke some common standard library extensions (PR30346), but was
11541   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11542   //   with some sort of list. OTOH, it seems that GCC is always
11543   //   conservative with the last element in structs (if it's an array), so our
11544   //   current behavior is more compatible than an explicit list approach would
11545   //   be.
11546   return LVal.InvalidBase &&
11547          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11548          Designator.MostDerivedIsArrayElement &&
11549          isDesignatorAtObjectEnd(Ctx, LVal);
11550 }
11551 
11552 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11553 /// Fails if the conversion would cause loss of precision.
11554 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11555                                             CharUnits &Result) {
11556   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11557   if (Int.ugt(CharUnitsMax))
11558     return false;
11559   Result = CharUnits::fromQuantity(Int.getZExtValue());
11560   return true;
11561 }
11562 
11563 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11564 /// determine how many bytes exist from the beginning of the object to either
11565 /// the end of the current subobject, or the end of the object itself, depending
11566 /// on what the LValue looks like + the value of Type.
11567 ///
11568 /// If this returns false, the value of Result is undefined.
11569 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11570                                unsigned Type, const LValue &LVal,
11571                                CharUnits &EndOffset) {
11572   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11573 
11574   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11575     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11576       return false;
11577     return HandleSizeof(Info, ExprLoc, Ty, Result);
11578   };
11579 
11580   // We want to evaluate the size of the entire object. This is a valid fallback
11581   // for when Type=1 and the designator is invalid, because we're asked for an
11582   // upper-bound.
11583   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11584     // Type=3 wants a lower bound, so we can't fall back to this.
11585     if (Type == 3 && !DetermineForCompleteObject)
11586       return false;
11587 
11588     llvm::APInt APEndOffset;
11589     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11590         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11591       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11592 
11593     if (LVal.InvalidBase)
11594       return false;
11595 
11596     QualType BaseTy = getObjectType(LVal.getLValueBase());
11597     return CheckedHandleSizeof(BaseTy, EndOffset);
11598   }
11599 
11600   // We want to evaluate the size of a subobject.
11601   const SubobjectDesignator &Designator = LVal.Designator;
11602 
11603   // The following is a moderately common idiom in C:
11604   //
11605   // struct Foo { int a; char c[1]; };
11606   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11607   // strcpy(&F->c[0], Bar);
11608   //
11609   // In order to not break too much legacy code, we need to support it.
11610   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11611     // If we can resolve this to an alloc_size call, we can hand that back,
11612     // because we know for certain how many bytes there are to write to.
11613     llvm::APInt APEndOffset;
11614     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11615         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11616       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11617 
11618     // If we cannot determine the size of the initial allocation, then we can't
11619     // given an accurate upper-bound. However, we are still able to give
11620     // conservative lower-bounds for Type=3.
11621     if (Type == 1)
11622       return false;
11623   }
11624 
11625   CharUnits BytesPerElem;
11626   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11627     return false;
11628 
11629   // According to the GCC documentation, we want the size of the subobject
11630   // denoted by the pointer. But that's not quite right -- what we actually
11631   // want is the size of the immediately-enclosing array, if there is one.
11632   int64_t ElemsRemaining;
11633   if (Designator.MostDerivedIsArrayElement &&
11634       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11635     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11636     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11637     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11638   } else {
11639     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11640   }
11641 
11642   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11643   return true;
11644 }
11645 
11646 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11647 /// returns true and stores the result in @p Size.
11648 ///
11649 /// If @p WasError is non-null, this will report whether the failure to evaluate
11650 /// is to be treated as an Error in IntExprEvaluator.
11651 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11652                                          EvalInfo &Info, uint64_t &Size) {
11653   // Determine the denoted object.
11654   LValue LVal;
11655   {
11656     // The operand of __builtin_object_size is never evaluated for side-effects.
11657     // If there are any, but we can determine the pointed-to object anyway, then
11658     // ignore the side-effects.
11659     SpeculativeEvaluationRAII SpeculativeEval(Info);
11660     IgnoreSideEffectsRAII Fold(Info);
11661 
11662     if (E->isGLValue()) {
11663       // It's possible for us to be given GLValues if we're called via
11664       // Expr::tryEvaluateObjectSize.
11665       APValue RVal;
11666       if (!EvaluateAsRValue(Info, E, RVal))
11667         return false;
11668       LVal.setFrom(Info.Ctx, RVal);
11669     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11670                                 /*InvalidBaseOK=*/true))
11671       return false;
11672   }
11673 
11674   // If we point to before the start of the object, there are no accessible
11675   // bytes.
11676   if (LVal.getLValueOffset().isNegative()) {
11677     Size = 0;
11678     return true;
11679   }
11680 
11681   CharUnits EndOffset;
11682   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11683     return false;
11684 
11685   // If we've fallen outside of the end offset, just pretend there's nothing to
11686   // write to/read from.
11687   if (EndOffset <= LVal.getLValueOffset())
11688     Size = 0;
11689   else
11690     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11691   return true;
11692 }
11693 
11694 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11695   if (unsigned BuiltinOp = E->getBuiltinCallee())
11696     return VisitBuiltinCallExpr(E, BuiltinOp);
11697 
11698   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11699 }
11700 
11701 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11702                                      APValue &Val, APSInt &Alignment) {
11703   QualType SrcTy = E->getArg(0)->getType();
11704   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11705     return false;
11706   // Even though we are evaluating integer expressions we could get a pointer
11707   // argument for the __builtin_is_aligned() case.
11708   if (SrcTy->isPointerType()) {
11709     LValue Ptr;
11710     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11711       return false;
11712     Ptr.moveInto(Val);
11713   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11714     Info.FFDiag(E->getArg(0));
11715     return false;
11716   } else {
11717     APSInt SrcInt;
11718     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11719       return false;
11720     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11721            "Bit widths must be the same");
11722     Val = APValue(SrcInt);
11723   }
11724   assert(Val.hasValue());
11725   return true;
11726 }
11727 
11728 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11729                                             unsigned BuiltinOp) {
11730   switch (BuiltinOp) {
11731   default:
11732     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11733 
11734   case Builtin::BI__builtin_dynamic_object_size:
11735   case Builtin::BI__builtin_object_size: {
11736     // The type was checked when we built the expression.
11737     unsigned Type =
11738         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11739     assert(Type <= 3 && "unexpected type");
11740 
11741     uint64_t Size;
11742     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11743       return Success(Size, E);
11744 
11745     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11746       return Success((Type & 2) ? 0 : -1, E);
11747 
11748     // Expression had no side effects, but we couldn't statically determine the
11749     // size of the referenced object.
11750     switch (Info.EvalMode) {
11751     case EvalInfo::EM_ConstantExpression:
11752     case EvalInfo::EM_ConstantFold:
11753     case EvalInfo::EM_IgnoreSideEffects:
11754       // Leave it to IR generation.
11755       return Error(E);
11756     case EvalInfo::EM_ConstantExpressionUnevaluated:
11757       // Reduce it to a constant now.
11758       return Success((Type & 2) ? 0 : -1, E);
11759     }
11760 
11761     llvm_unreachable("unexpected EvalMode");
11762   }
11763 
11764   case Builtin::BI__builtin_os_log_format_buffer_size: {
11765     analyze_os_log::OSLogBufferLayout Layout;
11766     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11767     return Success(Layout.size().getQuantity(), E);
11768   }
11769 
11770   case Builtin::BI__builtin_is_aligned: {
11771     APValue Src;
11772     APSInt Alignment;
11773     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11774       return false;
11775     if (Src.isLValue()) {
11776       // If we evaluated a pointer, check the minimum known alignment.
11777       LValue Ptr;
11778       Ptr.setFrom(Info.Ctx, Src);
11779       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11780       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11781       // We can return true if the known alignment at the computed offset is
11782       // greater than the requested alignment.
11783       assert(PtrAlign.isPowerOfTwo());
11784       assert(Alignment.isPowerOf2());
11785       if (PtrAlign.getQuantity() >= Alignment)
11786         return Success(1, E);
11787       // If the alignment is not known to be sufficient, some cases could still
11788       // be aligned at run time. However, if the requested alignment is less or
11789       // equal to the base alignment and the offset is not aligned, we know that
11790       // the run-time value can never be aligned.
11791       if (BaseAlignment.getQuantity() >= Alignment &&
11792           PtrAlign.getQuantity() < Alignment)
11793         return Success(0, E);
11794       // Otherwise we can't infer whether the value is sufficiently aligned.
11795       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11796       //  in cases where we can't fully evaluate the pointer.
11797       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11798           << Alignment;
11799       return false;
11800     }
11801     assert(Src.isInt());
11802     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11803   }
11804   case Builtin::BI__builtin_align_up: {
11805     APValue Src;
11806     APSInt Alignment;
11807     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11808       return false;
11809     if (!Src.isInt())
11810       return Error(E);
11811     APSInt AlignedVal =
11812         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11813                Src.getInt().isUnsigned());
11814     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11815     return Success(AlignedVal, E);
11816   }
11817   case Builtin::BI__builtin_align_down: {
11818     APValue Src;
11819     APSInt Alignment;
11820     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11821       return false;
11822     if (!Src.isInt())
11823       return Error(E);
11824     APSInt AlignedVal =
11825         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11826     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11827     return Success(AlignedVal, E);
11828   }
11829 
11830   case Builtin::BI__builtin_bitreverse8:
11831   case Builtin::BI__builtin_bitreverse16:
11832   case Builtin::BI__builtin_bitreverse32:
11833   case Builtin::BI__builtin_bitreverse64: {
11834     APSInt Val;
11835     if (!EvaluateInteger(E->getArg(0), Val, Info))
11836       return false;
11837 
11838     return Success(Val.reverseBits(), E);
11839   }
11840 
11841   case Builtin::BI__builtin_bswap16:
11842   case Builtin::BI__builtin_bswap32:
11843   case Builtin::BI__builtin_bswap64: {
11844     APSInt Val;
11845     if (!EvaluateInteger(E->getArg(0), Val, Info))
11846       return false;
11847 
11848     return Success(Val.byteSwap(), E);
11849   }
11850 
11851   case Builtin::BI__builtin_classify_type:
11852     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11853 
11854   case Builtin::BI__builtin_clrsb:
11855   case Builtin::BI__builtin_clrsbl:
11856   case Builtin::BI__builtin_clrsbll: {
11857     APSInt Val;
11858     if (!EvaluateInteger(E->getArg(0), Val, Info))
11859       return false;
11860 
11861     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11862   }
11863 
11864   case Builtin::BI__builtin_clz:
11865   case Builtin::BI__builtin_clzl:
11866   case Builtin::BI__builtin_clzll:
11867   case Builtin::BI__builtin_clzs: {
11868     APSInt Val;
11869     if (!EvaluateInteger(E->getArg(0), Val, Info))
11870       return false;
11871     if (!Val)
11872       return Error(E);
11873 
11874     return Success(Val.countLeadingZeros(), E);
11875   }
11876 
11877   case Builtin::BI__builtin_constant_p: {
11878     const Expr *Arg = E->getArg(0);
11879     if (EvaluateBuiltinConstantP(Info, Arg))
11880       return Success(true, E);
11881     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11882       // Outside a constant context, eagerly evaluate to false in the presence
11883       // of side-effects in order to avoid -Wunsequenced false-positives in
11884       // a branch on __builtin_constant_p(expr).
11885       return Success(false, E);
11886     }
11887     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11888     return false;
11889   }
11890 
11891   case Builtin::BI__builtin_is_constant_evaluated: {
11892     const auto *Callee = Info.CurrentCall->getCallee();
11893     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11894         (Info.CallStackDepth == 1 ||
11895          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11896           Callee->getIdentifier() &&
11897           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11898       // FIXME: Find a better way to avoid duplicated diagnostics.
11899       if (Info.EvalStatus.Diag)
11900         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11901                                                : Info.CurrentCall->CallLoc,
11902                     diag::warn_is_constant_evaluated_always_true_constexpr)
11903             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11904                                          : "std::is_constant_evaluated");
11905     }
11906 
11907     return Success(Info.InConstantContext, E);
11908   }
11909 
11910   case Builtin::BI__builtin_ctz:
11911   case Builtin::BI__builtin_ctzl:
11912   case Builtin::BI__builtin_ctzll:
11913   case Builtin::BI__builtin_ctzs: {
11914     APSInt Val;
11915     if (!EvaluateInteger(E->getArg(0), Val, Info))
11916       return false;
11917     if (!Val)
11918       return Error(E);
11919 
11920     return Success(Val.countTrailingZeros(), E);
11921   }
11922 
11923   case Builtin::BI__builtin_eh_return_data_regno: {
11924     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11925     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11926     return Success(Operand, E);
11927   }
11928 
11929   case Builtin::BI__builtin_expect:
11930   case Builtin::BI__builtin_expect_with_probability:
11931     return Visit(E->getArg(0));
11932 
11933   case Builtin::BI__builtin_ffs:
11934   case Builtin::BI__builtin_ffsl:
11935   case Builtin::BI__builtin_ffsll: {
11936     APSInt Val;
11937     if (!EvaluateInteger(E->getArg(0), Val, Info))
11938       return false;
11939 
11940     unsigned N = Val.countTrailingZeros();
11941     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11942   }
11943 
11944   case Builtin::BI__builtin_fpclassify: {
11945     APFloat Val(0.0);
11946     if (!EvaluateFloat(E->getArg(5), Val, Info))
11947       return false;
11948     unsigned Arg;
11949     switch (Val.getCategory()) {
11950     case APFloat::fcNaN: Arg = 0; break;
11951     case APFloat::fcInfinity: Arg = 1; break;
11952     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11953     case APFloat::fcZero: Arg = 4; break;
11954     }
11955     return Visit(E->getArg(Arg));
11956   }
11957 
11958   case Builtin::BI__builtin_isinf_sign: {
11959     APFloat Val(0.0);
11960     return EvaluateFloat(E->getArg(0), Val, Info) &&
11961            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11962   }
11963 
11964   case Builtin::BI__builtin_isinf: {
11965     APFloat Val(0.0);
11966     return EvaluateFloat(E->getArg(0), Val, Info) &&
11967            Success(Val.isInfinity() ? 1 : 0, E);
11968   }
11969 
11970   case Builtin::BI__builtin_isfinite: {
11971     APFloat Val(0.0);
11972     return EvaluateFloat(E->getArg(0), Val, Info) &&
11973            Success(Val.isFinite() ? 1 : 0, E);
11974   }
11975 
11976   case Builtin::BI__builtin_isnan: {
11977     APFloat Val(0.0);
11978     return EvaluateFloat(E->getArg(0), Val, Info) &&
11979            Success(Val.isNaN() ? 1 : 0, E);
11980   }
11981 
11982   case Builtin::BI__builtin_isnormal: {
11983     APFloat Val(0.0);
11984     return EvaluateFloat(E->getArg(0), Val, Info) &&
11985            Success(Val.isNormal() ? 1 : 0, E);
11986   }
11987 
11988   case Builtin::BI__builtin_parity:
11989   case Builtin::BI__builtin_parityl:
11990   case Builtin::BI__builtin_parityll: {
11991     APSInt Val;
11992     if (!EvaluateInteger(E->getArg(0), Val, Info))
11993       return false;
11994 
11995     return Success(Val.countPopulation() % 2, E);
11996   }
11997 
11998   case Builtin::BI__builtin_popcount:
11999   case Builtin::BI__builtin_popcountl:
12000   case Builtin::BI__builtin_popcountll: {
12001     APSInt Val;
12002     if (!EvaluateInteger(E->getArg(0), Val, Info))
12003       return false;
12004 
12005     return Success(Val.countPopulation(), E);
12006   }
12007 
12008   case Builtin::BI__builtin_rotateleft8:
12009   case Builtin::BI__builtin_rotateleft16:
12010   case Builtin::BI__builtin_rotateleft32:
12011   case Builtin::BI__builtin_rotateleft64:
12012   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12013   case Builtin::BI_rotl16:
12014   case Builtin::BI_rotl:
12015   case Builtin::BI_lrotl:
12016   case Builtin::BI_rotl64: {
12017     APSInt Val, Amt;
12018     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12019         !EvaluateInteger(E->getArg(1), Amt, Info))
12020       return false;
12021 
12022     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12023   }
12024 
12025   case Builtin::BI__builtin_rotateright8:
12026   case Builtin::BI__builtin_rotateright16:
12027   case Builtin::BI__builtin_rotateright32:
12028   case Builtin::BI__builtin_rotateright64:
12029   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12030   case Builtin::BI_rotr16:
12031   case Builtin::BI_rotr:
12032   case Builtin::BI_lrotr:
12033   case Builtin::BI_rotr64: {
12034     APSInt Val, Amt;
12035     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12036         !EvaluateInteger(E->getArg(1), Amt, Info))
12037       return false;
12038 
12039     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12040   }
12041 
12042   case Builtin::BIstrlen:
12043   case Builtin::BIwcslen:
12044     // A call to strlen is not a constant expression.
12045     if (Info.getLangOpts().CPlusPlus11)
12046       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12047         << /*isConstexpr*/0 << /*isConstructor*/0
12048         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12049     else
12050       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12051     LLVM_FALLTHROUGH;
12052   case Builtin::BI__builtin_strlen:
12053   case Builtin::BI__builtin_wcslen: {
12054     // As an extension, we support __builtin_strlen() as a constant expression,
12055     // and support folding strlen() to a constant.
12056     uint64_t StrLen;
12057     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12058       return Success(StrLen, E);
12059     return false;
12060   }
12061 
12062   case Builtin::BIstrcmp:
12063   case Builtin::BIwcscmp:
12064   case Builtin::BIstrncmp:
12065   case Builtin::BIwcsncmp:
12066   case Builtin::BImemcmp:
12067   case Builtin::BIbcmp:
12068   case Builtin::BIwmemcmp:
12069     // A call to strlen is not a constant expression.
12070     if (Info.getLangOpts().CPlusPlus11)
12071       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12072         << /*isConstexpr*/0 << /*isConstructor*/0
12073         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12074     else
12075       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12076     LLVM_FALLTHROUGH;
12077   case Builtin::BI__builtin_strcmp:
12078   case Builtin::BI__builtin_wcscmp:
12079   case Builtin::BI__builtin_strncmp:
12080   case Builtin::BI__builtin_wcsncmp:
12081   case Builtin::BI__builtin_memcmp:
12082   case Builtin::BI__builtin_bcmp:
12083   case Builtin::BI__builtin_wmemcmp: {
12084     LValue String1, String2;
12085     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12086         !EvaluatePointer(E->getArg(1), String2, Info))
12087       return false;
12088 
12089     uint64_t MaxLength = uint64_t(-1);
12090     if (BuiltinOp != Builtin::BIstrcmp &&
12091         BuiltinOp != Builtin::BIwcscmp &&
12092         BuiltinOp != Builtin::BI__builtin_strcmp &&
12093         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12094       APSInt N;
12095       if (!EvaluateInteger(E->getArg(2), N, Info))
12096         return false;
12097       MaxLength = N.getExtValue();
12098     }
12099 
12100     // Empty substrings compare equal by definition.
12101     if (MaxLength == 0u)
12102       return Success(0, E);
12103 
12104     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12105         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12106         String1.Designator.Invalid || String2.Designator.Invalid)
12107       return false;
12108 
12109     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12110     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12111 
12112     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12113                      BuiltinOp == Builtin::BIbcmp ||
12114                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12115                      BuiltinOp == Builtin::BI__builtin_bcmp;
12116 
12117     assert(IsRawByte ||
12118            (Info.Ctx.hasSameUnqualifiedType(
12119                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12120             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12121 
12122     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12123     // 'char8_t', but no other types.
12124     if (IsRawByte &&
12125         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12126       // FIXME: Consider using our bit_cast implementation to support this.
12127       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12128           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12129           << CharTy1 << CharTy2;
12130       return false;
12131     }
12132 
12133     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12134       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12135              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12136              Char1.isInt() && Char2.isInt();
12137     };
12138     const auto &AdvanceElems = [&] {
12139       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12140              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12141     };
12142 
12143     bool StopAtNull =
12144         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12145          BuiltinOp != Builtin::BIwmemcmp &&
12146          BuiltinOp != Builtin::BI__builtin_memcmp &&
12147          BuiltinOp != Builtin::BI__builtin_bcmp &&
12148          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12149     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12150                   BuiltinOp == Builtin::BIwcsncmp ||
12151                   BuiltinOp == Builtin::BIwmemcmp ||
12152                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12153                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12154                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12155 
12156     for (; MaxLength; --MaxLength) {
12157       APValue Char1, Char2;
12158       if (!ReadCurElems(Char1, Char2))
12159         return false;
12160       if (Char1.getInt().ne(Char2.getInt())) {
12161         if (IsWide) // wmemcmp compares with wchar_t signedness.
12162           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12163         // memcmp always compares unsigned chars.
12164         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12165       }
12166       if (StopAtNull && !Char1.getInt())
12167         return Success(0, E);
12168       assert(!(StopAtNull && !Char2.getInt()));
12169       if (!AdvanceElems())
12170         return false;
12171     }
12172     // We hit the strncmp / memcmp limit.
12173     return Success(0, E);
12174   }
12175 
12176   case Builtin::BI__atomic_always_lock_free:
12177   case Builtin::BI__atomic_is_lock_free:
12178   case Builtin::BI__c11_atomic_is_lock_free: {
12179     APSInt SizeVal;
12180     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12181       return false;
12182 
12183     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12184     // of two less than or equal to the maximum inline atomic width, we know it
12185     // is lock-free.  If the size isn't a power of two, or greater than the
12186     // maximum alignment where we promote atomics, we know it is not lock-free
12187     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12188     // the answer can only be determined at runtime; for example, 16-byte
12189     // atomics have lock-free implementations on some, but not all,
12190     // x86-64 processors.
12191 
12192     // Check power-of-two.
12193     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12194     if (Size.isPowerOfTwo()) {
12195       // Check against inlining width.
12196       unsigned InlineWidthBits =
12197           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12198       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12199         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12200             Size == CharUnits::One() ||
12201             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12202                                                 Expr::NPC_NeverValueDependent))
12203           // OK, we will inline appropriately-aligned operations of this size,
12204           // and _Atomic(T) is appropriately-aligned.
12205           return Success(1, E);
12206 
12207         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12208           castAs<PointerType>()->getPointeeType();
12209         if (!PointeeType->isIncompleteType() &&
12210             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12211           // OK, we will inline operations on this object.
12212           return Success(1, E);
12213         }
12214       }
12215     }
12216 
12217     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12218         Success(0, E) : Error(E);
12219   }
12220   case Builtin::BI__builtin_add_overflow:
12221   case Builtin::BI__builtin_sub_overflow:
12222   case Builtin::BI__builtin_mul_overflow:
12223   case Builtin::BI__builtin_sadd_overflow:
12224   case Builtin::BI__builtin_uadd_overflow:
12225   case Builtin::BI__builtin_uaddl_overflow:
12226   case Builtin::BI__builtin_uaddll_overflow:
12227   case Builtin::BI__builtin_usub_overflow:
12228   case Builtin::BI__builtin_usubl_overflow:
12229   case Builtin::BI__builtin_usubll_overflow:
12230   case Builtin::BI__builtin_umul_overflow:
12231   case Builtin::BI__builtin_umull_overflow:
12232   case Builtin::BI__builtin_umulll_overflow:
12233   case Builtin::BI__builtin_saddl_overflow:
12234   case Builtin::BI__builtin_saddll_overflow:
12235   case Builtin::BI__builtin_ssub_overflow:
12236   case Builtin::BI__builtin_ssubl_overflow:
12237   case Builtin::BI__builtin_ssubll_overflow:
12238   case Builtin::BI__builtin_smul_overflow:
12239   case Builtin::BI__builtin_smull_overflow:
12240   case Builtin::BI__builtin_smulll_overflow: {
12241     LValue ResultLValue;
12242     APSInt LHS, RHS;
12243 
12244     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12245     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12246         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12247         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12248       return false;
12249 
12250     APSInt Result;
12251     bool DidOverflow = false;
12252 
12253     // If the types don't have to match, enlarge all 3 to the largest of them.
12254     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12255         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12256         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12257       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12258                       ResultType->isSignedIntegerOrEnumerationType();
12259       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12260                       ResultType->isSignedIntegerOrEnumerationType();
12261       uint64_t LHSSize = LHS.getBitWidth();
12262       uint64_t RHSSize = RHS.getBitWidth();
12263       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12264       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12265 
12266       // Add an additional bit if the signedness isn't uniformly agreed to. We
12267       // could do this ONLY if there is a signed and an unsigned that both have
12268       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12269       // caught in the shrink-to-result later anyway.
12270       if (IsSigned && !AllSigned)
12271         ++MaxBits;
12272 
12273       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12274       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12275       Result = APSInt(MaxBits, !IsSigned);
12276     }
12277 
12278     // Find largest int.
12279     switch (BuiltinOp) {
12280     default:
12281       llvm_unreachable("Invalid value for BuiltinOp");
12282     case Builtin::BI__builtin_add_overflow:
12283     case Builtin::BI__builtin_sadd_overflow:
12284     case Builtin::BI__builtin_saddl_overflow:
12285     case Builtin::BI__builtin_saddll_overflow:
12286     case Builtin::BI__builtin_uadd_overflow:
12287     case Builtin::BI__builtin_uaddl_overflow:
12288     case Builtin::BI__builtin_uaddll_overflow:
12289       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12290                               : LHS.uadd_ov(RHS, DidOverflow);
12291       break;
12292     case Builtin::BI__builtin_sub_overflow:
12293     case Builtin::BI__builtin_ssub_overflow:
12294     case Builtin::BI__builtin_ssubl_overflow:
12295     case Builtin::BI__builtin_ssubll_overflow:
12296     case Builtin::BI__builtin_usub_overflow:
12297     case Builtin::BI__builtin_usubl_overflow:
12298     case Builtin::BI__builtin_usubll_overflow:
12299       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12300                               : LHS.usub_ov(RHS, DidOverflow);
12301       break;
12302     case Builtin::BI__builtin_mul_overflow:
12303     case Builtin::BI__builtin_smul_overflow:
12304     case Builtin::BI__builtin_smull_overflow:
12305     case Builtin::BI__builtin_smulll_overflow:
12306     case Builtin::BI__builtin_umul_overflow:
12307     case Builtin::BI__builtin_umull_overflow:
12308     case Builtin::BI__builtin_umulll_overflow:
12309       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12310                               : LHS.umul_ov(RHS, DidOverflow);
12311       break;
12312     }
12313 
12314     // In the case where multiple sizes are allowed, truncate and see if
12315     // the values are the same.
12316     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12317         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12318         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12319       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12320       // since it will give us the behavior of a TruncOrSelf in the case where
12321       // its parameter <= its size.  We previously set Result to be at least the
12322       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12323       // will work exactly like TruncOrSelf.
12324       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12325       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12326 
12327       if (!APSInt::isSameValue(Temp, Result))
12328         DidOverflow = true;
12329       Result = Temp;
12330     }
12331 
12332     APValue APV{Result};
12333     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12334       return false;
12335     return Success(DidOverflow, E);
12336   }
12337   }
12338 }
12339 
12340 /// Determine whether this is a pointer past the end of the complete
12341 /// object referred to by the lvalue.
12342 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12343                                             const LValue &LV) {
12344   // A null pointer can be viewed as being "past the end" but we don't
12345   // choose to look at it that way here.
12346   if (!LV.getLValueBase())
12347     return false;
12348 
12349   // If the designator is valid and refers to a subobject, we're not pointing
12350   // past the end.
12351   if (!LV.getLValueDesignator().Invalid &&
12352       !LV.getLValueDesignator().isOnePastTheEnd())
12353     return false;
12354 
12355   // A pointer to an incomplete type might be past-the-end if the type's size is
12356   // zero.  We cannot tell because the type is incomplete.
12357   QualType Ty = getType(LV.getLValueBase());
12358   if (Ty->isIncompleteType())
12359     return true;
12360 
12361   // We're a past-the-end pointer if we point to the byte after the object,
12362   // no matter what our type or path is.
12363   auto Size = Ctx.getTypeSizeInChars(Ty);
12364   return LV.getLValueOffset() == Size;
12365 }
12366 
12367 namespace {
12368 
12369 /// Data recursive integer evaluator of certain binary operators.
12370 ///
12371 /// We use a data recursive algorithm for binary operators so that we are able
12372 /// to handle extreme cases of chained binary operators without causing stack
12373 /// overflow.
12374 class DataRecursiveIntBinOpEvaluator {
12375   struct EvalResult {
12376     APValue Val;
12377     bool Failed;
12378 
12379     EvalResult() : Failed(false) { }
12380 
12381     void swap(EvalResult &RHS) {
12382       Val.swap(RHS.Val);
12383       Failed = RHS.Failed;
12384       RHS.Failed = false;
12385     }
12386   };
12387 
12388   struct Job {
12389     const Expr *E;
12390     EvalResult LHSResult; // meaningful only for binary operator expression.
12391     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12392 
12393     Job() = default;
12394     Job(Job &&) = default;
12395 
12396     void startSpeculativeEval(EvalInfo &Info) {
12397       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12398     }
12399 
12400   private:
12401     SpeculativeEvaluationRAII SpecEvalRAII;
12402   };
12403 
12404   SmallVector<Job, 16> Queue;
12405 
12406   IntExprEvaluator &IntEval;
12407   EvalInfo &Info;
12408   APValue &FinalResult;
12409 
12410 public:
12411   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12412     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12413 
12414   /// True if \param E is a binary operator that we are going to handle
12415   /// data recursively.
12416   /// We handle binary operators that are comma, logical, or that have operands
12417   /// with integral or enumeration type.
12418   static bool shouldEnqueue(const BinaryOperator *E) {
12419     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12420            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12421             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12422             E->getRHS()->getType()->isIntegralOrEnumerationType());
12423   }
12424 
12425   bool Traverse(const BinaryOperator *E) {
12426     enqueue(E);
12427     EvalResult PrevResult;
12428     while (!Queue.empty())
12429       process(PrevResult);
12430 
12431     if (PrevResult.Failed) return false;
12432 
12433     FinalResult.swap(PrevResult.Val);
12434     return true;
12435   }
12436 
12437 private:
12438   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12439     return IntEval.Success(Value, E, Result);
12440   }
12441   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12442     return IntEval.Success(Value, E, Result);
12443   }
12444   bool Error(const Expr *E) {
12445     return IntEval.Error(E);
12446   }
12447   bool Error(const Expr *E, diag::kind D) {
12448     return IntEval.Error(E, D);
12449   }
12450 
12451   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12452     return Info.CCEDiag(E, D);
12453   }
12454 
12455   // Returns true if visiting the RHS is necessary, false otherwise.
12456   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12457                          bool &SuppressRHSDiags);
12458 
12459   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12460                   const BinaryOperator *E, APValue &Result);
12461 
12462   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12463     Result.Failed = !Evaluate(Result.Val, Info, E);
12464     if (Result.Failed)
12465       Result.Val = APValue();
12466   }
12467 
12468   void process(EvalResult &Result);
12469 
12470   void enqueue(const Expr *E) {
12471     E = E->IgnoreParens();
12472     Queue.resize(Queue.size()+1);
12473     Queue.back().E = E;
12474     Queue.back().Kind = Job::AnyExprKind;
12475   }
12476 };
12477 
12478 }
12479 
12480 bool DataRecursiveIntBinOpEvaluator::
12481        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12482                          bool &SuppressRHSDiags) {
12483   if (E->getOpcode() == BO_Comma) {
12484     // Ignore LHS but note if we could not evaluate it.
12485     if (LHSResult.Failed)
12486       return Info.noteSideEffect();
12487     return true;
12488   }
12489 
12490   if (E->isLogicalOp()) {
12491     bool LHSAsBool;
12492     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12493       // We were able to evaluate the LHS, see if we can get away with not
12494       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12495       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12496         Success(LHSAsBool, E, LHSResult.Val);
12497         return false; // Ignore RHS
12498       }
12499     } else {
12500       LHSResult.Failed = true;
12501 
12502       // Since we weren't able to evaluate the left hand side, it
12503       // might have had side effects.
12504       if (!Info.noteSideEffect())
12505         return false;
12506 
12507       // We can't evaluate the LHS; however, sometimes the result
12508       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12509       // Don't ignore RHS and suppress diagnostics from this arm.
12510       SuppressRHSDiags = true;
12511     }
12512 
12513     return true;
12514   }
12515 
12516   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12517          E->getRHS()->getType()->isIntegralOrEnumerationType());
12518 
12519   if (LHSResult.Failed && !Info.noteFailure())
12520     return false; // Ignore RHS;
12521 
12522   return true;
12523 }
12524 
12525 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12526                                     bool IsSub) {
12527   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12528   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12529   // offsets.
12530   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12531   CharUnits &Offset = LVal.getLValueOffset();
12532   uint64_t Offset64 = Offset.getQuantity();
12533   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12534   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12535                                          : Offset64 + Index64);
12536 }
12537 
12538 bool DataRecursiveIntBinOpEvaluator::
12539        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12540                   const BinaryOperator *E, APValue &Result) {
12541   if (E->getOpcode() == BO_Comma) {
12542     if (RHSResult.Failed)
12543       return false;
12544     Result = RHSResult.Val;
12545     return true;
12546   }
12547 
12548   if (E->isLogicalOp()) {
12549     bool lhsResult, rhsResult;
12550     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12551     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12552 
12553     if (LHSIsOK) {
12554       if (RHSIsOK) {
12555         if (E->getOpcode() == BO_LOr)
12556           return Success(lhsResult || rhsResult, E, Result);
12557         else
12558           return Success(lhsResult && rhsResult, E, Result);
12559       }
12560     } else {
12561       if (RHSIsOK) {
12562         // We can't evaluate the LHS; however, sometimes the result
12563         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12564         if (rhsResult == (E->getOpcode() == BO_LOr))
12565           return Success(rhsResult, E, Result);
12566       }
12567     }
12568 
12569     return false;
12570   }
12571 
12572   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12573          E->getRHS()->getType()->isIntegralOrEnumerationType());
12574 
12575   if (LHSResult.Failed || RHSResult.Failed)
12576     return false;
12577 
12578   const APValue &LHSVal = LHSResult.Val;
12579   const APValue &RHSVal = RHSResult.Val;
12580 
12581   // Handle cases like (unsigned long)&a + 4.
12582   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12583     Result = LHSVal;
12584     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12585     return true;
12586   }
12587 
12588   // Handle cases like 4 + (unsigned long)&a
12589   if (E->getOpcode() == BO_Add &&
12590       RHSVal.isLValue() && LHSVal.isInt()) {
12591     Result = RHSVal;
12592     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12593     return true;
12594   }
12595 
12596   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12597     // Handle (intptr_t)&&A - (intptr_t)&&B.
12598     if (!LHSVal.getLValueOffset().isZero() ||
12599         !RHSVal.getLValueOffset().isZero())
12600       return false;
12601     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12602     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12603     if (!LHSExpr || !RHSExpr)
12604       return false;
12605     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12606     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12607     if (!LHSAddrExpr || !RHSAddrExpr)
12608       return false;
12609     // Make sure both labels come from the same function.
12610     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12611         RHSAddrExpr->getLabel()->getDeclContext())
12612       return false;
12613     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12614     return true;
12615   }
12616 
12617   // All the remaining cases expect both operands to be an integer
12618   if (!LHSVal.isInt() || !RHSVal.isInt())
12619     return Error(E);
12620 
12621   // Set up the width and signedness manually, in case it can't be deduced
12622   // from the operation we're performing.
12623   // FIXME: Don't do this in the cases where we can deduce it.
12624   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12625                E->getType()->isUnsignedIntegerOrEnumerationType());
12626   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12627                          RHSVal.getInt(), Value))
12628     return false;
12629   return Success(Value, E, Result);
12630 }
12631 
12632 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12633   Job &job = Queue.back();
12634 
12635   switch (job.Kind) {
12636     case Job::AnyExprKind: {
12637       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12638         if (shouldEnqueue(Bop)) {
12639           job.Kind = Job::BinOpKind;
12640           enqueue(Bop->getLHS());
12641           return;
12642         }
12643       }
12644 
12645       EvaluateExpr(job.E, Result);
12646       Queue.pop_back();
12647       return;
12648     }
12649 
12650     case Job::BinOpKind: {
12651       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12652       bool SuppressRHSDiags = false;
12653       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12654         Queue.pop_back();
12655         return;
12656       }
12657       if (SuppressRHSDiags)
12658         job.startSpeculativeEval(Info);
12659       job.LHSResult.swap(Result);
12660       job.Kind = Job::BinOpVisitedLHSKind;
12661       enqueue(Bop->getRHS());
12662       return;
12663     }
12664 
12665     case Job::BinOpVisitedLHSKind: {
12666       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12667       EvalResult RHS;
12668       RHS.swap(Result);
12669       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12670       Queue.pop_back();
12671       return;
12672     }
12673   }
12674 
12675   llvm_unreachable("Invalid Job::Kind!");
12676 }
12677 
12678 namespace {
12679 enum class CmpResult {
12680   Unequal,
12681   Less,
12682   Equal,
12683   Greater,
12684   Unordered,
12685 };
12686 }
12687 
12688 template <class SuccessCB, class AfterCB>
12689 static bool
12690 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12691                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12692   assert(!E->isValueDependent());
12693   assert(E->isComparisonOp() && "expected comparison operator");
12694   assert((E->getOpcode() == BO_Cmp ||
12695           E->getType()->isIntegralOrEnumerationType()) &&
12696          "unsupported binary expression evaluation");
12697   auto Error = [&](const Expr *E) {
12698     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12699     return false;
12700   };
12701 
12702   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12703   bool IsEquality = E->isEqualityOp();
12704 
12705   QualType LHSTy = E->getLHS()->getType();
12706   QualType RHSTy = E->getRHS()->getType();
12707 
12708   if (LHSTy->isIntegralOrEnumerationType() &&
12709       RHSTy->isIntegralOrEnumerationType()) {
12710     APSInt LHS, RHS;
12711     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12712     if (!LHSOK && !Info.noteFailure())
12713       return false;
12714     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12715       return false;
12716     if (LHS < RHS)
12717       return Success(CmpResult::Less, E);
12718     if (LHS > RHS)
12719       return Success(CmpResult::Greater, E);
12720     return Success(CmpResult::Equal, E);
12721   }
12722 
12723   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12724     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12725     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12726 
12727     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12728     if (!LHSOK && !Info.noteFailure())
12729       return false;
12730     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12731       return false;
12732     if (LHSFX < RHSFX)
12733       return Success(CmpResult::Less, E);
12734     if (LHSFX > RHSFX)
12735       return Success(CmpResult::Greater, E);
12736     return Success(CmpResult::Equal, E);
12737   }
12738 
12739   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12740     ComplexValue LHS, RHS;
12741     bool LHSOK;
12742     if (E->isAssignmentOp()) {
12743       LValue LV;
12744       EvaluateLValue(E->getLHS(), LV, Info);
12745       LHSOK = false;
12746     } else if (LHSTy->isRealFloatingType()) {
12747       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12748       if (LHSOK) {
12749         LHS.makeComplexFloat();
12750         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12751       }
12752     } else {
12753       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12754     }
12755     if (!LHSOK && !Info.noteFailure())
12756       return false;
12757 
12758     if (E->getRHS()->getType()->isRealFloatingType()) {
12759       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12760         return false;
12761       RHS.makeComplexFloat();
12762       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12763     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12764       return false;
12765 
12766     if (LHS.isComplexFloat()) {
12767       APFloat::cmpResult CR_r =
12768         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12769       APFloat::cmpResult CR_i =
12770         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12771       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12772       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12773     } else {
12774       assert(IsEquality && "invalid complex comparison");
12775       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12776                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12777       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12778     }
12779   }
12780 
12781   if (LHSTy->isRealFloatingType() &&
12782       RHSTy->isRealFloatingType()) {
12783     APFloat RHS(0.0), LHS(0.0);
12784 
12785     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12786     if (!LHSOK && !Info.noteFailure())
12787       return false;
12788 
12789     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12790       return false;
12791 
12792     assert(E->isComparisonOp() && "Invalid binary operator!");
12793     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12794     if (!Info.InConstantContext &&
12795         APFloatCmpResult == APFloat::cmpUnordered &&
12796         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12797       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12798       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12799       return false;
12800     }
12801     auto GetCmpRes = [&]() {
12802       switch (APFloatCmpResult) {
12803       case APFloat::cmpEqual:
12804         return CmpResult::Equal;
12805       case APFloat::cmpLessThan:
12806         return CmpResult::Less;
12807       case APFloat::cmpGreaterThan:
12808         return CmpResult::Greater;
12809       case APFloat::cmpUnordered:
12810         return CmpResult::Unordered;
12811       }
12812       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12813     };
12814     return Success(GetCmpRes(), E);
12815   }
12816 
12817   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12818     LValue LHSValue, RHSValue;
12819 
12820     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12821     if (!LHSOK && !Info.noteFailure())
12822       return false;
12823 
12824     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12825       return false;
12826 
12827     // Reject differing bases from the normal codepath; we special-case
12828     // comparisons to null.
12829     if (!HasSameBase(LHSValue, RHSValue)) {
12830       // Inequalities and subtractions between unrelated pointers have
12831       // unspecified or undefined behavior.
12832       if (!IsEquality) {
12833         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12834         return false;
12835       }
12836       // A constant address may compare equal to the address of a symbol.
12837       // The one exception is that address of an object cannot compare equal
12838       // to a null pointer constant.
12839       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12840           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12841         return Error(E);
12842       // It's implementation-defined whether distinct literals will have
12843       // distinct addresses. In clang, the result of such a comparison is
12844       // unspecified, so it is not a constant expression. However, we do know
12845       // that the address of a literal will be non-null.
12846       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12847           LHSValue.Base && RHSValue.Base)
12848         return Error(E);
12849       // We can't tell whether weak symbols will end up pointing to the same
12850       // object.
12851       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12852         return Error(E);
12853       // We can't compare the address of the start of one object with the
12854       // past-the-end address of another object, per C++ DR1652.
12855       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12856            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12857           (RHSValue.Base && RHSValue.Offset.isZero() &&
12858            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12859         return Error(E);
12860       // We can't tell whether an object is at the same address as another
12861       // zero sized object.
12862       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12863           (LHSValue.Base && isZeroSized(RHSValue)))
12864         return Error(E);
12865       return Success(CmpResult::Unequal, E);
12866     }
12867 
12868     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12869     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12870 
12871     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12872     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12873 
12874     // C++11 [expr.rel]p3:
12875     //   Pointers to void (after pointer conversions) can be compared, with a
12876     //   result defined as follows: If both pointers represent the same
12877     //   address or are both the null pointer value, the result is true if the
12878     //   operator is <= or >= and false otherwise; otherwise the result is
12879     //   unspecified.
12880     // We interpret this as applying to pointers to *cv* void.
12881     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12882       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12883 
12884     // C++11 [expr.rel]p2:
12885     // - If two pointers point to non-static data members of the same object,
12886     //   or to subobjects or array elements fo such members, recursively, the
12887     //   pointer to the later declared member compares greater provided the
12888     //   two members have the same access control and provided their class is
12889     //   not a union.
12890     //   [...]
12891     // - Otherwise pointer comparisons are unspecified.
12892     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12893       bool WasArrayIndex;
12894       unsigned Mismatch = FindDesignatorMismatch(
12895           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12896       // At the point where the designators diverge, the comparison has a
12897       // specified value if:
12898       //  - we are comparing array indices
12899       //  - we are comparing fields of a union, or fields with the same access
12900       // Otherwise, the result is unspecified and thus the comparison is not a
12901       // constant expression.
12902       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12903           Mismatch < RHSDesignator.Entries.size()) {
12904         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12905         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12906         if (!LF && !RF)
12907           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12908         else if (!LF)
12909           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12910               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12911               << RF->getParent() << RF;
12912         else if (!RF)
12913           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12914               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12915               << LF->getParent() << LF;
12916         else if (!LF->getParent()->isUnion() &&
12917                  LF->getAccess() != RF->getAccess())
12918           Info.CCEDiag(E,
12919                        diag::note_constexpr_pointer_comparison_differing_access)
12920               << LF << LF->getAccess() << RF << RF->getAccess()
12921               << LF->getParent();
12922       }
12923     }
12924 
12925     // The comparison here must be unsigned, and performed with the same
12926     // width as the pointer.
12927     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12928     uint64_t CompareLHS = LHSOffset.getQuantity();
12929     uint64_t CompareRHS = RHSOffset.getQuantity();
12930     assert(PtrSize <= 64 && "Unexpected pointer width");
12931     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12932     CompareLHS &= Mask;
12933     CompareRHS &= Mask;
12934 
12935     // If there is a base and this is a relational operator, we can only
12936     // compare pointers within the object in question; otherwise, the result
12937     // depends on where the object is located in memory.
12938     if (!LHSValue.Base.isNull() && IsRelational) {
12939       QualType BaseTy = getType(LHSValue.Base);
12940       if (BaseTy->isIncompleteType())
12941         return Error(E);
12942       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12943       uint64_t OffsetLimit = Size.getQuantity();
12944       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12945         return Error(E);
12946     }
12947 
12948     if (CompareLHS < CompareRHS)
12949       return Success(CmpResult::Less, E);
12950     if (CompareLHS > CompareRHS)
12951       return Success(CmpResult::Greater, E);
12952     return Success(CmpResult::Equal, E);
12953   }
12954 
12955   if (LHSTy->isMemberPointerType()) {
12956     assert(IsEquality && "unexpected member pointer operation");
12957     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12958 
12959     MemberPtr LHSValue, RHSValue;
12960 
12961     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12962     if (!LHSOK && !Info.noteFailure())
12963       return false;
12964 
12965     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12966       return false;
12967 
12968     // C++11 [expr.eq]p2:
12969     //   If both operands are null, they compare equal. Otherwise if only one is
12970     //   null, they compare unequal.
12971     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12972       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12973       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12974     }
12975 
12976     //   Otherwise if either is a pointer to a virtual member function, the
12977     //   result is unspecified.
12978     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12979       if (MD->isVirtual())
12980         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12981     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12982       if (MD->isVirtual())
12983         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12984 
12985     //   Otherwise they compare equal if and only if they would refer to the
12986     //   same member of the same most derived object or the same subobject if
12987     //   they were dereferenced with a hypothetical object of the associated
12988     //   class type.
12989     bool Equal = LHSValue == RHSValue;
12990     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12991   }
12992 
12993   if (LHSTy->isNullPtrType()) {
12994     assert(E->isComparisonOp() && "unexpected nullptr operation");
12995     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12996     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12997     // are compared, the result is true of the operator is <=, >= or ==, and
12998     // false otherwise.
12999     return Success(CmpResult::Equal, E);
13000   }
13001 
13002   return DoAfter();
13003 }
13004 
13005 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13006   if (!CheckLiteralType(Info, E))
13007     return false;
13008 
13009   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13010     ComparisonCategoryResult CCR;
13011     switch (CR) {
13012     case CmpResult::Unequal:
13013       llvm_unreachable("should never produce Unequal for three-way comparison");
13014     case CmpResult::Less:
13015       CCR = ComparisonCategoryResult::Less;
13016       break;
13017     case CmpResult::Equal:
13018       CCR = ComparisonCategoryResult::Equal;
13019       break;
13020     case CmpResult::Greater:
13021       CCR = ComparisonCategoryResult::Greater;
13022       break;
13023     case CmpResult::Unordered:
13024       CCR = ComparisonCategoryResult::Unordered;
13025       break;
13026     }
13027     // Evaluation succeeded. Lookup the information for the comparison category
13028     // type and fetch the VarDecl for the result.
13029     const ComparisonCategoryInfo &CmpInfo =
13030         Info.Ctx.CompCategories.getInfoForType(E->getType());
13031     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13032     // Check and evaluate the result as a constant expression.
13033     LValue LV;
13034     LV.set(VD);
13035     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13036       return false;
13037     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13038                                    ConstantExprKind::Normal);
13039   };
13040   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13041     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13042   });
13043 }
13044 
13045 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13046   // We don't support assignment in C. C++ assignments don't get here because
13047   // assignment is an lvalue in C++.
13048   if (E->isAssignmentOp()) {
13049     Error(E);
13050     if (!Info.noteFailure())
13051       return false;
13052   }
13053 
13054   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13055     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13056 
13057   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13058           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13059          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13060 
13061   if (E->isComparisonOp()) {
13062     // Evaluate builtin binary comparisons by evaluating them as three-way
13063     // comparisons and then translating the result.
13064     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13065       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13066              "should only produce Unequal for equality comparisons");
13067       bool IsEqual   = CR == CmpResult::Equal,
13068            IsLess    = CR == CmpResult::Less,
13069            IsGreater = CR == CmpResult::Greater;
13070       auto Op = E->getOpcode();
13071       switch (Op) {
13072       default:
13073         llvm_unreachable("unsupported binary operator");
13074       case BO_EQ:
13075       case BO_NE:
13076         return Success(IsEqual == (Op == BO_EQ), E);
13077       case BO_LT:
13078         return Success(IsLess, E);
13079       case BO_GT:
13080         return Success(IsGreater, E);
13081       case BO_LE:
13082         return Success(IsEqual || IsLess, E);
13083       case BO_GE:
13084         return Success(IsEqual || IsGreater, E);
13085       }
13086     };
13087     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13088       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13089     });
13090   }
13091 
13092   QualType LHSTy = E->getLHS()->getType();
13093   QualType RHSTy = E->getRHS()->getType();
13094 
13095   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13096       E->getOpcode() == BO_Sub) {
13097     LValue LHSValue, RHSValue;
13098 
13099     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13100     if (!LHSOK && !Info.noteFailure())
13101       return false;
13102 
13103     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13104       return false;
13105 
13106     // Reject differing bases from the normal codepath; we special-case
13107     // comparisons to null.
13108     if (!HasSameBase(LHSValue, RHSValue)) {
13109       // Handle &&A - &&B.
13110       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13111         return Error(E);
13112       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13113       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13114       if (!LHSExpr || !RHSExpr)
13115         return Error(E);
13116       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13117       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13118       if (!LHSAddrExpr || !RHSAddrExpr)
13119         return Error(E);
13120       // Make sure both labels come from the same function.
13121       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13122           RHSAddrExpr->getLabel()->getDeclContext())
13123         return Error(E);
13124       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13125     }
13126     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13127     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13128 
13129     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13130     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13131 
13132     // C++11 [expr.add]p6:
13133     //   Unless both pointers point to elements of the same array object, or
13134     //   one past the last element of the array object, the behavior is
13135     //   undefined.
13136     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13137         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13138                                 RHSDesignator))
13139       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13140 
13141     QualType Type = E->getLHS()->getType();
13142     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13143 
13144     CharUnits ElementSize;
13145     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13146       return false;
13147 
13148     // As an extension, a type may have zero size (empty struct or union in
13149     // C, array of zero length). Pointer subtraction in such cases has
13150     // undefined behavior, so is not constant.
13151     if (ElementSize.isZero()) {
13152       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13153           << ElementType;
13154       return false;
13155     }
13156 
13157     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13158     // and produce incorrect results when it overflows. Such behavior
13159     // appears to be non-conforming, but is common, so perhaps we should
13160     // assume the standard intended for such cases to be undefined behavior
13161     // and check for them.
13162 
13163     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13164     // overflow in the final conversion to ptrdiff_t.
13165     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13166     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13167     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13168                     false);
13169     APSInt TrueResult = (LHS - RHS) / ElemSize;
13170     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13171 
13172     if (Result.extend(65) != TrueResult &&
13173         !HandleOverflow(Info, E, TrueResult, E->getType()))
13174       return false;
13175     return Success(Result, E);
13176   }
13177 
13178   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13179 }
13180 
13181 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13182 /// a result as the expression's type.
13183 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13184                                     const UnaryExprOrTypeTraitExpr *E) {
13185   switch(E->getKind()) {
13186   case UETT_PreferredAlignOf:
13187   case UETT_AlignOf: {
13188     if (E->isArgumentType())
13189       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13190                      E);
13191     else
13192       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13193                      E);
13194   }
13195 
13196   case UETT_VecStep: {
13197     QualType Ty = E->getTypeOfArgument();
13198 
13199     if (Ty->isVectorType()) {
13200       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13201 
13202       // The vec_step built-in functions that take a 3-component
13203       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13204       if (n == 3)
13205         n = 4;
13206 
13207       return Success(n, E);
13208     } else
13209       return Success(1, E);
13210   }
13211 
13212   case UETT_SizeOf: {
13213     QualType SrcTy = E->getTypeOfArgument();
13214     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13215     //   the result is the size of the referenced type."
13216     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13217       SrcTy = Ref->getPointeeType();
13218 
13219     CharUnits Sizeof;
13220     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13221       return false;
13222     return Success(Sizeof, E);
13223   }
13224   case UETT_OpenMPRequiredSimdAlign:
13225     assert(E->isArgumentType());
13226     return Success(
13227         Info.Ctx.toCharUnitsFromBits(
13228                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13229             .getQuantity(),
13230         E);
13231   }
13232 
13233   llvm_unreachable("unknown expr/type trait");
13234 }
13235 
13236 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13237   CharUnits Result;
13238   unsigned n = OOE->getNumComponents();
13239   if (n == 0)
13240     return Error(OOE);
13241   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13242   for (unsigned i = 0; i != n; ++i) {
13243     OffsetOfNode ON = OOE->getComponent(i);
13244     switch (ON.getKind()) {
13245     case OffsetOfNode::Array: {
13246       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13247       APSInt IdxResult;
13248       if (!EvaluateInteger(Idx, IdxResult, Info))
13249         return false;
13250       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13251       if (!AT)
13252         return Error(OOE);
13253       CurrentType = AT->getElementType();
13254       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13255       Result += IdxResult.getSExtValue() * ElementSize;
13256       break;
13257     }
13258 
13259     case OffsetOfNode::Field: {
13260       FieldDecl *MemberDecl = ON.getField();
13261       const RecordType *RT = CurrentType->getAs<RecordType>();
13262       if (!RT)
13263         return Error(OOE);
13264       RecordDecl *RD = RT->getDecl();
13265       if (RD->isInvalidDecl()) return false;
13266       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13267       unsigned i = MemberDecl->getFieldIndex();
13268       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13269       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13270       CurrentType = MemberDecl->getType().getNonReferenceType();
13271       break;
13272     }
13273 
13274     case OffsetOfNode::Identifier:
13275       llvm_unreachable("dependent __builtin_offsetof");
13276 
13277     case OffsetOfNode::Base: {
13278       CXXBaseSpecifier *BaseSpec = ON.getBase();
13279       if (BaseSpec->isVirtual())
13280         return Error(OOE);
13281 
13282       // Find the layout of the class whose base we are looking into.
13283       const RecordType *RT = CurrentType->getAs<RecordType>();
13284       if (!RT)
13285         return Error(OOE);
13286       RecordDecl *RD = RT->getDecl();
13287       if (RD->isInvalidDecl()) return false;
13288       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13289 
13290       // Find the base class itself.
13291       CurrentType = BaseSpec->getType();
13292       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13293       if (!BaseRT)
13294         return Error(OOE);
13295 
13296       // Add the offset to the base.
13297       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13298       break;
13299     }
13300     }
13301   }
13302   return Success(Result, OOE);
13303 }
13304 
13305 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13306   switch (E->getOpcode()) {
13307   default:
13308     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13309     // See C99 6.6p3.
13310     return Error(E);
13311   case UO_Extension:
13312     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13313     // If so, we could clear the diagnostic ID.
13314     return Visit(E->getSubExpr());
13315   case UO_Plus:
13316     // The result is just the value.
13317     return Visit(E->getSubExpr());
13318   case UO_Minus: {
13319     if (!Visit(E->getSubExpr()))
13320       return false;
13321     if (!Result.isInt()) return Error(E);
13322     const APSInt &Value = Result.getInt();
13323     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13324         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13325                         E->getType()))
13326       return false;
13327     return Success(-Value, E);
13328   }
13329   case UO_Not: {
13330     if (!Visit(E->getSubExpr()))
13331       return false;
13332     if (!Result.isInt()) return Error(E);
13333     return Success(~Result.getInt(), E);
13334   }
13335   case UO_LNot: {
13336     bool bres;
13337     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13338       return false;
13339     return Success(!bres, E);
13340   }
13341   }
13342 }
13343 
13344 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13345 /// result type is integer.
13346 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13347   const Expr *SubExpr = E->getSubExpr();
13348   QualType DestType = E->getType();
13349   QualType SrcType = SubExpr->getType();
13350 
13351   switch (E->getCastKind()) {
13352   case CK_BaseToDerived:
13353   case CK_DerivedToBase:
13354   case CK_UncheckedDerivedToBase:
13355   case CK_Dynamic:
13356   case CK_ToUnion:
13357   case CK_ArrayToPointerDecay:
13358   case CK_FunctionToPointerDecay:
13359   case CK_NullToPointer:
13360   case CK_NullToMemberPointer:
13361   case CK_BaseToDerivedMemberPointer:
13362   case CK_DerivedToBaseMemberPointer:
13363   case CK_ReinterpretMemberPointer:
13364   case CK_ConstructorConversion:
13365   case CK_IntegralToPointer:
13366   case CK_ToVoid:
13367   case CK_VectorSplat:
13368   case CK_IntegralToFloating:
13369   case CK_FloatingCast:
13370   case CK_CPointerToObjCPointerCast:
13371   case CK_BlockPointerToObjCPointerCast:
13372   case CK_AnyPointerToBlockPointerCast:
13373   case CK_ObjCObjectLValueCast:
13374   case CK_FloatingRealToComplex:
13375   case CK_FloatingComplexToReal:
13376   case CK_FloatingComplexCast:
13377   case CK_FloatingComplexToIntegralComplex:
13378   case CK_IntegralRealToComplex:
13379   case CK_IntegralComplexCast:
13380   case CK_IntegralComplexToFloatingComplex:
13381   case CK_BuiltinFnToFnPtr:
13382   case CK_ZeroToOCLOpaqueType:
13383   case CK_NonAtomicToAtomic:
13384   case CK_AddressSpaceConversion:
13385   case CK_IntToOCLSampler:
13386   case CK_FloatingToFixedPoint:
13387   case CK_FixedPointToFloating:
13388   case CK_FixedPointCast:
13389   case CK_IntegralToFixedPoint:
13390   case CK_MatrixCast:
13391     llvm_unreachable("invalid cast kind for integral value");
13392 
13393   case CK_BitCast:
13394   case CK_Dependent:
13395   case CK_LValueBitCast:
13396   case CK_ARCProduceObject:
13397   case CK_ARCConsumeObject:
13398   case CK_ARCReclaimReturnedObject:
13399   case CK_ARCExtendBlockObject:
13400   case CK_CopyAndAutoreleaseBlockObject:
13401     return Error(E);
13402 
13403   case CK_UserDefinedConversion:
13404   case CK_LValueToRValue:
13405   case CK_AtomicToNonAtomic:
13406   case CK_NoOp:
13407   case CK_LValueToRValueBitCast:
13408     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13409 
13410   case CK_MemberPointerToBoolean:
13411   case CK_PointerToBoolean:
13412   case CK_IntegralToBoolean:
13413   case CK_FloatingToBoolean:
13414   case CK_BooleanToSignedIntegral:
13415   case CK_FloatingComplexToBoolean:
13416   case CK_IntegralComplexToBoolean: {
13417     bool BoolResult;
13418     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13419       return false;
13420     uint64_t IntResult = BoolResult;
13421     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13422       IntResult = (uint64_t)-1;
13423     return Success(IntResult, E);
13424   }
13425 
13426   case CK_FixedPointToIntegral: {
13427     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13428     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13429       return false;
13430     bool Overflowed;
13431     llvm::APSInt Result = Src.convertToInt(
13432         Info.Ctx.getIntWidth(DestType),
13433         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13434     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13435       return false;
13436     return Success(Result, E);
13437   }
13438 
13439   case CK_FixedPointToBoolean: {
13440     // Unsigned padding does not affect this.
13441     APValue Val;
13442     if (!Evaluate(Val, Info, SubExpr))
13443       return false;
13444     return Success(Val.getFixedPoint().getBoolValue(), E);
13445   }
13446 
13447   case CK_IntegralCast: {
13448     if (!Visit(SubExpr))
13449       return false;
13450 
13451     if (!Result.isInt()) {
13452       // Allow casts of address-of-label differences if they are no-ops
13453       // or narrowing.  (The narrowing case isn't actually guaranteed to
13454       // be constant-evaluatable except in some narrow cases which are hard
13455       // to detect here.  We let it through on the assumption the user knows
13456       // what they are doing.)
13457       if (Result.isAddrLabelDiff())
13458         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13459       // Only allow casts of lvalues if they are lossless.
13460       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13461     }
13462 
13463     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13464                                       Result.getInt()), E);
13465   }
13466 
13467   case CK_PointerToIntegral: {
13468     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13469 
13470     LValue LV;
13471     if (!EvaluatePointer(SubExpr, LV, Info))
13472       return false;
13473 
13474     if (LV.getLValueBase()) {
13475       // Only allow based lvalue casts if they are lossless.
13476       // FIXME: Allow a larger integer size than the pointer size, and allow
13477       // narrowing back down to pointer width in subsequent integral casts.
13478       // FIXME: Check integer type's active bits, not its type size.
13479       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13480         return Error(E);
13481 
13482       LV.Designator.setInvalid();
13483       LV.moveInto(Result);
13484       return true;
13485     }
13486 
13487     APSInt AsInt;
13488     APValue V;
13489     LV.moveInto(V);
13490     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13491       llvm_unreachable("Can't cast this!");
13492 
13493     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13494   }
13495 
13496   case CK_IntegralComplexToReal: {
13497     ComplexValue C;
13498     if (!EvaluateComplex(SubExpr, C, Info))
13499       return false;
13500     return Success(C.getComplexIntReal(), E);
13501   }
13502 
13503   case CK_FloatingToIntegral: {
13504     APFloat F(0.0);
13505     if (!EvaluateFloat(SubExpr, F, Info))
13506       return false;
13507 
13508     APSInt Value;
13509     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13510       return false;
13511     return Success(Value, E);
13512   }
13513   }
13514 
13515   llvm_unreachable("unknown cast resulting in integral value");
13516 }
13517 
13518 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13519   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13520     ComplexValue LV;
13521     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13522       return false;
13523     if (!LV.isComplexInt())
13524       return Error(E);
13525     return Success(LV.getComplexIntReal(), E);
13526   }
13527 
13528   return Visit(E->getSubExpr());
13529 }
13530 
13531 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13532   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13533     ComplexValue LV;
13534     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13535       return false;
13536     if (!LV.isComplexInt())
13537       return Error(E);
13538     return Success(LV.getComplexIntImag(), E);
13539   }
13540 
13541   VisitIgnoredValue(E->getSubExpr());
13542   return Success(0, E);
13543 }
13544 
13545 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13546   return Success(E->getPackLength(), E);
13547 }
13548 
13549 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13550   return Success(E->getValue(), E);
13551 }
13552 
13553 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13554        const ConceptSpecializationExpr *E) {
13555   return Success(E->isSatisfied(), E);
13556 }
13557 
13558 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13559   return Success(E->isSatisfied(), E);
13560 }
13561 
13562 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13563   switch (E->getOpcode()) {
13564     default:
13565       // Invalid unary operators
13566       return Error(E);
13567     case UO_Plus:
13568       // The result is just the value.
13569       return Visit(E->getSubExpr());
13570     case UO_Minus: {
13571       if (!Visit(E->getSubExpr())) return false;
13572       if (!Result.isFixedPoint())
13573         return Error(E);
13574       bool Overflowed;
13575       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13576       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13577         return false;
13578       return Success(Negated, E);
13579     }
13580     case UO_LNot: {
13581       bool bres;
13582       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13583         return false;
13584       return Success(!bres, E);
13585     }
13586   }
13587 }
13588 
13589 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13590   const Expr *SubExpr = E->getSubExpr();
13591   QualType DestType = E->getType();
13592   assert(DestType->isFixedPointType() &&
13593          "Expected destination type to be a fixed point type");
13594   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13595 
13596   switch (E->getCastKind()) {
13597   case CK_FixedPointCast: {
13598     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13599     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13600       return false;
13601     bool Overflowed;
13602     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13603     if (Overflowed) {
13604       if (Info.checkingForUndefinedBehavior())
13605         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13606                                          diag::warn_fixedpoint_constant_overflow)
13607           << Result.toString() << E->getType();
13608       if (!HandleOverflow(Info, E, Result, E->getType()))
13609         return false;
13610     }
13611     return Success(Result, E);
13612   }
13613   case CK_IntegralToFixedPoint: {
13614     APSInt Src;
13615     if (!EvaluateInteger(SubExpr, Src, Info))
13616       return false;
13617 
13618     bool Overflowed;
13619     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13620         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13621 
13622     if (Overflowed) {
13623       if (Info.checkingForUndefinedBehavior())
13624         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13625                                          diag::warn_fixedpoint_constant_overflow)
13626           << IntResult.toString() << E->getType();
13627       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13628         return false;
13629     }
13630 
13631     return Success(IntResult, E);
13632   }
13633   case CK_FloatingToFixedPoint: {
13634     APFloat Src(0.0);
13635     if (!EvaluateFloat(SubExpr, Src, Info))
13636       return false;
13637 
13638     bool Overflowed;
13639     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13640         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13641 
13642     if (Overflowed) {
13643       if (Info.checkingForUndefinedBehavior())
13644         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13645                                          diag::warn_fixedpoint_constant_overflow)
13646           << Result.toString() << E->getType();
13647       if (!HandleOverflow(Info, E, Result, E->getType()))
13648         return false;
13649     }
13650 
13651     return Success(Result, E);
13652   }
13653   case CK_NoOp:
13654   case CK_LValueToRValue:
13655     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13656   default:
13657     return Error(E);
13658   }
13659 }
13660 
13661 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13662   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13663     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13664 
13665   const Expr *LHS = E->getLHS();
13666   const Expr *RHS = E->getRHS();
13667   FixedPointSemantics ResultFXSema =
13668       Info.Ctx.getFixedPointSemantics(E->getType());
13669 
13670   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13671   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13672     return false;
13673   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13674   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13675     return false;
13676 
13677   bool OpOverflow = false, ConversionOverflow = false;
13678   APFixedPoint Result(LHSFX.getSemantics());
13679   switch (E->getOpcode()) {
13680   case BO_Add: {
13681     Result = LHSFX.add(RHSFX, &OpOverflow)
13682                   .convert(ResultFXSema, &ConversionOverflow);
13683     break;
13684   }
13685   case BO_Sub: {
13686     Result = LHSFX.sub(RHSFX, &OpOverflow)
13687                   .convert(ResultFXSema, &ConversionOverflow);
13688     break;
13689   }
13690   case BO_Mul: {
13691     Result = LHSFX.mul(RHSFX, &OpOverflow)
13692                   .convert(ResultFXSema, &ConversionOverflow);
13693     break;
13694   }
13695   case BO_Div: {
13696     if (RHSFX.getValue() == 0) {
13697       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13698       return false;
13699     }
13700     Result = LHSFX.div(RHSFX, &OpOverflow)
13701                   .convert(ResultFXSema, &ConversionOverflow);
13702     break;
13703   }
13704   case BO_Shl:
13705   case BO_Shr: {
13706     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13707     llvm::APSInt RHSVal = RHSFX.getValue();
13708 
13709     unsigned ShiftBW =
13710         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13711     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13712     // Embedded-C 4.1.6.2.2:
13713     //   The right operand must be nonnegative and less than the total number
13714     //   of (nonpadding) bits of the fixed-point operand ...
13715     if (RHSVal.isNegative())
13716       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13717     else if (Amt != RHSVal)
13718       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13719           << RHSVal << E->getType() << ShiftBW;
13720 
13721     if (E->getOpcode() == BO_Shl)
13722       Result = LHSFX.shl(Amt, &OpOverflow);
13723     else
13724       Result = LHSFX.shr(Amt, &OpOverflow);
13725     break;
13726   }
13727   default:
13728     return false;
13729   }
13730   if (OpOverflow || ConversionOverflow) {
13731     if (Info.checkingForUndefinedBehavior())
13732       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13733                                        diag::warn_fixedpoint_constant_overflow)
13734         << Result.toString() << E->getType();
13735     if (!HandleOverflow(Info, E, Result, E->getType()))
13736       return false;
13737   }
13738   return Success(Result, E);
13739 }
13740 
13741 //===----------------------------------------------------------------------===//
13742 // Float Evaluation
13743 //===----------------------------------------------------------------------===//
13744 
13745 namespace {
13746 class FloatExprEvaluator
13747   : public ExprEvaluatorBase<FloatExprEvaluator> {
13748   APFloat &Result;
13749 public:
13750   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13751     : ExprEvaluatorBaseTy(info), Result(result) {}
13752 
13753   bool Success(const APValue &V, const Expr *e) {
13754     Result = V.getFloat();
13755     return true;
13756   }
13757 
13758   bool ZeroInitialization(const Expr *E) {
13759     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13760     return true;
13761   }
13762 
13763   bool VisitCallExpr(const CallExpr *E);
13764 
13765   bool VisitUnaryOperator(const UnaryOperator *E);
13766   bool VisitBinaryOperator(const BinaryOperator *E);
13767   bool VisitFloatingLiteral(const FloatingLiteral *E);
13768   bool VisitCastExpr(const CastExpr *E);
13769 
13770   bool VisitUnaryReal(const UnaryOperator *E);
13771   bool VisitUnaryImag(const UnaryOperator *E);
13772 
13773   // FIXME: Missing: array subscript of vector, member of vector
13774 };
13775 } // end anonymous namespace
13776 
13777 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13778   assert(!E->isValueDependent());
13779   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13780   return FloatExprEvaluator(Info, Result).Visit(E);
13781 }
13782 
13783 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13784                                   QualType ResultTy,
13785                                   const Expr *Arg,
13786                                   bool SNaN,
13787                                   llvm::APFloat &Result) {
13788   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13789   if (!S) return false;
13790 
13791   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13792 
13793   llvm::APInt fill;
13794 
13795   // Treat empty strings as if they were zero.
13796   if (S->getString().empty())
13797     fill = llvm::APInt(32, 0);
13798   else if (S->getString().getAsInteger(0, fill))
13799     return false;
13800 
13801   if (Context.getTargetInfo().isNan2008()) {
13802     if (SNaN)
13803       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13804     else
13805       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13806   } else {
13807     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13808     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13809     // a different encoding to what became a standard in 2008, and for pre-
13810     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13811     // sNaN. This is now known as "legacy NaN" encoding.
13812     if (SNaN)
13813       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13814     else
13815       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13816   }
13817 
13818   return true;
13819 }
13820 
13821 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13822   switch (E->getBuiltinCallee()) {
13823   default:
13824     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13825 
13826   case Builtin::BI__builtin_huge_val:
13827   case Builtin::BI__builtin_huge_valf:
13828   case Builtin::BI__builtin_huge_vall:
13829   case Builtin::BI__builtin_huge_valf128:
13830   case Builtin::BI__builtin_inf:
13831   case Builtin::BI__builtin_inff:
13832   case Builtin::BI__builtin_infl:
13833   case Builtin::BI__builtin_inff128: {
13834     const llvm::fltSemantics &Sem =
13835       Info.Ctx.getFloatTypeSemantics(E->getType());
13836     Result = llvm::APFloat::getInf(Sem);
13837     return true;
13838   }
13839 
13840   case Builtin::BI__builtin_nans:
13841   case Builtin::BI__builtin_nansf:
13842   case Builtin::BI__builtin_nansl:
13843   case Builtin::BI__builtin_nansf128:
13844     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13845                                true, Result))
13846       return Error(E);
13847     return true;
13848 
13849   case Builtin::BI__builtin_nan:
13850   case Builtin::BI__builtin_nanf:
13851   case Builtin::BI__builtin_nanl:
13852   case Builtin::BI__builtin_nanf128:
13853     // If this is __builtin_nan() turn this into a nan, otherwise we
13854     // can't constant fold it.
13855     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13856                                false, Result))
13857       return Error(E);
13858     return true;
13859 
13860   case Builtin::BI__builtin_fabs:
13861   case Builtin::BI__builtin_fabsf:
13862   case Builtin::BI__builtin_fabsl:
13863   case Builtin::BI__builtin_fabsf128:
13864     // The C standard says "fabs raises no floating-point exceptions,
13865     // even if x is a signaling NaN. The returned value is independent of
13866     // the current rounding direction mode."  Therefore constant folding can
13867     // proceed without regard to the floating point settings.
13868     // Reference, WG14 N2478 F.10.4.3
13869     if (!EvaluateFloat(E->getArg(0), Result, Info))
13870       return false;
13871 
13872     if (Result.isNegative())
13873       Result.changeSign();
13874     return true;
13875 
13876   case Builtin::BI__arithmetic_fence:
13877     return EvaluateFloat(E->getArg(0), Result, Info);
13878 
13879   // FIXME: Builtin::BI__builtin_powi
13880   // FIXME: Builtin::BI__builtin_powif
13881   // FIXME: Builtin::BI__builtin_powil
13882 
13883   case Builtin::BI__builtin_copysign:
13884   case Builtin::BI__builtin_copysignf:
13885   case Builtin::BI__builtin_copysignl:
13886   case Builtin::BI__builtin_copysignf128: {
13887     APFloat RHS(0.);
13888     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13889         !EvaluateFloat(E->getArg(1), RHS, Info))
13890       return false;
13891     Result.copySign(RHS);
13892     return true;
13893   }
13894   }
13895 }
13896 
13897 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13898   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13899     ComplexValue CV;
13900     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13901       return false;
13902     Result = CV.FloatReal;
13903     return true;
13904   }
13905 
13906   return Visit(E->getSubExpr());
13907 }
13908 
13909 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13910   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13911     ComplexValue CV;
13912     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13913       return false;
13914     Result = CV.FloatImag;
13915     return true;
13916   }
13917 
13918   VisitIgnoredValue(E->getSubExpr());
13919   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13920   Result = llvm::APFloat::getZero(Sem);
13921   return true;
13922 }
13923 
13924 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13925   switch (E->getOpcode()) {
13926   default: return Error(E);
13927   case UO_Plus:
13928     return EvaluateFloat(E->getSubExpr(), Result, Info);
13929   case UO_Minus:
13930     // In C standard, WG14 N2478 F.3 p4
13931     // "the unary - raises no floating point exceptions,
13932     // even if the operand is signalling."
13933     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13934       return false;
13935     Result.changeSign();
13936     return true;
13937   }
13938 }
13939 
13940 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13941   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13942     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13943 
13944   APFloat RHS(0.0);
13945   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13946   if (!LHSOK && !Info.noteFailure())
13947     return false;
13948   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13949          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13950 }
13951 
13952 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13953   Result = E->getValue();
13954   return true;
13955 }
13956 
13957 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13958   const Expr* SubExpr = E->getSubExpr();
13959 
13960   switch (E->getCastKind()) {
13961   default:
13962     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13963 
13964   case CK_IntegralToFloating: {
13965     APSInt IntResult;
13966     const FPOptions FPO = E->getFPFeaturesInEffect(
13967                                   Info.Ctx.getLangOpts());
13968     return EvaluateInteger(SubExpr, IntResult, Info) &&
13969            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13970                                 IntResult, E->getType(), Result);
13971   }
13972 
13973   case CK_FixedPointToFloating: {
13974     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13975     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13976       return false;
13977     Result =
13978         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13979     return true;
13980   }
13981 
13982   case CK_FloatingCast: {
13983     if (!Visit(SubExpr))
13984       return false;
13985     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13986                                   Result);
13987   }
13988 
13989   case CK_FloatingComplexToReal: {
13990     ComplexValue V;
13991     if (!EvaluateComplex(SubExpr, V, Info))
13992       return false;
13993     Result = V.getComplexFloatReal();
13994     return true;
13995   }
13996   }
13997 }
13998 
13999 //===----------------------------------------------------------------------===//
14000 // Complex Evaluation (for float and integer)
14001 //===----------------------------------------------------------------------===//
14002 
14003 namespace {
14004 class ComplexExprEvaluator
14005   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14006   ComplexValue &Result;
14007 
14008 public:
14009   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14010     : ExprEvaluatorBaseTy(info), Result(Result) {}
14011 
14012   bool Success(const APValue &V, const Expr *e) {
14013     Result.setFrom(V);
14014     return true;
14015   }
14016 
14017   bool ZeroInitialization(const Expr *E);
14018 
14019   //===--------------------------------------------------------------------===//
14020   //                            Visitor Methods
14021   //===--------------------------------------------------------------------===//
14022 
14023   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14024   bool VisitCastExpr(const CastExpr *E);
14025   bool VisitBinaryOperator(const BinaryOperator *E);
14026   bool VisitUnaryOperator(const UnaryOperator *E);
14027   bool VisitInitListExpr(const InitListExpr *E);
14028   bool VisitCallExpr(const CallExpr *E);
14029 };
14030 } // end anonymous namespace
14031 
14032 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14033                             EvalInfo &Info) {
14034   assert(!E->isValueDependent());
14035   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14036   return ComplexExprEvaluator(Info, Result).Visit(E);
14037 }
14038 
14039 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14040   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14041   if (ElemTy->isRealFloatingType()) {
14042     Result.makeComplexFloat();
14043     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14044     Result.FloatReal = Zero;
14045     Result.FloatImag = Zero;
14046   } else {
14047     Result.makeComplexInt();
14048     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14049     Result.IntReal = Zero;
14050     Result.IntImag = Zero;
14051   }
14052   return true;
14053 }
14054 
14055 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14056   const Expr* SubExpr = E->getSubExpr();
14057 
14058   if (SubExpr->getType()->isRealFloatingType()) {
14059     Result.makeComplexFloat();
14060     APFloat &Imag = Result.FloatImag;
14061     if (!EvaluateFloat(SubExpr, Imag, Info))
14062       return false;
14063 
14064     Result.FloatReal = APFloat(Imag.getSemantics());
14065     return true;
14066   } else {
14067     assert(SubExpr->getType()->isIntegerType() &&
14068            "Unexpected imaginary literal.");
14069 
14070     Result.makeComplexInt();
14071     APSInt &Imag = Result.IntImag;
14072     if (!EvaluateInteger(SubExpr, Imag, Info))
14073       return false;
14074 
14075     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14076     return true;
14077   }
14078 }
14079 
14080 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14081 
14082   switch (E->getCastKind()) {
14083   case CK_BitCast:
14084   case CK_BaseToDerived:
14085   case CK_DerivedToBase:
14086   case CK_UncheckedDerivedToBase:
14087   case CK_Dynamic:
14088   case CK_ToUnion:
14089   case CK_ArrayToPointerDecay:
14090   case CK_FunctionToPointerDecay:
14091   case CK_NullToPointer:
14092   case CK_NullToMemberPointer:
14093   case CK_BaseToDerivedMemberPointer:
14094   case CK_DerivedToBaseMemberPointer:
14095   case CK_MemberPointerToBoolean:
14096   case CK_ReinterpretMemberPointer:
14097   case CK_ConstructorConversion:
14098   case CK_IntegralToPointer:
14099   case CK_PointerToIntegral:
14100   case CK_PointerToBoolean:
14101   case CK_ToVoid:
14102   case CK_VectorSplat:
14103   case CK_IntegralCast:
14104   case CK_BooleanToSignedIntegral:
14105   case CK_IntegralToBoolean:
14106   case CK_IntegralToFloating:
14107   case CK_FloatingToIntegral:
14108   case CK_FloatingToBoolean:
14109   case CK_FloatingCast:
14110   case CK_CPointerToObjCPointerCast:
14111   case CK_BlockPointerToObjCPointerCast:
14112   case CK_AnyPointerToBlockPointerCast:
14113   case CK_ObjCObjectLValueCast:
14114   case CK_FloatingComplexToReal:
14115   case CK_FloatingComplexToBoolean:
14116   case CK_IntegralComplexToReal:
14117   case CK_IntegralComplexToBoolean:
14118   case CK_ARCProduceObject:
14119   case CK_ARCConsumeObject:
14120   case CK_ARCReclaimReturnedObject:
14121   case CK_ARCExtendBlockObject:
14122   case CK_CopyAndAutoreleaseBlockObject:
14123   case CK_BuiltinFnToFnPtr:
14124   case CK_ZeroToOCLOpaqueType:
14125   case CK_NonAtomicToAtomic:
14126   case CK_AddressSpaceConversion:
14127   case CK_IntToOCLSampler:
14128   case CK_FloatingToFixedPoint:
14129   case CK_FixedPointToFloating:
14130   case CK_FixedPointCast:
14131   case CK_FixedPointToBoolean:
14132   case CK_FixedPointToIntegral:
14133   case CK_IntegralToFixedPoint:
14134   case CK_MatrixCast:
14135     llvm_unreachable("invalid cast kind for complex value");
14136 
14137   case CK_LValueToRValue:
14138   case CK_AtomicToNonAtomic:
14139   case CK_NoOp:
14140   case CK_LValueToRValueBitCast:
14141     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14142 
14143   case CK_Dependent:
14144   case CK_LValueBitCast:
14145   case CK_UserDefinedConversion:
14146     return Error(E);
14147 
14148   case CK_FloatingRealToComplex: {
14149     APFloat &Real = Result.FloatReal;
14150     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14151       return false;
14152 
14153     Result.makeComplexFloat();
14154     Result.FloatImag = APFloat(Real.getSemantics());
14155     return true;
14156   }
14157 
14158   case CK_FloatingComplexCast: {
14159     if (!Visit(E->getSubExpr()))
14160       return false;
14161 
14162     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14163     QualType From
14164       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14165 
14166     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14167            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14168   }
14169 
14170   case CK_FloatingComplexToIntegralComplex: {
14171     if (!Visit(E->getSubExpr()))
14172       return false;
14173 
14174     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14175     QualType From
14176       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14177     Result.makeComplexInt();
14178     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14179                                 To, Result.IntReal) &&
14180            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14181                                 To, Result.IntImag);
14182   }
14183 
14184   case CK_IntegralRealToComplex: {
14185     APSInt &Real = Result.IntReal;
14186     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14187       return false;
14188 
14189     Result.makeComplexInt();
14190     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14191     return true;
14192   }
14193 
14194   case CK_IntegralComplexCast: {
14195     if (!Visit(E->getSubExpr()))
14196       return false;
14197 
14198     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14199     QualType From
14200       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14201 
14202     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14203     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14204     return true;
14205   }
14206 
14207   case CK_IntegralComplexToFloatingComplex: {
14208     if (!Visit(E->getSubExpr()))
14209       return false;
14210 
14211     const FPOptions FPO = E->getFPFeaturesInEffect(
14212                                   Info.Ctx.getLangOpts());
14213     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14214     QualType From
14215       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14216     Result.makeComplexFloat();
14217     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14218                                 To, Result.FloatReal) &&
14219            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14220                                 To, Result.FloatImag);
14221   }
14222   }
14223 
14224   llvm_unreachable("unknown cast resulting in complex value");
14225 }
14226 
14227 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14228   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14229     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14230 
14231   // Track whether the LHS or RHS is real at the type system level. When this is
14232   // the case we can simplify our evaluation strategy.
14233   bool LHSReal = false, RHSReal = false;
14234 
14235   bool LHSOK;
14236   if (E->getLHS()->getType()->isRealFloatingType()) {
14237     LHSReal = true;
14238     APFloat &Real = Result.FloatReal;
14239     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14240     if (LHSOK) {
14241       Result.makeComplexFloat();
14242       Result.FloatImag = APFloat(Real.getSemantics());
14243     }
14244   } else {
14245     LHSOK = Visit(E->getLHS());
14246   }
14247   if (!LHSOK && !Info.noteFailure())
14248     return false;
14249 
14250   ComplexValue RHS;
14251   if (E->getRHS()->getType()->isRealFloatingType()) {
14252     RHSReal = true;
14253     APFloat &Real = RHS.FloatReal;
14254     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14255       return false;
14256     RHS.makeComplexFloat();
14257     RHS.FloatImag = APFloat(Real.getSemantics());
14258   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14259     return false;
14260 
14261   assert(!(LHSReal && RHSReal) &&
14262          "Cannot have both operands of a complex operation be real.");
14263   switch (E->getOpcode()) {
14264   default: return Error(E);
14265   case BO_Add:
14266     if (Result.isComplexFloat()) {
14267       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14268                                        APFloat::rmNearestTiesToEven);
14269       if (LHSReal)
14270         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14271       else if (!RHSReal)
14272         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14273                                          APFloat::rmNearestTiesToEven);
14274     } else {
14275       Result.getComplexIntReal() += RHS.getComplexIntReal();
14276       Result.getComplexIntImag() += RHS.getComplexIntImag();
14277     }
14278     break;
14279   case BO_Sub:
14280     if (Result.isComplexFloat()) {
14281       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14282                                             APFloat::rmNearestTiesToEven);
14283       if (LHSReal) {
14284         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14285         Result.getComplexFloatImag().changeSign();
14286       } else if (!RHSReal) {
14287         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14288                                               APFloat::rmNearestTiesToEven);
14289       }
14290     } else {
14291       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14292       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14293     }
14294     break;
14295   case BO_Mul:
14296     if (Result.isComplexFloat()) {
14297       // This is an implementation of complex multiplication according to the
14298       // constraints laid out in C11 Annex G. The implementation uses the
14299       // following naming scheme:
14300       //   (a + ib) * (c + id)
14301       ComplexValue LHS = Result;
14302       APFloat &A = LHS.getComplexFloatReal();
14303       APFloat &B = LHS.getComplexFloatImag();
14304       APFloat &C = RHS.getComplexFloatReal();
14305       APFloat &D = RHS.getComplexFloatImag();
14306       APFloat &ResR = Result.getComplexFloatReal();
14307       APFloat &ResI = Result.getComplexFloatImag();
14308       if (LHSReal) {
14309         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14310         ResR = A * C;
14311         ResI = A * D;
14312       } else if (RHSReal) {
14313         ResR = C * A;
14314         ResI = C * B;
14315       } else {
14316         // In the fully general case, we need to handle NaNs and infinities
14317         // robustly.
14318         APFloat AC = A * C;
14319         APFloat BD = B * D;
14320         APFloat AD = A * D;
14321         APFloat BC = B * C;
14322         ResR = AC - BD;
14323         ResI = AD + BC;
14324         if (ResR.isNaN() && ResI.isNaN()) {
14325           bool Recalc = false;
14326           if (A.isInfinity() || B.isInfinity()) {
14327             A = APFloat::copySign(
14328                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14329             B = APFloat::copySign(
14330                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14331             if (C.isNaN())
14332               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14333             if (D.isNaN())
14334               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14335             Recalc = true;
14336           }
14337           if (C.isInfinity() || D.isInfinity()) {
14338             C = APFloat::copySign(
14339                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14340             D = APFloat::copySign(
14341                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14342             if (A.isNaN())
14343               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14344             if (B.isNaN())
14345               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14346             Recalc = true;
14347           }
14348           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14349                           AD.isInfinity() || BC.isInfinity())) {
14350             if (A.isNaN())
14351               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14352             if (B.isNaN())
14353               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14354             if (C.isNaN())
14355               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14356             if (D.isNaN())
14357               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14358             Recalc = true;
14359           }
14360           if (Recalc) {
14361             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14362             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14363           }
14364         }
14365       }
14366     } else {
14367       ComplexValue LHS = Result;
14368       Result.getComplexIntReal() =
14369         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14370          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14371       Result.getComplexIntImag() =
14372         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14373          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14374     }
14375     break;
14376   case BO_Div:
14377     if (Result.isComplexFloat()) {
14378       // This is an implementation of complex division according to the
14379       // constraints laid out in C11 Annex G. The implementation uses the
14380       // following naming scheme:
14381       //   (a + ib) / (c + id)
14382       ComplexValue LHS = Result;
14383       APFloat &A = LHS.getComplexFloatReal();
14384       APFloat &B = LHS.getComplexFloatImag();
14385       APFloat &C = RHS.getComplexFloatReal();
14386       APFloat &D = RHS.getComplexFloatImag();
14387       APFloat &ResR = Result.getComplexFloatReal();
14388       APFloat &ResI = Result.getComplexFloatImag();
14389       if (RHSReal) {
14390         ResR = A / C;
14391         ResI = B / C;
14392       } else {
14393         if (LHSReal) {
14394           // No real optimizations we can do here, stub out with zero.
14395           B = APFloat::getZero(A.getSemantics());
14396         }
14397         int DenomLogB = 0;
14398         APFloat MaxCD = maxnum(abs(C), abs(D));
14399         if (MaxCD.isFinite()) {
14400           DenomLogB = ilogb(MaxCD);
14401           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14402           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14403         }
14404         APFloat Denom = C * C + D * D;
14405         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14406                       APFloat::rmNearestTiesToEven);
14407         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14408                       APFloat::rmNearestTiesToEven);
14409         if (ResR.isNaN() && ResI.isNaN()) {
14410           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14411             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14412             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14413           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14414                      D.isFinite()) {
14415             A = APFloat::copySign(
14416                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14417             B = APFloat::copySign(
14418                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14419             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14420             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14421           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14422             C = APFloat::copySign(
14423                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14424             D = APFloat::copySign(
14425                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14426             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14427             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14428           }
14429         }
14430       }
14431     } else {
14432       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14433         return Error(E, diag::note_expr_divide_by_zero);
14434 
14435       ComplexValue LHS = Result;
14436       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14437         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14438       Result.getComplexIntReal() =
14439         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14440          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14441       Result.getComplexIntImag() =
14442         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14443          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14444     }
14445     break;
14446   }
14447 
14448   return true;
14449 }
14450 
14451 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14452   // Get the operand value into 'Result'.
14453   if (!Visit(E->getSubExpr()))
14454     return false;
14455 
14456   switch (E->getOpcode()) {
14457   default:
14458     return Error(E);
14459   case UO_Extension:
14460     return true;
14461   case UO_Plus:
14462     // The result is always just the subexpr.
14463     return true;
14464   case UO_Minus:
14465     if (Result.isComplexFloat()) {
14466       Result.getComplexFloatReal().changeSign();
14467       Result.getComplexFloatImag().changeSign();
14468     }
14469     else {
14470       Result.getComplexIntReal() = -Result.getComplexIntReal();
14471       Result.getComplexIntImag() = -Result.getComplexIntImag();
14472     }
14473     return true;
14474   case UO_Not:
14475     if (Result.isComplexFloat())
14476       Result.getComplexFloatImag().changeSign();
14477     else
14478       Result.getComplexIntImag() = -Result.getComplexIntImag();
14479     return true;
14480   }
14481 }
14482 
14483 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14484   if (E->getNumInits() == 2) {
14485     if (E->getType()->isComplexType()) {
14486       Result.makeComplexFloat();
14487       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14488         return false;
14489       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14490         return false;
14491     } else {
14492       Result.makeComplexInt();
14493       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14494         return false;
14495       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14496         return false;
14497     }
14498     return true;
14499   }
14500   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14501 }
14502 
14503 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14504   switch (E->getBuiltinCallee()) {
14505   case Builtin::BI__builtin_complex:
14506     Result.makeComplexFloat();
14507     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14508       return false;
14509     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14510       return false;
14511     return true;
14512 
14513   default:
14514     break;
14515   }
14516 
14517   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14518 }
14519 
14520 //===----------------------------------------------------------------------===//
14521 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14522 // implicit conversion.
14523 //===----------------------------------------------------------------------===//
14524 
14525 namespace {
14526 class AtomicExprEvaluator :
14527     public ExprEvaluatorBase<AtomicExprEvaluator> {
14528   const LValue *This;
14529   APValue &Result;
14530 public:
14531   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14532       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14533 
14534   bool Success(const APValue &V, const Expr *E) {
14535     Result = V;
14536     return true;
14537   }
14538 
14539   bool ZeroInitialization(const Expr *E) {
14540     ImplicitValueInitExpr VIE(
14541         E->getType()->castAs<AtomicType>()->getValueType());
14542     // For atomic-qualified class (and array) types in C++, initialize the
14543     // _Atomic-wrapped subobject directly, in-place.
14544     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14545                 : Evaluate(Result, Info, &VIE);
14546   }
14547 
14548   bool VisitCastExpr(const CastExpr *E) {
14549     switch (E->getCastKind()) {
14550     default:
14551       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14552     case CK_NonAtomicToAtomic:
14553       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14554                   : Evaluate(Result, Info, E->getSubExpr());
14555     }
14556   }
14557 };
14558 } // end anonymous namespace
14559 
14560 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14561                            EvalInfo &Info) {
14562   assert(!E->isValueDependent());
14563   assert(E->isPRValue() && E->getType()->isAtomicType());
14564   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14565 }
14566 
14567 //===----------------------------------------------------------------------===//
14568 // Void expression evaluation, primarily for a cast to void on the LHS of a
14569 // comma operator
14570 //===----------------------------------------------------------------------===//
14571 
14572 namespace {
14573 class VoidExprEvaluator
14574   : public ExprEvaluatorBase<VoidExprEvaluator> {
14575 public:
14576   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14577 
14578   bool Success(const APValue &V, const Expr *e) { return true; }
14579 
14580   bool ZeroInitialization(const Expr *E) { return true; }
14581 
14582   bool VisitCastExpr(const CastExpr *E) {
14583     switch (E->getCastKind()) {
14584     default:
14585       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14586     case CK_ToVoid:
14587       VisitIgnoredValue(E->getSubExpr());
14588       return true;
14589     }
14590   }
14591 
14592   bool VisitCallExpr(const CallExpr *E) {
14593     switch (E->getBuiltinCallee()) {
14594     case Builtin::BI__assume:
14595     case Builtin::BI__builtin_assume:
14596       // The argument is not evaluated!
14597       return true;
14598 
14599     case Builtin::BI__builtin_operator_delete:
14600       return HandleOperatorDeleteCall(Info, E);
14601 
14602     default:
14603       break;
14604     }
14605 
14606     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14607   }
14608 
14609   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14610 };
14611 } // end anonymous namespace
14612 
14613 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14614   // We cannot speculatively evaluate a delete expression.
14615   if (Info.SpeculativeEvaluationDepth)
14616     return false;
14617 
14618   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14619   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14620     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14621         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14622     return false;
14623   }
14624 
14625   const Expr *Arg = E->getArgument();
14626 
14627   LValue Pointer;
14628   if (!EvaluatePointer(Arg, Pointer, Info))
14629     return false;
14630   if (Pointer.Designator.Invalid)
14631     return false;
14632 
14633   // Deleting a null pointer has no effect.
14634   if (Pointer.isNullPointer()) {
14635     // This is the only case where we need to produce an extension warning:
14636     // the only other way we can succeed is if we find a dynamic allocation,
14637     // and we will have warned when we allocated it in that case.
14638     if (!Info.getLangOpts().CPlusPlus20)
14639       Info.CCEDiag(E, diag::note_constexpr_new);
14640     return true;
14641   }
14642 
14643   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14644       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14645   if (!Alloc)
14646     return false;
14647   QualType AllocType = Pointer.Base.getDynamicAllocType();
14648 
14649   // For the non-array case, the designator must be empty if the static type
14650   // does not have a virtual destructor.
14651   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14652       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14653     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14654         << Arg->getType()->getPointeeType() << AllocType;
14655     return false;
14656   }
14657 
14658   // For a class type with a virtual destructor, the selected operator delete
14659   // is the one looked up when building the destructor.
14660   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14661     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14662     if (VirtualDelete &&
14663         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14664       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14665           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14666       return false;
14667     }
14668   }
14669 
14670   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14671                          (*Alloc)->Value, AllocType))
14672     return false;
14673 
14674   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14675     // The element was already erased. This means the destructor call also
14676     // deleted the object.
14677     // FIXME: This probably results in undefined behavior before we get this
14678     // far, and should be diagnosed elsewhere first.
14679     Info.FFDiag(E, diag::note_constexpr_double_delete);
14680     return false;
14681   }
14682 
14683   return true;
14684 }
14685 
14686 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14687   assert(!E->isValueDependent());
14688   assert(E->isPRValue() && E->getType()->isVoidType());
14689   return VoidExprEvaluator(Info).Visit(E);
14690 }
14691 
14692 //===----------------------------------------------------------------------===//
14693 // Top level Expr::EvaluateAsRValue method.
14694 //===----------------------------------------------------------------------===//
14695 
14696 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14697   assert(!E->isValueDependent());
14698   // In C, function designators are not lvalues, but we evaluate them as if they
14699   // are.
14700   QualType T = E->getType();
14701   if (E->isGLValue() || T->isFunctionType()) {
14702     LValue LV;
14703     if (!EvaluateLValue(E, LV, Info))
14704       return false;
14705     LV.moveInto(Result);
14706   } else if (T->isVectorType()) {
14707     if (!EvaluateVector(E, Result, Info))
14708       return false;
14709   } else if (T->isIntegralOrEnumerationType()) {
14710     if (!IntExprEvaluator(Info, Result).Visit(E))
14711       return false;
14712   } else if (T->hasPointerRepresentation()) {
14713     LValue LV;
14714     if (!EvaluatePointer(E, LV, Info))
14715       return false;
14716     LV.moveInto(Result);
14717   } else if (T->isRealFloatingType()) {
14718     llvm::APFloat F(0.0);
14719     if (!EvaluateFloat(E, F, Info))
14720       return false;
14721     Result = APValue(F);
14722   } else if (T->isAnyComplexType()) {
14723     ComplexValue C;
14724     if (!EvaluateComplex(E, C, Info))
14725       return false;
14726     C.moveInto(Result);
14727   } else if (T->isFixedPointType()) {
14728     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14729   } else if (T->isMemberPointerType()) {
14730     MemberPtr P;
14731     if (!EvaluateMemberPointer(E, P, Info))
14732       return false;
14733     P.moveInto(Result);
14734     return true;
14735   } else if (T->isArrayType()) {
14736     LValue LV;
14737     APValue &Value =
14738         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14739     if (!EvaluateArray(E, LV, Value, Info))
14740       return false;
14741     Result = Value;
14742   } else if (T->isRecordType()) {
14743     LValue LV;
14744     APValue &Value =
14745         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14746     if (!EvaluateRecord(E, LV, Value, Info))
14747       return false;
14748     Result = Value;
14749   } else if (T->isVoidType()) {
14750     if (!Info.getLangOpts().CPlusPlus11)
14751       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14752         << E->getType();
14753     if (!EvaluateVoid(E, Info))
14754       return false;
14755   } else if (T->isAtomicType()) {
14756     QualType Unqual = T.getAtomicUnqualifiedType();
14757     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14758       LValue LV;
14759       APValue &Value = Info.CurrentCall->createTemporary(
14760           E, Unqual, ScopeKind::FullExpression, LV);
14761       if (!EvaluateAtomic(E, &LV, Value, Info))
14762         return false;
14763     } else {
14764       if (!EvaluateAtomic(E, nullptr, Result, Info))
14765         return false;
14766     }
14767   } else if (Info.getLangOpts().CPlusPlus11) {
14768     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14769     return false;
14770   } else {
14771     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14772     return false;
14773   }
14774 
14775   return true;
14776 }
14777 
14778 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14779 /// cases, the in-place evaluation is essential, since later initializers for
14780 /// an object can indirectly refer to subobjects which were initialized earlier.
14781 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14782                             const Expr *E, bool AllowNonLiteralTypes) {
14783   assert(!E->isValueDependent());
14784 
14785   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14786     return false;
14787 
14788   if (E->isPRValue()) {
14789     // Evaluate arrays and record types in-place, so that later initializers can
14790     // refer to earlier-initialized members of the object.
14791     QualType T = E->getType();
14792     if (T->isArrayType())
14793       return EvaluateArray(E, This, Result, Info);
14794     else if (T->isRecordType())
14795       return EvaluateRecord(E, This, Result, Info);
14796     else if (T->isAtomicType()) {
14797       QualType Unqual = T.getAtomicUnqualifiedType();
14798       if (Unqual->isArrayType() || Unqual->isRecordType())
14799         return EvaluateAtomic(E, &This, Result, Info);
14800     }
14801   }
14802 
14803   // For any other type, in-place evaluation is unimportant.
14804   return Evaluate(Result, Info, E);
14805 }
14806 
14807 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14808 /// lvalue-to-rvalue cast if it is an lvalue.
14809 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14810   assert(!E->isValueDependent());
14811   if (Info.EnableNewConstInterp) {
14812     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14813       return false;
14814   } else {
14815     if (E->getType().isNull())
14816       return false;
14817 
14818     if (!CheckLiteralType(Info, E))
14819       return false;
14820 
14821     if (!::Evaluate(Result, Info, E))
14822       return false;
14823 
14824     if (E->isGLValue()) {
14825       LValue LV;
14826       LV.setFrom(Info.Ctx, Result);
14827       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14828         return false;
14829     }
14830   }
14831 
14832   // Check this core constant expression is a constant expression.
14833   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14834                                  ConstantExprKind::Normal) &&
14835          CheckMemoryLeaks(Info);
14836 }
14837 
14838 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14839                                  const ASTContext &Ctx, bool &IsConst) {
14840   // Fast-path evaluations of integer literals, since we sometimes see files
14841   // containing vast quantities of these.
14842   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14843     Result.Val = APValue(APSInt(L->getValue(),
14844                                 L->getType()->isUnsignedIntegerType()));
14845     IsConst = true;
14846     return true;
14847   }
14848 
14849   // This case should be rare, but we need to check it before we check on
14850   // the type below.
14851   if (Exp->getType().isNull()) {
14852     IsConst = false;
14853     return true;
14854   }
14855 
14856   // FIXME: Evaluating values of large array and record types can cause
14857   // performance problems. Only do so in C++11 for now.
14858   if (Exp->isPRValue() &&
14859       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14860       !Ctx.getLangOpts().CPlusPlus11) {
14861     IsConst = false;
14862     return true;
14863   }
14864   return false;
14865 }
14866 
14867 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14868                                       Expr::SideEffectsKind SEK) {
14869   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14870          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14871 }
14872 
14873 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14874                              const ASTContext &Ctx, EvalInfo &Info) {
14875   assert(!E->isValueDependent());
14876   bool IsConst;
14877   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14878     return IsConst;
14879 
14880   return EvaluateAsRValue(Info, E, Result.Val);
14881 }
14882 
14883 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14884                           const ASTContext &Ctx,
14885                           Expr::SideEffectsKind AllowSideEffects,
14886                           EvalInfo &Info) {
14887   assert(!E->isValueDependent());
14888   if (!E->getType()->isIntegralOrEnumerationType())
14889     return false;
14890 
14891   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14892       !ExprResult.Val.isInt() ||
14893       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14894     return false;
14895 
14896   return true;
14897 }
14898 
14899 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14900                                  const ASTContext &Ctx,
14901                                  Expr::SideEffectsKind AllowSideEffects,
14902                                  EvalInfo &Info) {
14903   assert(!E->isValueDependent());
14904   if (!E->getType()->isFixedPointType())
14905     return false;
14906 
14907   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14908     return false;
14909 
14910   if (!ExprResult.Val.isFixedPoint() ||
14911       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14912     return false;
14913 
14914   return true;
14915 }
14916 
14917 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14918 /// any crazy technique (that has nothing to do with language standards) that
14919 /// we want to.  If this function returns true, it returns the folded constant
14920 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14921 /// will be applied to the result.
14922 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14923                             bool InConstantContext) const {
14924   assert(!isValueDependent() &&
14925          "Expression evaluator can't be called on a dependent expression.");
14926   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14927   Info.InConstantContext = InConstantContext;
14928   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14929 }
14930 
14931 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14932                                       bool InConstantContext) const {
14933   assert(!isValueDependent() &&
14934          "Expression evaluator can't be called on a dependent expression.");
14935   EvalResult Scratch;
14936   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14937          HandleConversionToBool(Scratch.Val, Result);
14938 }
14939 
14940 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14941                          SideEffectsKind AllowSideEffects,
14942                          bool InConstantContext) const {
14943   assert(!isValueDependent() &&
14944          "Expression evaluator can't be called on a dependent expression.");
14945   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14946   Info.InConstantContext = InConstantContext;
14947   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14948 }
14949 
14950 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14951                                 SideEffectsKind AllowSideEffects,
14952                                 bool InConstantContext) const {
14953   assert(!isValueDependent() &&
14954          "Expression evaluator can't be called on a dependent expression.");
14955   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14956   Info.InConstantContext = InConstantContext;
14957   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14958 }
14959 
14960 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14961                            SideEffectsKind AllowSideEffects,
14962                            bool InConstantContext) const {
14963   assert(!isValueDependent() &&
14964          "Expression evaluator can't be called on a dependent expression.");
14965 
14966   if (!getType()->isRealFloatingType())
14967     return false;
14968 
14969   EvalResult ExprResult;
14970   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14971       !ExprResult.Val.isFloat() ||
14972       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14973     return false;
14974 
14975   Result = ExprResult.Val.getFloat();
14976   return true;
14977 }
14978 
14979 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14980                             bool InConstantContext) const {
14981   assert(!isValueDependent() &&
14982          "Expression evaluator can't be called on a dependent expression.");
14983 
14984   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14985   Info.InConstantContext = InConstantContext;
14986   LValue LV;
14987   CheckedTemporaries CheckedTemps;
14988   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14989       Result.HasSideEffects ||
14990       !CheckLValueConstantExpression(Info, getExprLoc(),
14991                                      Ctx.getLValueReferenceType(getType()), LV,
14992                                      ConstantExprKind::Normal, CheckedTemps))
14993     return false;
14994 
14995   LV.moveInto(Result.Val);
14996   return true;
14997 }
14998 
14999 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15000                                 APValue DestroyedValue, QualType Type,
15001                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15002                                 bool IsConstantDestruction) {
15003   EvalInfo Info(Ctx, EStatus,
15004                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15005                                       : EvalInfo::EM_ConstantFold);
15006   Info.setEvaluatingDecl(Base, DestroyedValue,
15007                          EvalInfo::EvaluatingDeclKind::Dtor);
15008   Info.InConstantContext = IsConstantDestruction;
15009 
15010   LValue LVal;
15011   LVal.set(Base);
15012 
15013   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15014       EStatus.HasSideEffects)
15015     return false;
15016 
15017   if (!Info.discardCleanups())
15018     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15019 
15020   return true;
15021 }
15022 
15023 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15024                                   ConstantExprKind Kind) const {
15025   assert(!isValueDependent() &&
15026          "Expression evaluator can't be called on a dependent expression.");
15027 
15028   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15029   EvalInfo Info(Ctx, Result, EM);
15030   Info.InConstantContext = true;
15031 
15032   // The type of the object we're initializing is 'const T' for a class NTTP.
15033   QualType T = getType();
15034   if (Kind == ConstantExprKind::ClassTemplateArgument)
15035     T.addConst();
15036 
15037   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15038   // represent the result of the evaluation. CheckConstantExpression ensures
15039   // this doesn't escape.
15040   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15041   APValue::LValueBase Base(&BaseMTE);
15042 
15043   Info.setEvaluatingDecl(Base, Result.Val);
15044   LValue LVal;
15045   LVal.set(Base);
15046 
15047   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15048     return false;
15049 
15050   if (!Info.discardCleanups())
15051     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15052 
15053   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15054                                Result.Val, Kind))
15055     return false;
15056   if (!CheckMemoryLeaks(Info))
15057     return false;
15058 
15059   // If this is a class template argument, it's required to have constant
15060   // destruction too.
15061   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15062       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15063                             true) ||
15064        Result.HasSideEffects)) {
15065     // FIXME: Prefix a note to indicate that the problem is lack of constant
15066     // destruction.
15067     return false;
15068   }
15069 
15070   return true;
15071 }
15072 
15073 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15074                                  const VarDecl *VD,
15075                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15076                                  bool IsConstantInitialization) const {
15077   assert(!isValueDependent() &&
15078          "Expression evaluator can't be called on a dependent expression.");
15079 
15080   // FIXME: Evaluating initializers for large array and record types can cause
15081   // performance problems. Only do so in C++11 for now.
15082   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15083       !Ctx.getLangOpts().CPlusPlus11)
15084     return false;
15085 
15086   Expr::EvalStatus EStatus;
15087   EStatus.Diag = &Notes;
15088 
15089   EvalInfo Info(Ctx, EStatus,
15090                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15091                     ? EvalInfo::EM_ConstantExpression
15092                     : EvalInfo::EM_ConstantFold);
15093   Info.setEvaluatingDecl(VD, Value);
15094   Info.InConstantContext = IsConstantInitialization;
15095 
15096   SourceLocation DeclLoc = VD->getLocation();
15097   QualType DeclTy = VD->getType();
15098 
15099   if (Info.EnableNewConstInterp) {
15100     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15101     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15102       return false;
15103   } else {
15104     LValue LVal;
15105     LVal.set(VD);
15106 
15107     if (!EvaluateInPlace(Value, Info, LVal, this,
15108                          /*AllowNonLiteralTypes=*/true) ||
15109         EStatus.HasSideEffects)
15110       return false;
15111 
15112     // At this point, any lifetime-extended temporaries are completely
15113     // initialized.
15114     Info.performLifetimeExtension();
15115 
15116     if (!Info.discardCleanups())
15117       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15118   }
15119   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15120                                  ConstantExprKind::Normal) &&
15121          CheckMemoryLeaks(Info);
15122 }
15123 
15124 bool VarDecl::evaluateDestruction(
15125     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15126   Expr::EvalStatus EStatus;
15127   EStatus.Diag = &Notes;
15128 
15129   // Only treat the destruction as constant destruction if we formally have
15130   // constant initialization (or are usable in a constant expression).
15131   bool IsConstantDestruction = hasConstantInitialization();
15132 
15133   // Make a copy of the value for the destructor to mutate, if we know it.
15134   // Otherwise, treat the value as default-initialized; if the destructor works
15135   // anyway, then the destruction is constant (and must be essentially empty).
15136   APValue DestroyedValue;
15137   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15138     DestroyedValue = *getEvaluatedValue();
15139   else if (!getDefaultInitValue(getType(), DestroyedValue))
15140     return false;
15141 
15142   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15143                            getType(), getLocation(), EStatus,
15144                            IsConstantDestruction) ||
15145       EStatus.HasSideEffects)
15146     return false;
15147 
15148   ensureEvaluatedStmt()->HasConstantDestruction = true;
15149   return true;
15150 }
15151 
15152 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15153 /// constant folded, but discard the result.
15154 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15155   assert(!isValueDependent() &&
15156          "Expression evaluator can't be called on a dependent expression.");
15157 
15158   EvalResult Result;
15159   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15160          !hasUnacceptableSideEffect(Result, SEK);
15161 }
15162 
15163 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15164                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15165   assert(!isValueDependent() &&
15166          "Expression evaluator can't be called on a dependent expression.");
15167 
15168   EvalResult EVResult;
15169   EVResult.Diag = Diag;
15170   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15171   Info.InConstantContext = true;
15172 
15173   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15174   (void)Result;
15175   assert(Result && "Could not evaluate expression");
15176   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15177 
15178   return EVResult.Val.getInt();
15179 }
15180 
15181 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15182     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15183   assert(!isValueDependent() &&
15184          "Expression evaluator can't be called on a dependent expression.");
15185 
15186   EvalResult EVResult;
15187   EVResult.Diag = Diag;
15188   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15189   Info.InConstantContext = true;
15190   Info.CheckingForUndefinedBehavior = true;
15191 
15192   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15193   (void)Result;
15194   assert(Result && "Could not evaluate expression");
15195   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15196 
15197   return EVResult.Val.getInt();
15198 }
15199 
15200 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15201   assert(!isValueDependent() &&
15202          "Expression evaluator can't be called on a dependent expression.");
15203 
15204   bool IsConst;
15205   EvalResult EVResult;
15206   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15207     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15208     Info.CheckingForUndefinedBehavior = true;
15209     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15210   }
15211 }
15212 
15213 bool Expr::EvalResult::isGlobalLValue() const {
15214   assert(Val.isLValue());
15215   return IsGlobalLValue(Val.getLValueBase());
15216 }
15217 
15218 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15219 /// an integer constant expression.
15220 
15221 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15222 /// comma, etc
15223 
15224 // CheckICE - This function does the fundamental ICE checking: the returned
15225 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15226 // and a (possibly null) SourceLocation indicating the location of the problem.
15227 //
15228 // Note that to reduce code duplication, this helper does no evaluation
15229 // itself; the caller checks whether the expression is evaluatable, and
15230 // in the rare cases where CheckICE actually cares about the evaluated
15231 // value, it calls into Evaluate.
15232 
15233 namespace {
15234 
15235 enum ICEKind {
15236   /// This expression is an ICE.
15237   IK_ICE,
15238   /// This expression is not an ICE, but if it isn't evaluated, it's
15239   /// a legal subexpression for an ICE. This return value is used to handle
15240   /// the comma operator in C99 mode, and non-constant subexpressions.
15241   IK_ICEIfUnevaluated,
15242   /// This expression is not an ICE, and is not a legal subexpression for one.
15243   IK_NotICE
15244 };
15245 
15246 struct ICEDiag {
15247   ICEKind Kind;
15248   SourceLocation Loc;
15249 
15250   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15251 };
15252 
15253 }
15254 
15255 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15256 
15257 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15258 
15259 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15260   Expr::EvalResult EVResult;
15261   Expr::EvalStatus Status;
15262   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15263 
15264   Info.InConstantContext = true;
15265   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15266       !EVResult.Val.isInt())
15267     return ICEDiag(IK_NotICE, E->getBeginLoc());
15268 
15269   return NoDiag();
15270 }
15271 
15272 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15273   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15274   if (!E->getType()->isIntegralOrEnumerationType())
15275     return ICEDiag(IK_NotICE, E->getBeginLoc());
15276 
15277   switch (E->getStmtClass()) {
15278 #define ABSTRACT_STMT(Node)
15279 #define STMT(Node, Base) case Expr::Node##Class:
15280 #define EXPR(Node, Base)
15281 #include "clang/AST/StmtNodes.inc"
15282   case Expr::PredefinedExprClass:
15283   case Expr::FloatingLiteralClass:
15284   case Expr::ImaginaryLiteralClass:
15285   case Expr::StringLiteralClass:
15286   case Expr::ArraySubscriptExprClass:
15287   case Expr::MatrixSubscriptExprClass:
15288   case Expr::OMPArraySectionExprClass:
15289   case Expr::OMPArrayShapingExprClass:
15290   case Expr::OMPIteratorExprClass:
15291   case Expr::MemberExprClass:
15292   case Expr::CompoundAssignOperatorClass:
15293   case Expr::CompoundLiteralExprClass:
15294   case Expr::ExtVectorElementExprClass:
15295   case Expr::DesignatedInitExprClass:
15296   case Expr::ArrayInitLoopExprClass:
15297   case Expr::ArrayInitIndexExprClass:
15298   case Expr::NoInitExprClass:
15299   case Expr::DesignatedInitUpdateExprClass:
15300   case Expr::ImplicitValueInitExprClass:
15301   case Expr::ParenListExprClass:
15302   case Expr::VAArgExprClass:
15303   case Expr::AddrLabelExprClass:
15304   case Expr::StmtExprClass:
15305   case Expr::CXXMemberCallExprClass:
15306   case Expr::CUDAKernelCallExprClass:
15307   case Expr::CXXAddrspaceCastExprClass:
15308   case Expr::CXXDynamicCastExprClass:
15309   case Expr::CXXTypeidExprClass:
15310   case Expr::CXXUuidofExprClass:
15311   case Expr::MSPropertyRefExprClass:
15312   case Expr::MSPropertySubscriptExprClass:
15313   case Expr::CXXNullPtrLiteralExprClass:
15314   case Expr::UserDefinedLiteralClass:
15315   case Expr::CXXThisExprClass:
15316   case Expr::CXXThrowExprClass:
15317   case Expr::CXXNewExprClass:
15318   case Expr::CXXDeleteExprClass:
15319   case Expr::CXXPseudoDestructorExprClass:
15320   case Expr::UnresolvedLookupExprClass:
15321   case Expr::TypoExprClass:
15322   case Expr::RecoveryExprClass:
15323   case Expr::DependentScopeDeclRefExprClass:
15324   case Expr::CXXConstructExprClass:
15325   case Expr::CXXInheritedCtorInitExprClass:
15326   case Expr::CXXStdInitializerListExprClass:
15327   case Expr::CXXBindTemporaryExprClass:
15328   case Expr::ExprWithCleanupsClass:
15329   case Expr::CXXTemporaryObjectExprClass:
15330   case Expr::CXXUnresolvedConstructExprClass:
15331   case Expr::CXXDependentScopeMemberExprClass:
15332   case Expr::UnresolvedMemberExprClass:
15333   case Expr::ObjCStringLiteralClass:
15334   case Expr::ObjCBoxedExprClass:
15335   case Expr::ObjCArrayLiteralClass:
15336   case Expr::ObjCDictionaryLiteralClass:
15337   case Expr::ObjCEncodeExprClass:
15338   case Expr::ObjCMessageExprClass:
15339   case Expr::ObjCSelectorExprClass:
15340   case Expr::ObjCProtocolExprClass:
15341   case Expr::ObjCIvarRefExprClass:
15342   case Expr::ObjCPropertyRefExprClass:
15343   case Expr::ObjCSubscriptRefExprClass:
15344   case Expr::ObjCIsaExprClass:
15345   case Expr::ObjCAvailabilityCheckExprClass:
15346   case Expr::ShuffleVectorExprClass:
15347   case Expr::ConvertVectorExprClass:
15348   case Expr::BlockExprClass:
15349   case Expr::NoStmtClass:
15350   case Expr::OpaqueValueExprClass:
15351   case Expr::PackExpansionExprClass:
15352   case Expr::SubstNonTypeTemplateParmPackExprClass:
15353   case Expr::FunctionParmPackExprClass:
15354   case Expr::AsTypeExprClass:
15355   case Expr::ObjCIndirectCopyRestoreExprClass:
15356   case Expr::MaterializeTemporaryExprClass:
15357   case Expr::PseudoObjectExprClass:
15358   case Expr::AtomicExprClass:
15359   case Expr::LambdaExprClass:
15360   case Expr::CXXFoldExprClass:
15361   case Expr::CoawaitExprClass:
15362   case Expr::DependentCoawaitExprClass:
15363   case Expr::CoyieldExprClass:
15364   case Expr::SYCLUniqueStableNameExprClass:
15365     return ICEDiag(IK_NotICE, E->getBeginLoc());
15366 
15367   case Expr::InitListExprClass: {
15368     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15369     // form "T x = { a };" is equivalent to "T x = a;".
15370     // Unless we're initializing a reference, T is a scalar as it is known to be
15371     // of integral or enumeration type.
15372     if (E->isPRValue())
15373       if (cast<InitListExpr>(E)->getNumInits() == 1)
15374         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15375     return ICEDiag(IK_NotICE, E->getBeginLoc());
15376   }
15377 
15378   case Expr::SizeOfPackExprClass:
15379   case Expr::GNUNullExprClass:
15380   case Expr::SourceLocExprClass:
15381     return NoDiag();
15382 
15383   case Expr::SubstNonTypeTemplateParmExprClass:
15384     return
15385       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15386 
15387   case Expr::ConstantExprClass:
15388     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15389 
15390   case Expr::ParenExprClass:
15391     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15392   case Expr::GenericSelectionExprClass:
15393     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15394   case Expr::IntegerLiteralClass:
15395   case Expr::FixedPointLiteralClass:
15396   case Expr::CharacterLiteralClass:
15397   case Expr::ObjCBoolLiteralExprClass:
15398   case Expr::CXXBoolLiteralExprClass:
15399   case Expr::CXXScalarValueInitExprClass:
15400   case Expr::TypeTraitExprClass:
15401   case Expr::ConceptSpecializationExprClass:
15402   case Expr::RequiresExprClass:
15403   case Expr::ArrayTypeTraitExprClass:
15404   case Expr::ExpressionTraitExprClass:
15405   case Expr::CXXNoexceptExprClass:
15406     return NoDiag();
15407   case Expr::CallExprClass:
15408   case Expr::CXXOperatorCallExprClass: {
15409     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15410     // constant expressions, but they can never be ICEs because an ICE cannot
15411     // contain an operand of (pointer to) function type.
15412     const CallExpr *CE = cast<CallExpr>(E);
15413     if (CE->getBuiltinCallee())
15414       return CheckEvalInICE(E, Ctx);
15415     return ICEDiag(IK_NotICE, E->getBeginLoc());
15416   }
15417   case Expr::CXXRewrittenBinaryOperatorClass:
15418     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15419                     Ctx);
15420   case Expr::DeclRefExprClass: {
15421     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15422     if (isa<EnumConstantDecl>(D))
15423       return NoDiag();
15424 
15425     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15426     // integer variables in constant expressions:
15427     //
15428     // C++ 7.1.5.1p2
15429     //   A variable of non-volatile const-qualified integral or enumeration
15430     //   type initialized by an ICE can be used in ICEs.
15431     //
15432     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15433     // that mode, use of reference variables should not be allowed.
15434     const VarDecl *VD = dyn_cast<VarDecl>(D);
15435     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15436         !VD->getType()->isReferenceType())
15437       return NoDiag();
15438 
15439     return ICEDiag(IK_NotICE, E->getBeginLoc());
15440   }
15441   case Expr::UnaryOperatorClass: {
15442     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15443     switch (Exp->getOpcode()) {
15444     case UO_PostInc:
15445     case UO_PostDec:
15446     case UO_PreInc:
15447     case UO_PreDec:
15448     case UO_AddrOf:
15449     case UO_Deref:
15450     case UO_Coawait:
15451       // C99 6.6/3 allows increment and decrement within unevaluated
15452       // subexpressions of constant expressions, but they can never be ICEs
15453       // because an ICE cannot contain an lvalue operand.
15454       return ICEDiag(IK_NotICE, E->getBeginLoc());
15455     case UO_Extension:
15456     case UO_LNot:
15457     case UO_Plus:
15458     case UO_Minus:
15459     case UO_Not:
15460     case UO_Real:
15461     case UO_Imag:
15462       return CheckICE(Exp->getSubExpr(), Ctx);
15463     }
15464     llvm_unreachable("invalid unary operator class");
15465   }
15466   case Expr::OffsetOfExprClass: {
15467     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15468     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15469     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15470     // compliance: we should warn earlier for offsetof expressions with
15471     // array subscripts that aren't ICEs, and if the array subscripts
15472     // are ICEs, the value of the offsetof must be an integer constant.
15473     return CheckEvalInICE(E, Ctx);
15474   }
15475   case Expr::UnaryExprOrTypeTraitExprClass: {
15476     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15477     if ((Exp->getKind() ==  UETT_SizeOf) &&
15478         Exp->getTypeOfArgument()->isVariableArrayType())
15479       return ICEDiag(IK_NotICE, E->getBeginLoc());
15480     return NoDiag();
15481   }
15482   case Expr::BinaryOperatorClass: {
15483     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15484     switch (Exp->getOpcode()) {
15485     case BO_PtrMemD:
15486     case BO_PtrMemI:
15487     case BO_Assign:
15488     case BO_MulAssign:
15489     case BO_DivAssign:
15490     case BO_RemAssign:
15491     case BO_AddAssign:
15492     case BO_SubAssign:
15493     case BO_ShlAssign:
15494     case BO_ShrAssign:
15495     case BO_AndAssign:
15496     case BO_XorAssign:
15497     case BO_OrAssign:
15498       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15499       // constant expressions, but they can never be ICEs because an ICE cannot
15500       // contain an lvalue operand.
15501       return ICEDiag(IK_NotICE, E->getBeginLoc());
15502 
15503     case BO_Mul:
15504     case BO_Div:
15505     case BO_Rem:
15506     case BO_Add:
15507     case BO_Sub:
15508     case BO_Shl:
15509     case BO_Shr:
15510     case BO_LT:
15511     case BO_GT:
15512     case BO_LE:
15513     case BO_GE:
15514     case BO_EQ:
15515     case BO_NE:
15516     case BO_And:
15517     case BO_Xor:
15518     case BO_Or:
15519     case BO_Comma:
15520     case BO_Cmp: {
15521       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15522       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15523       if (Exp->getOpcode() == BO_Div ||
15524           Exp->getOpcode() == BO_Rem) {
15525         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15526         // we don't evaluate one.
15527         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15528           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15529           if (REval == 0)
15530             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15531           if (REval.isSigned() && REval.isAllOnes()) {
15532             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15533             if (LEval.isMinSignedValue())
15534               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15535           }
15536         }
15537       }
15538       if (Exp->getOpcode() == BO_Comma) {
15539         if (Ctx.getLangOpts().C99) {
15540           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15541           // if it isn't evaluated.
15542           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15543             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15544         } else {
15545           // In both C89 and C++, commas in ICEs are illegal.
15546           return ICEDiag(IK_NotICE, E->getBeginLoc());
15547         }
15548       }
15549       return Worst(LHSResult, RHSResult);
15550     }
15551     case BO_LAnd:
15552     case BO_LOr: {
15553       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15554       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15555       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15556         // Rare case where the RHS has a comma "side-effect"; we need
15557         // to actually check the condition to see whether the side
15558         // with the comma is evaluated.
15559         if ((Exp->getOpcode() == BO_LAnd) !=
15560             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15561           return RHSResult;
15562         return NoDiag();
15563       }
15564 
15565       return Worst(LHSResult, RHSResult);
15566     }
15567     }
15568     llvm_unreachable("invalid binary operator kind");
15569   }
15570   case Expr::ImplicitCastExprClass:
15571   case Expr::CStyleCastExprClass:
15572   case Expr::CXXFunctionalCastExprClass:
15573   case Expr::CXXStaticCastExprClass:
15574   case Expr::CXXReinterpretCastExprClass:
15575   case Expr::CXXConstCastExprClass:
15576   case Expr::ObjCBridgedCastExprClass: {
15577     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15578     if (isa<ExplicitCastExpr>(E)) {
15579       if (const FloatingLiteral *FL
15580             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15581         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15582         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15583         APSInt IgnoredVal(DestWidth, !DestSigned);
15584         bool Ignored;
15585         // If the value does not fit in the destination type, the behavior is
15586         // undefined, so we are not required to treat it as a constant
15587         // expression.
15588         if (FL->getValue().convertToInteger(IgnoredVal,
15589                                             llvm::APFloat::rmTowardZero,
15590                                             &Ignored) & APFloat::opInvalidOp)
15591           return ICEDiag(IK_NotICE, E->getBeginLoc());
15592         return NoDiag();
15593       }
15594     }
15595     switch (cast<CastExpr>(E)->getCastKind()) {
15596     case CK_LValueToRValue:
15597     case CK_AtomicToNonAtomic:
15598     case CK_NonAtomicToAtomic:
15599     case CK_NoOp:
15600     case CK_IntegralToBoolean:
15601     case CK_IntegralCast:
15602       return CheckICE(SubExpr, Ctx);
15603     default:
15604       return ICEDiag(IK_NotICE, E->getBeginLoc());
15605     }
15606   }
15607   case Expr::BinaryConditionalOperatorClass: {
15608     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15609     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15610     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15611     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15612     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15613     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15614     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15615         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15616     return FalseResult;
15617   }
15618   case Expr::ConditionalOperatorClass: {
15619     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15620     // If the condition (ignoring parens) is a __builtin_constant_p call,
15621     // then only the true side is actually considered in an integer constant
15622     // expression, and it is fully evaluated.  This is an important GNU
15623     // extension.  See GCC PR38377 for discussion.
15624     if (const CallExpr *CallCE
15625         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15626       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15627         return CheckEvalInICE(E, Ctx);
15628     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15629     if (CondResult.Kind == IK_NotICE)
15630       return CondResult;
15631 
15632     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15633     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15634 
15635     if (TrueResult.Kind == IK_NotICE)
15636       return TrueResult;
15637     if (FalseResult.Kind == IK_NotICE)
15638       return FalseResult;
15639     if (CondResult.Kind == IK_ICEIfUnevaluated)
15640       return CondResult;
15641     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15642       return NoDiag();
15643     // Rare case where the diagnostics depend on which side is evaluated
15644     // Note that if we get here, CondResult is 0, and at least one of
15645     // TrueResult and FalseResult is non-zero.
15646     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15647       return FalseResult;
15648     return TrueResult;
15649   }
15650   case Expr::CXXDefaultArgExprClass:
15651     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15652   case Expr::CXXDefaultInitExprClass:
15653     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15654   case Expr::ChooseExprClass: {
15655     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15656   }
15657   case Expr::BuiltinBitCastExprClass: {
15658     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15659       return ICEDiag(IK_NotICE, E->getBeginLoc());
15660     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15661   }
15662   }
15663 
15664   llvm_unreachable("Invalid StmtClass!");
15665 }
15666 
15667 /// Evaluate an expression as a C++11 integral constant expression.
15668 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15669                                                     const Expr *E,
15670                                                     llvm::APSInt *Value,
15671                                                     SourceLocation *Loc) {
15672   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15673     if (Loc) *Loc = E->getExprLoc();
15674     return false;
15675   }
15676 
15677   APValue Result;
15678   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15679     return false;
15680 
15681   if (!Result.isInt()) {
15682     if (Loc) *Loc = E->getExprLoc();
15683     return false;
15684   }
15685 
15686   if (Value) *Value = Result.getInt();
15687   return true;
15688 }
15689 
15690 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15691                                  SourceLocation *Loc) const {
15692   assert(!isValueDependent() &&
15693          "Expression evaluator can't be called on a dependent expression.");
15694 
15695   if (Ctx.getLangOpts().CPlusPlus11)
15696     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15697 
15698   ICEDiag D = CheckICE(this, Ctx);
15699   if (D.Kind != IK_ICE) {
15700     if (Loc) *Loc = D.Loc;
15701     return false;
15702   }
15703   return true;
15704 }
15705 
15706 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15707                                                     SourceLocation *Loc,
15708                                                     bool isEvaluated) const {
15709   if (isValueDependent()) {
15710     // Expression evaluator can't succeed on a dependent expression.
15711     return None;
15712   }
15713 
15714   APSInt Value;
15715 
15716   if (Ctx.getLangOpts().CPlusPlus11) {
15717     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15718       return Value;
15719     return None;
15720   }
15721 
15722   if (!isIntegerConstantExpr(Ctx, Loc))
15723     return None;
15724 
15725   // The only possible side-effects here are due to UB discovered in the
15726   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15727   // required to treat the expression as an ICE, so we produce the folded
15728   // value.
15729   EvalResult ExprResult;
15730   Expr::EvalStatus Status;
15731   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15732   Info.InConstantContext = true;
15733 
15734   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15735     llvm_unreachable("ICE cannot be evaluated!");
15736 
15737   return ExprResult.Val.getInt();
15738 }
15739 
15740 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15741   assert(!isValueDependent() &&
15742          "Expression evaluator can't be called on a dependent expression.");
15743 
15744   return CheckICE(this, Ctx).Kind == IK_ICE;
15745 }
15746 
15747 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15748                                SourceLocation *Loc) const {
15749   assert(!isValueDependent() &&
15750          "Expression evaluator can't be called on a dependent expression.");
15751 
15752   // We support this checking in C++98 mode in order to diagnose compatibility
15753   // issues.
15754   assert(Ctx.getLangOpts().CPlusPlus);
15755 
15756   // Build evaluation settings.
15757   Expr::EvalStatus Status;
15758   SmallVector<PartialDiagnosticAt, 8> Diags;
15759   Status.Diag = &Diags;
15760   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15761 
15762   APValue Scratch;
15763   bool IsConstExpr =
15764       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15765       // FIXME: We don't produce a diagnostic for this, but the callers that
15766       // call us on arbitrary full-expressions should generally not care.
15767       Info.discardCleanups() && !Status.HasSideEffects;
15768 
15769   if (!Diags.empty()) {
15770     IsConstExpr = false;
15771     if (Loc) *Loc = Diags[0].first;
15772   } else if (!IsConstExpr) {
15773     // FIXME: This shouldn't happen.
15774     if (Loc) *Loc = getExprLoc();
15775   }
15776 
15777   return IsConstExpr;
15778 }
15779 
15780 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15781                                     const FunctionDecl *Callee,
15782                                     ArrayRef<const Expr*> Args,
15783                                     const Expr *This) const {
15784   assert(!isValueDependent() &&
15785          "Expression evaluator can't be called on a dependent expression.");
15786 
15787   Expr::EvalStatus Status;
15788   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15789   Info.InConstantContext = true;
15790 
15791   LValue ThisVal;
15792   const LValue *ThisPtr = nullptr;
15793   if (This) {
15794 #ifndef NDEBUG
15795     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15796     assert(MD && "Don't provide `this` for non-methods.");
15797     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15798 #endif
15799     if (!This->isValueDependent() &&
15800         EvaluateObjectArgument(Info, This, ThisVal) &&
15801         !Info.EvalStatus.HasSideEffects)
15802       ThisPtr = &ThisVal;
15803 
15804     // Ignore any side-effects from a failed evaluation. This is safe because
15805     // they can't interfere with any other argument evaluation.
15806     Info.EvalStatus.HasSideEffects = false;
15807   }
15808 
15809   CallRef Call = Info.CurrentCall->createCall(Callee);
15810   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15811        I != E; ++I) {
15812     unsigned Idx = I - Args.begin();
15813     if (Idx >= Callee->getNumParams())
15814       break;
15815     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15816     if ((*I)->isValueDependent() ||
15817         !EvaluateCallArg(PVD, *I, Call, Info) ||
15818         Info.EvalStatus.HasSideEffects) {
15819       // If evaluation fails, throw away the argument entirely.
15820       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15821         *Slot = APValue();
15822     }
15823 
15824     // Ignore any side-effects from a failed evaluation. This is safe because
15825     // they can't interfere with any other argument evaluation.
15826     Info.EvalStatus.HasSideEffects = false;
15827   }
15828 
15829   // Parameter cleanups happen in the caller and are not part of this
15830   // evaluation.
15831   Info.discardCleanups();
15832   Info.EvalStatus.HasSideEffects = false;
15833 
15834   // Build fake call to Callee.
15835   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15836   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15837   FullExpressionRAII Scope(Info);
15838   return Evaluate(Value, Info, this) && Scope.destroy() &&
15839          !Info.EvalStatus.HasSideEffects;
15840 }
15841 
15842 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15843                                    SmallVectorImpl<
15844                                      PartialDiagnosticAt> &Diags) {
15845   // FIXME: It would be useful to check constexpr function templates, but at the
15846   // moment the constant expression evaluator cannot cope with the non-rigorous
15847   // ASTs which we build for dependent expressions.
15848   if (FD->isDependentContext())
15849     return true;
15850 
15851   Expr::EvalStatus Status;
15852   Status.Diag = &Diags;
15853 
15854   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15855   Info.InConstantContext = true;
15856   Info.CheckingPotentialConstantExpression = true;
15857 
15858   // The constexpr VM attempts to compile all methods to bytecode here.
15859   if (Info.EnableNewConstInterp) {
15860     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15861     return Diags.empty();
15862   }
15863 
15864   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15865   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15866 
15867   // Fabricate an arbitrary expression on the stack and pretend that it
15868   // is a temporary being used as the 'this' pointer.
15869   LValue This;
15870   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15871   This.set({&VIE, Info.CurrentCall->Index});
15872 
15873   ArrayRef<const Expr*> Args;
15874 
15875   APValue Scratch;
15876   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15877     // Evaluate the call as a constant initializer, to allow the construction
15878     // of objects of non-literal types.
15879     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15880     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15881   } else {
15882     SourceLocation Loc = FD->getLocation();
15883     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15884                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15885   }
15886 
15887   return Diags.empty();
15888 }
15889 
15890 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15891                                               const FunctionDecl *FD,
15892                                               SmallVectorImpl<
15893                                                 PartialDiagnosticAt> &Diags) {
15894   assert(!E->isValueDependent() &&
15895          "Expression evaluator can't be called on a dependent expression.");
15896 
15897   Expr::EvalStatus Status;
15898   Status.Diag = &Diags;
15899 
15900   EvalInfo Info(FD->getASTContext(), Status,
15901                 EvalInfo::EM_ConstantExpressionUnevaluated);
15902   Info.InConstantContext = true;
15903   Info.CheckingPotentialConstantExpression = true;
15904 
15905   // Fabricate a call stack frame to give the arguments a plausible cover story.
15906   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15907 
15908   APValue ResultScratch;
15909   Evaluate(ResultScratch, Info, E);
15910   return Diags.empty();
15911 }
15912 
15913 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15914                                  unsigned Type) const {
15915   if (!getType()->isPointerType())
15916     return false;
15917 
15918   Expr::EvalStatus Status;
15919   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15920   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15921 }
15922 
15923 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15924                                   EvalInfo &Info) {
15925   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15926     return false;
15927 
15928   LValue String;
15929 
15930   if (!EvaluatePointer(E, String, Info))
15931     return false;
15932 
15933   QualType CharTy = E->getType()->getPointeeType();
15934 
15935   // Fast path: if it's a string literal, search the string value.
15936   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15937           String.getLValueBase().dyn_cast<const Expr *>())) {
15938     StringRef Str = S->getBytes();
15939     int64_t Off = String.Offset.getQuantity();
15940     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15941         S->getCharByteWidth() == 1 &&
15942         // FIXME: Add fast-path for wchar_t too.
15943         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15944       Str = Str.substr(Off);
15945 
15946       StringRef::size_type Pos = Str.find(0);
15947       if (Pos != StringRef::npos)
15948         Str = Str.substr(0, Pos);
15949 
15950       Result = Str.size();
15951       return true;
15952     }
15953 
15954     // Fall through to slow path.
15955   }
15956 
15957   // Slow path: scan the bytes of the string looking for the terminating 0.
15958   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15959     APValue Char;
15960     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15961         !Char.isInt())
15962       return false;
15963     if (!Char.getInt()) {
15964       Result = Strlen;
15965       return true;
15966     }
15967     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15968       return false;
15969   }
15970 }
15971 
15972 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15973   Expr::EvalStatus Status;
15974   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15975   return EvaluateBuiltinStrLen(this, Result, Info);
15976 }
15977