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 to use in evaluation of the specified expression.
2556 ///
2557 /// If rounding mode is unknown at compile time, still try to evaluate the
2558 /// expression. If the result is exact, it does not depend on rounding mode.
2559 /// So return "tonearest" mode instead of "dynamic".
2560 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2561   llvm::RoundingMode RM =
2562       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2563   if (RM == llvm::RoundingMode::Dynamic)
2564     RM = llvm::RoundingMode::NearestTiesToEven;
2565   return RM;
2566 }
2567 
2568 /// Check if the given evaluation result is allowed for constant evaluation.
2569 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2570                                      APFloat::opStatus St) {
2571   // In a constant context, assume that any dynamic rounding mode or FP
2572   // exception state matches the default floating-point environment.
2573   if (Info.InConstantContext)
2574     return true;
2575 
2576   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2577   if ((St & APFloat::opInexact) &&
2578       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2579     // Inexact result means that it depends on rounding mode. If the requested
2580     // mode is dynamic, the evaluation cannot be made in compile time.
2581     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2582     return false;
2583   }
2584 
2585   if ((St != APFloat::opOK) &&
2586       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2587        FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2588        FPO.getAllowFEnvAccess())) {
2589     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2590     return false;
2591   }
2592 
2593   if ((St & APFloat::opStatus::opInvalidOp) &&
2594       FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2595     // There is no usefully definable result.
2596     Info.FFDiag(E);
2597     return false;
2598   }
2599 
2600   // FIXME: if:
2601   // - evaluation triggered other FP exception, and
2602   // - exception mode is not "ignore", and
2603   // - the expression being evaluated is not a part of global variable
2604   //   initializer,
2605   // the evaluation probably need to be rejected.
2606   return true;
2607 }
2608 
2609 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2610                                    QualType SrcType, QualType DestType,
2611                                    APFloat &Result) {
2612   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2613   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2614   APFloat::opStatus St;
2615   APFloat Value = Result;
2616   bool ignored;
2617   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2618   return checkFloatingPointResult(Info, E, St);
2619 }
2620 
2621 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2622                                  QualType DestType, QualType SrcType,
2623                                  const APSInt &Value) {
2624   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2625   // Figure out if this is a truncate, extend or noop cast.
2626   // If the input is signed, do a sign extend, noop, or truncate.
2627   APSInt Result = Value.extOrTrunc(DestWidth);
2628   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2629   if (DestType->isBooleanType())
2630     Result = Value.getBoolValue();
2631   return Result;
2632 }
2633 
2634 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2635                                  const FPOptions FPO,
2636                                  QualType SrcType, const APSInt &Value,
2637                                  QualType DestType, APFloat &Result) {
2638   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2639   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2640        APFloat::rmNearestTiesToEven);
2641   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2642       FPO.isFPConstrained()) {
2643     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2644     return false;
2645   }
2646   return true;
2647 }
2648 
2649 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2650                                   APValue &Value, const FieldDecl *FD) {
2651   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2652 
2653   if (!Value.isInt()) {
2654     // Trying to store a pointer-cast-to-integer into a bitfield.
2655     // FIXME: In this case, we should provide the diagnostic for casting
2656     // a pointer to an integer.
2657     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2658     Info.FFDiag(E);
2659     return false;
2660   }
2661 
2662   APSInt &Int = Value.getInt();
2663   unsigned OldBitWidth = Int.getBitWidth();
2664   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2665   if (NewBitWidth < OldBitWidth)
2666     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2667   return true;
2668 }
2669 
2670 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2671                                   llvm::APInt &Res) {
2672   APValue SVal;
2673   if (!Evaluate(SVal, Info, E))
2674     return false;
2675   if (SVal.isInt()) {
2676     Res = SVal.getInt();
2677     return true;
2678   }
2679   if (SVal.isFloat()) {
2680     Res = SVal.getFloat().bitcastToAPInt();
2681     return true;
2682   }
2683   if (SVal.isVector()) {
2684     QualType VecTy = E->getType();
2685     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2686     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2687     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2688     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2689     Res = llvm::APInt::getZero(VecSize);
2690     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2691       APValue &Elt = SVal.getVectorElt(i);
2692       llvm::APInt EltAsInt;
2693       if (Elt.isInt()) {
2694         EltAsInt = Elt.getInt();
2695       } else if (Elt.isFloat()) {
2696         EltAsInt = Elt.getFloat().bitcastToAPInt();
2697       } else {
2698         // Don't try to handle vectors of anything other than int or float
2699         // (not sure if it's possible to hit this case).
2700         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2701         return false;
2702       }
2703       unsigned BaseEltSize = EltAsInt.getBitWidth();
2704       if (BigEndian)
2705         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2706       else
2707         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2708     }
2709     return true;
2710   }
2711   // Give up if the input isn't an int, float, or vector.  For example, we
2712   // reject "(v4i16)(intptr_t)&a".
2713   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2714   return false;
2715 }
2716 
2717 /// Perform the given integer operation, which is known to need at most BitWidth
2718 /// bits, and check for overflow in the original type (if that type was not an
2719 /// unsigned type).
2720 template<typename Operation>
2721 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2722                                  const APSInt &LHS, const APSInt &RHS,
2723                                  unsigned BitWidth, Operation Op,
2724                                  APSInt &Result) {
2725   if (LHS.isUnsigned()) {
2726     Result = Op(LHS, RHS);
2727     return true;
2728   }
2729 
2730   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2731   Result = Value.trunc(LHS.getBitWidth());
2732   if (Result.extend(BitWidth) != Value) {
2733     if (Info.checkingForUndefinedBehavior())
2734       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2735                                        diag::warn_integer_constant_overflow)
2736           << toString(Result, 10) << E->getType();
2737     return HandleOverflow(Info, E, Value, E->getType());
2738   }
2739   return true;
2740 }
2741 
2742 /// Perform the given binary integer operation.
2743 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2744                               BinaryOperatorKind Opcode, APSInt RHS,
2745                               APSInt &Result) {
2746   switch (Opcode) {
2747   default:
2748     Info.FFDiag(E);
2749     return false;
2750   case BO_Mul:
2751     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2752                                 std::multiplies<APSInt>(), Result);
2753   case BO_Add:
2754     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2755                                 std::plus<APSInt>(), Result);
2756   case BO_Sub:
2757     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2758                                 std::minus<APSInt>(), Result);
2759   case BO_And: Result = LHS & RHS; return true;
2760   case BO_Xor: Result = LHS ^ RHS; return true;
2761   case BO_Or:  Result = LHS | RHS; return true;
2762   case BO_Div:
2763   case BO_Rem:
2764     if (RHS == 0) {
2765       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2766       return false;
2767     }
2768     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2769     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2770     // this operation and gives the two's complement result.
2771     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2772         LHS.isMinSignedValue())
2773       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2774                             E->getType());
2775     return true;
2776   case BO_Shl: {
2777     if (Info.getLangOpts().OpenCL)
2778       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2779       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2780                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2781                     RHS.isUnsigned());
2782     else if (RHS.isSigned() && RHS.isNegative()) {
2783       // During constant-folding, a negative shift is an opposite shift. Such
2784       // a shift is not a constant expression.
2785       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2786       RHS = -RHS;
2787       goto shift_right;
2788     }
2789   shift_left:
2790     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2791     // the shifted type.
2792     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2793     if (SA != RHS) {
2794       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2795         << RHS << E->getType() << LHS.getBitWidth();
2796     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2797       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2798       // operand, and must not overflow the corresponding unsigned type.
2799       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2800       // E1 x 2^E2 module 2^N.
2801       if (LHS.isNegative())
2802         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2803       else if (LHS.countLeadingZeros() < SA)
2804         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2805     }
2806     Result = LHS << SA;
2807     return true;
2808   }
2809   case BO_Shr: {
2810     if (Info.getLangOpts().OpenCL)
2811       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2812       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2813                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2814                     RHS.isUnsigned());
2815     else if (RHS.isSigned() && RHS.isNegative()) {
2816       // During constant-folding, a negative shift is an opposite shift. Such a
2817       // shift is not a constant expression.
2818       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2819       RHS = -RHS;
2820       goto shift_left;
2821     }
2822   shift_right:
2823     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2824     // shifted type.
2825     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2826     if (SA != RHS)
2827       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2828         << RHS << E->getType() << LHS.getBitWidth();
2829     Result = LHS >> SA;
2830     return true;
2831   }
2832 
2833   case BO_LT: Result = LHS < RHS; return true;
2834   case BO_GT: Result = LHS > RHS; return true;
2835   case BO_LE: Result = LHS <= RHS; return true;
2836   case BO_GE: Result = LHS >= RHS; return true;
2837   case BO_EQ: Result = LHS == RHS; return true;
2838   case BO_NE: Result = LHS != RHS; return true;
2839   case BO_Cmp:
2840     llvm_unreachable("BO_Cmp should be handled elsewhere");
2841   }
2842 }
2843 
2844 /// Perform the given binary floating-point operation, in-place, on LHS.
2845 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2846                                   APFloat &LHS, BinaryOperatorKind Opcode,
2847                                   const APFloat &RHS) {
2848   llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2849   APFloat::opStatus St;
2850   switch (Opcode) {
2851   default:
2852     Info.FFDiag(E);
2853     return false;
2854   case BO_Mul:
2855     St = LHS.multiply(RHS, RM);
2856     break;
2857   case BO_Add:
2858     St = LHS.add(RHS, RM);
2859     break;
2860   case BO_Sub:
2861     St = LHS.subtract(RHS, RM);
2862     break;
2863   case BO_Div:
2864     // [expr.mul]p4:
2865     //   If the second operand of / or % is zero the behavior is undefined.
2866     if (RHS.isZero())
2867       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2868     St = LHS.divide(RHS, RM);
2869     break;
2870   }
2871 
2872   // [expr.pre]p4:
2873   //   If during the evaluation of an expression, the result is not
2874   //   mathematically defined [...], the behavior is undefined.
2875   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2876   if (LHS.isNaN()) {
2877     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2878     return Info.noteUndefinedBehavior();
2879   }
2880 
2881   return checkFloatingPointResult(Info, E, St);
2882 }
2883 
2884 static bool handleLogicalOpForVector(const APInt &LHSValue,
2885                                      BinaryOperatorKind Opcode,
2886                                      const APInt &RHSValue, APInt &Result) {
2887   bool LHS = (LHSValue != 0);
2888   bool RHS = (RHSValue != 0);
2889 
2890   if (Opcode == BO_LAnd)
2891     Result = LHS && RHS;
2892   else
2893     Result = LHS || RHS;
2894   return true;
2895 }
2896 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2897                                      BinaryOperatorKind Opcode,
2898                                      const APFloat &RHSValue, APInt &Result) {
2899   bool LHS = !LHSValue.isZero();
2900   bool RHS = !RHSValue.isZero();
2901 
2902   if (Opcode == BO_LAnd)
2903     Result = LHS && RHS;
2904   else
2905     Result = LHS || RHS;
2906   return true;
2907 }
2908 
2909 static bool handleLogicalOpForVector(const APValue &LHSValue,
2910                                      BinaryOperatorKind Opcode,
2911                                      const APValue &RHSValue, APInt &Result) {
2912   // The result is always an int type, however operands match the first.
2913   if (LHSValue.getKind() == APValue::Int)
2914     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2915                                     RHSValue.getInt(), Result);
2916   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2917   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2918                                   RHSValue.getFloat(), Result);
2919 }
2920 
2921 template <typename APTy>
2922 static bool
2923 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2924                                const APTy &RHSValue, APInt &Result) {
2925   switch (Opcode) {
2926   default:
2927     llvm_unreachable("unsupported binary operator");
2928   case BO_EQ:
2929     Result = (LHSValue == RHSValue);
2930     break;
2931   case BO_NE:
2932     Result = (LHSValue != RHSValue);
2933     break;
2934   case BO_LT:
2935     Result = (LHSValue < RHSValue);
2936     break;
2937   case BO_GT:
2938     Result = (LHSValue > RHSValue);
2939     break;
2940   case BO_LE:
2941     Result = (LHSValue <= RHSValue);
2942     break;
2943   case BO_GE:
2944     Result = (LHSValue >= RHSValue);
2945     break;
2946   }
2947 
2948   // The boolean operations on these vector types use an instruction that
2949   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2950   // to -1 to make sure that we produce the correct value.
2951   Result.negate();
2952 
2953   return true;
2954 }
2955 
2956 static bool handleCompareOpForVector(const APValue &LHSValue,
2957                                      BinaryOperatorKind Opcode,
2958                                      const APValue &RHSValue, APInt &Result) {
2959   // The result is always an int type, however operands match the first.
2960   if (LHSValue.getKind() == APValue::Int)
2961     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2962                                           RHSValue.getInt(), Result);
2963   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2964   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2965                                         RHSValue.getFloat(), Result);
2966 }
2967 
2968 // Perform binary operations for vector types, in place on the LHS.
2969 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2970                                     BinaryOperatorKind Opcode,
2971                                     APValue &LHSValue,
2972                                     const APValue &RHSValue) {
2973   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2974          "Operation not supported on vector types");
2975 
2976   const auto *VT = E->getType()->castAs<VectorType>();
2977   unsigned NumElements = VT->getNumElements();
2978   QualType EltTy = VT->getElementType();
2979 
2980   // In the cases (typically C as I've observed) where we aren't evaluating
2981   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2982   // just give up.
2983   if (!LHSValue.isVector()) {
2984     assert(LHSValue.isLValue() &&
2985            "A vector result that isn't a vector OR uncalculated LValue");
2986     Info.FFDiag(E);
2987     return false;
2988   }
2989 
2990   assert(LHSValue.getVectorLength() == NumElements &&
2991          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2992 
2993   SmallVector<APValue, 4> ResultElements;
2994 
2995   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2996     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2997     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2998 
2999     if (EltTy->isIntegerType()) {
3000       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3001                        EltTy->isUnsignedIntegerType()};
3002       bool Success = true;
3003 
3004       if (BinaryOperator::isLogicalOp(Opcode))
3005         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3006       else if (BinaryOperator::isComparisonOp(Opcode))
3007         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008       else
3009         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3010                                     RHSElt.getInt(), EltResult);
3011 
3012       if (!Success) {
3013         Info.FFDiag(E);
3014         return false;
3015       }
3016       ResultElements.emplace_back(EltResult);
3017 
3018     } else if (EltTy->isFloatingType()) {
3019       assert(LHSElt.getKind() == APValue::Float &&
3020              RHSElt.getKind() == APValue::Float &&
3021              "Mismatched LHS/RHS/Result Type");
3022       APFloat LHSFloat = LHSElt.getFloat();
3023 
3024       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3025                                  RHSElt.getFloat())) {
3026         Info.FFDiag(E);
3027         return false;
3028       }
3029 
3030       ResultElements.emplace_back(LHSFloat);
3031     }
3032   }
3033 
3034   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3035   return true;
3036 }
3037 
3038 /// Cast an lvalue referring to a base subobject to a derived class, by
3039 /// truncating the lvalue's path to the given length.
3040 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3041                                const RecordDecl *TruncatedType,
3042                                unsigned TruncatedElements) {
3043   SubobjectDesignator &D = Result.Designator;
3044 
3045   // Check we actually point to a derived class object.
3046   if (TruncatedElements == D.Entries.size())
3047     return true;
3048   assert(TruncatedElements >= D.MostDerivedPathLength &&
3049          "not casting to a derived class");
3050   if (!Result.checkSubobject(Info, E, CSK_Derived))
3051     return false;
3052 
3053   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3054   const RecordDecl *RD = TruncatedType;
3055   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3056     if (RD->isInvalidDecl()) return false;
3057     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3058     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3059     if (isVirtualBaseClass(D.Entries[I]))
3060       Result.Offset -= Layout.getVBaseClassOffset(Base);
3061     else
3062       Result.Offset -= Layout.getBaseClassOffset(Base);
3063     RD = Base;
3064   }
3065   D.Entries.resize(TruncatedElements);
3066   return true;
3067 }
3068 
3069 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3070                                    const CXXRecordDecl *Derived,
3071                                    const CXXRecordDecl *Base,
3072                                    const ASTRecordLayout *RL = nullptr) {
3073   if (!RL) {
3074     if (Derived->isInvalidDecl()) return false;
3075     RL = &Info.Ctx.getASTRecordLayout(Derived);
3076   }
3077 
3078   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3079   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3080   return true;
3081 }
3082 
3083 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3084                              const CXXRecordDecl *DerivedDecl,
3085                              const CXXBaseSpecifier *Base) {
3086   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3087 
3088   if (!Base->isVirtual())
3089     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3090 
3091   SubobjectDesignator &D = Obj.Designator;
3092   if (D.Invalid)
3093     return false;
3094 
3095   // Extract most-derived object and corresponding type.
3096   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3097   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3098     return false;
3099 
3100   // Find the virtual base class.
3101   if (DerivedDecl->isInvalidDecl()) return false;
3102   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3103   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3104   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3105   return true;
3106 }
3107 
3108 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3109                                  QualType Type, LValue &Result) {
3110   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3111                                      PathE = E->path_end();
3112        PathI != PathE; ++PathI) {
3113     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3114                           *PathI))
3115       return false;
3116     Type = (*PathI)->getType();
3117   }
3118   return true;
3119 }
3120 
3121 /// Cast an lvalue referring to a derived class to a known base subobject.
3122 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3123                             const CXXRecordDecl *DerivedRD,
3124                             const CXXRecordDecl *BaseRD) {
3125   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3126                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3127   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3128     llvm_unreachable("Class must be derived from the passed in base class!");
3129 
3130   for (CXXBasePathElement &Elem : Paths.front())
3131     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3132       return false;
3133   return true;
3134 }
3135 
3136 /// Update LVal to refer to the given field, which must be a member of the type
3137 /// currently described by LVal.
3138 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3139                                const FieldDecl *FD,
3140                                const ASTRecordLayout *RL = nullptr) {
3141   if (!RL) {
3142     if (FD->getParent()->isInvalidDecl()) return false;
3143     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3144   }
3145 
3146   unsigned I = FD->getFieldIndex();
3147   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3148   LVal.addDecl(Info, E, FD);
3149   return true;
3150 }
3151 
3152 /// Update LVal to refer to the given indirect field.
3153 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3154                                        LValue &LVal,
3155                                        const IndirectFieldDecl *IFD) {
3156   for (const auto *C : IFD->chain())
3157     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3158       return false;
3159   return true;
3160 }
3161 
3162 /// Get the size of the given type in char units.
3163 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3164                          QualType Type, CharUnits &Size) {
3165   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3166   // extension.
3167   if (Type->isVoidType() || Type->isFunctionType()) {
3168     Size = CharUnits::One();
3169     return true;
3170   }
3171 
3172   if (Type->isDependentType()) {
3173     Info.FFDiag(Loc);
3174     return false;
3175   }
3176 
3177   if (!Type->isConstantSizeType()) {
3178     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3179     // FIXME: Better diagnostic.
3180     Info.FFDiag(Loc);
3181     return false;
3182   }
3183 
3184   Size = Info.Ctx.getTypeSizeInChars(Type);
3185   return true;
3186 }
3187 
3188 /// Update a pointer value to model pointer arithmetic.
3189 /// \param Info - Information about the ongoing evaluation.
3190 /// \param E - The expression being evaluated, for diagnostic purposes.
3191 /// \param LVal - The pointer value to be updated.
3192 /// \param EltTy - The pointee type represented by LVal.
3193 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3194 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3195                                         LValue &LVal, QualType EltTy,
3196                                         APSInt Adjustment) {
3197   CharUnits SizeOfPointee;
3198   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3199     return false;
3200 
3201   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3202   return true;
3203 }
3204 
3205 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3206                                         LValue &LVal, QualType EltTy,
3207                                         int64_t Adjustment) {
3208   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3209                                      APSInt::get(Adjustment));
3210 }
3211 
3212 /// Update an lvalue to refer to a component of a complex number.
3213 /// \param Info - Information about the ongoing evaluation.
3214 /// \param LVal - The lvalue to be updated.
3215 /// \param EltTy - The complex number's component type.
3216 /// \param Imag - False for the real component, true for the imaginary.
3217 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3218                                        LValue &LVal, QualType EltTy,
3219                                        bool Imag) {
3220   if (Imag) {
3221     CharUnits SizeOfComponent;
3222     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3223       return false;
3224     LVal.Offset += SizeOfComponent;
3225   }
3226   LVal.addComplex(Info, E, EltTy, Imag);
3227   return true;
3228 }
3229 
3230 /// Try to evaluate the initializer for a variable declaration.
3231 ///
3232 /// \param Info   Information about the ongoing evaluation.
3233 /// \param E      An expression to be used when printing diagnostics.
3234 /// \param VD     The variable whose initializer should be obtained.
3235 /// \param Version The version of the variable within the frame.
3236 /// \param Frame  The frame in which the variable was created. Must be null
3237 ///               if this variable is not local to the evaluation.
3238 /// \param Result Filled in with a pointer to the value of the variable.
3239 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3240                                 const VarDecl *VD, CallStackFrame *Frame,
3241                                 unsigned Version, APValue *&Result) {
3242   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3243 
3244   // If this is a local variable, dig out its value.
3245   if (Frame) {
3246     Result = Frame->getTemporary(VD, Version);
3247     if (Result)
3248       return true;
3249 
3250     if (!isa<ParmVarDecl>(VD)) {
3251       // Assume variables referenced within a lambda's call operator that were
3252       // not declared within the call operator are captures and during checking
3253       // of a potential constant expression, assume they are unknown constant
3254       // expressions.
3255       assert(isLambdaCallOperator(Frame->Callee) &&
3256              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3257              "missing value for local variable");
3258       if (Info.checkingPotentialConstantExpression())
3259         return false;
3260       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3261       // still reachable at all?
3262       Info.FFDiag(E->getBeginLoc(),
3263                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3264           << "captures not currently allowed";
3265       return false;
3266     }
3267   }
3268 
3269   // If we're currently evaluating the initializer of this declaration, use that
3270   // in-flight value.
3271   if (Info.EvaluatingDecl == Base) {
3272     Result = Info.EvaluatingDeclValue;
3273     return true;
3274   }
3275 
3276   if (isa<ParmVarDecl>(VD)) {
3277     // Assume parameters of a potential constant expression are usable in
3278     // constant expressions.
3279     if (!Info.checkingPotentialConstantExpression() ||
3280         !Info.CurrentCall->Callee ||
3281         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3282       if (Info.getLangOpts().CPlusPlus11) {
3283         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3284             << VD;
3285         NoteLValueLocation(Info, Base);
3286       } else {
3287         Info.FFDiag(E);
3288       }
3289     }
3290     return false;
3291   }
3292 
3293   // Dig out the initializer, and use the declaration which it's attached to.
3294   // FIXME: We should eventually check whether the variable has a reachable
3295   // initializing declaration.
3296   const Expr *Init = VD->getAnyInitializer(VD);
3297   if (!Init) {
3298     // Don't diagnose during potential constant expression checking; an
3299     // initializer might be added later.
3300     if (!Info.checkingPotentialConstantExpression()) {
3301       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3302         << VD;
3303       NoteLValueLocation(Info, Base);
3304     }
3305     return false;
3306   }
3307 
3308   if (Init->isValueDependent()) {
3309     // The DeclRefExpr is not value-dependent, but the variable it refers to
3310     // has a value-dependent initializer. This should only happen in
3311     // constant-folding cases, where the variable is not actually of a suitable
3312     // type for use in a constant expression (otherwise the DeclRefExpr would
3313     // have been value-dependent too), so diagnose that.
3314     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3315     if (!Info.checkingPotentialConstantExpression()) {
3316       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3317                          ? diag::note_constexpr_ltor_non_constexpr
3318                          : diag::note_constexpr_ltor_non_integral, 1)
3319           << VD << VD->getType();
3320       NoteLValueLocation(Info, Base);
3321     }
3322     return false;
3323   }
3324 
3325   // Check that we can fold the initializer. In C++, we will have already done
3326   // this in the cases where it matters for conformance.
3327   SmallVector<PartialDiagnosticAt, 8> Notes;
3328   if (!VD->evaluateValue(Notes)) {
3329     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3330               Notes.size() + 1) << VD;
3331     NoteLValueLocation(Info, Base);
3332     Info.addNotes(Notes);
3333     return false;
3334   }
3335 
3336   // Check that the variable is actually usable in constant expressions. For a
3337   // const integral variable or a reference, we might have a non-constant
3338   // initializer that we can nonetheless evaluate the initializer for. Such
3339   // variables are not usable in constant expressions. In C++98, the
3340   // initializer also syntactically needs to be an ICE.
3341   //
3342   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3343   // expressions here; doing so would regress diagnostics for things like
3344   // reading from a volatile constexpr variable.
3345   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3346        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3347       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3348        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3349     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3350     NoteLValueLocation(Info, Base);
3351   }
3352 
3353   // Never use the initializer of a weak variable, not even for constant
3354   // folding. We can't be sure that this is the definition that will be used.
3355   if (VD->isWeak()) {
3356     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3357     NoteLValueLocation(Info, Base);
3358     return false;
3359   }
3360 
3361   Result = VD->getEvaluatedValue();
3362   return true;
3363 }
3364 
3365 /// Get the base index of the given base class within an APValue representing
3366 /// the given derived class.
3367 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3368                              const CXXRecordDecl *Base) {
3369   Base = Base->getCanonicalDecl();
3370   unsigned Index = 0;
3371   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3372          E = Derived->bases_end(); I != E; ++I, ++Index) {
3373     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3374       return Index;
3375   }
3376 
3377   llvm_unreachable("base class missing from derived class's bases list");
3378 }
3379 
3380 /// Extract the value of a character from a string literal.
3381 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3382                                             uint64_t Index) {
3383   assert(!isa<SourceLocExpr>(Lit) &&
3384          "SourceLocExpr should have already been converted to a StringLiteral");
3385 
3386   // FIXME: Support MakeStringConstant
3387   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3388     std::string Str;
3389     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3390     assert(Index <= Str.size() && "Index too large");
3391     return APSInt::getUnsigned(Str.c_str()[Index]);
3392   }
3393 
3394   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3395     Lit = PE->getFunctionName();
3396   const StringLiteral *S = cast<StringLiteral>(Lit);
3397   const ConstantArrayType *CAT =
3398       Info.Ctx.getAsConstantArrayType(S->getType());
3399   assert(CAT && "string literal isn't an array");
3400   QualType CharType = CAT->getElementType();
3401   assert(CharType->isIntegerType() && "unexpected character type");
3402 
3403   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3404                CharType->isUnsignedIntegerType());
3405   if (Index < S->getLength())
3406     Value = S->getCodeUnit(Index);
3407   return Value;
3408 }
3409 
3410 // Expand a string literal into an array of characters.
3411 //
3412 // FIXME: This is inefficient; we should probably introduce something similar
3413 // to the LLVM ConstantDataArray to make this cheaper.
3414 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3415                                 APValue &Result,
3416                                 QualType AllocType = QualType()) {
3417   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3418       AllocType.isNull() ? S->getType() : AllocType);
3419   assert(CAT && "string literal isn't an array");
3420   QualType CharType = CAT->getElementType();
3421   assert(CharType->isIntegerType() && "unexpected character type");
3422 
3423   unsigned Elts = CAT->getSize().getZExtValue();
3424   Result = APValue(APValue::UninitArray(),
3425                    std::min(S->getLength(), Elts), Elts);
3426   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3427                CharType->isUnsignedIntegerType());
3428   if (Result.hasArrayFiller())
3429     Result.getArrayFiller() = APValue(Value);
3430   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3431     Value = S->getCodeUnit(I);
3432     Result.getArrayInitializedElt(I) = APValue(Value);
3433   }
3434 }
3435 
3436 // Expand an array so that it has more than Index filled elements.
3437 static void expandArray(APValue &Array, unsigned Index) {
3438   unsigned Size = Array.getArraySize();
3439   assert(Index < Size);
3440 
3441   // Always at least double the number of elements for which we store a value.
3442   unsigned OldElts = Array.getArrayInitializedElts();
3443   unsigned NewElts = std::max(Index+1, OldElts * 2);
3444   NewElts = std::min(Size, std::max(NewElts, 8u));
3445 
3446   // Copy the data across.
3447   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3448   for (unsigned I = 0; I != OldElts; ++I)
3449     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3450   for (unsigned I = OldElts; I != NewElts; ++I)
3451     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3452   if (NewValue.hasArrayFiller())
3453     NewValue.getArrayFiller() = Array.getArrayFiller();
3454   Array.swap(NewValue);
3455 }
3456 
3457 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3458 /// conversion. If it's of class type, we may assume that the copy operation
3459 /// is trivial. Note that this is never true for a union type with fields
3460 /// (because the copy always "reads" the active member) and always true for
3461 /// a non-class type.
3462 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3463 static bool isReadByLvalueToRvalueConversion(QualType T) {
3464   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3465   return !RD || isReadByLvalueToRvalueConversion(RD);
3466 }
3467 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3468   // FIXME: A trivial copy of a union copies the object representation, even if
3469   // the union is empty.
3470   if (RD->isUnion())
3471     return !RD->field_empty();
3472   if (RD->isEmpty())
3473     return false;
3474 
3475   for (auto *Field : RD->fields())
3476     if (!Field->isUnnamedBitfield() &&
3477         isReadByLvalueToRvalueConversion(Field->getType()))
3478       return true;
3479 
3480   for (auto &BaseSpec : RD->bases())
3481     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3482       return true;
3483 
3484   return false;
3485 }
3486 
3487 /// Diagnose an attempt to read from any unreadable field within the specified
3488 /// type, which might be a class type.
3489 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3490                                   QualType T) {
3491   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3492   if (!RD)
3493     return false;
3494 
3495   if (!RD->hasMutableFields())
3496     return false;
3497 
3498   for (auto *Field : RD->fields()) {
3499     // If we're actually going to read this field in some way, then it can't
3500     // be mutable. If we're in a union, then assigning to a mutable field
3501     // (even an empty one) can change the active member, so that's not OK.
3502     // FIXME: Add core issue number for the union case.
3503     if (Field->isMutable() &&
3504         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3505       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3506       Info.Note(Field->getLocation(), diag::note_declared_at);
3507       return true;
3508     }
3509 
3510     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3511       return true;
3512   }
3513 
3514   for (auto &BaseSpec : RD->bases())
3515     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3516       return true;
3517 
3518   // All mutable fields were empty, and thus not actually read.
3519   return false;
3520 }
3521 
3522 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3523                                         APValue::LValueBase Base,
3524                                         bool MutableSubobject = false) {
3525   // A temporary or transient heap allocation we created.
3526   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3527     return true;
3528 
3529   switch (Info.IsEvaluatingDecl) {
3530   case EvalInfo::EvaluatingDeclKind::None:
3531     return false;
3532 
3533   case EvalInfo::EvaluatingDeclKind::Ctor:
3534     // The variable whose initializer we're evaluating.
3535     if (Info.EvaluatingDecl == Base)
3536       return true;
3537 
3538     // A temporary lifetime-extended by the variable whose initializer we're
3539     // evaluating.
3540     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3541       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3542         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3543     return false;
3544 
3545   case EvalInfo::EvaluatingDeclKind::Dtor:
3546     // C++2a [expr.const]p6:
3547     //   [during constant destruction] the lifetime of a and its non-mutable
3548     //   subobjects (but not its mutable subobjects) [are] considered to start
3549     //   within e.
3550     if (MutableSubobject || Base != Info.EvaluatingDecl)
3551       return false;
3552     // FIXME: We can meaningfully extend this to cover non-const objects, but
3553     // we will need special handling: we should be able to access only
3554     // subobjects of such objects that are themselves declared const.
3555     QualType T = getType(Base);
3556     return T.isConstQualified() || T->isReferenceType();
3557   }
3558 
3559   llvm_unreachable("unknown evaluating decl kind");
3560 }
3561 
3562 namespace {
3563 /// A handle to a complete object (an object that is not a subobject of
3564 /// another object).
3565 struct CompleteObject {
3566   /// The identity of the object.
3567   APValue::LValueBase Base;
3568   /// The value of the complete object.
3569   APValue *Value;
3570   /// The type of the complete object.
3571   QualType Type;
3572 
3573   CompleteObject() : Value(nullptr) {}
3574   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3575       : Base(Base), Value(Value), Type(Type) {}
3576 
3577   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3578     // If this isn't a "real" access (eg, if it's just accessing the type
3579     // info), allow it. We assume the type doesn't change dynamically for
3580     // subobjects of constexpr objects (even though we'd hit UB here if it
3581     // did). FIXME: Is this right?
3582     if (!isAnyAccess(AK))
3583       return true;
3584 
3585     // In C++14 onwards, it is permitted to read a mutable member whose
3586     // lifetime began within the evaluation.
3587     // FIXME: Should we also allow this in C++11?
3588     if (!Info.getLangOpts().CPlusPlus14)
3589       return false;
3590     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3591   }
3592 
3593   explicit operator bool() const { return !Type.isNull(); }
3594 };
3595 } // end anonymous namespace
3596 
3597 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3598                                  bool IsMutable = false) {
3599   // C++ [basic.type.qualifier]p1:
3600   // - A const object is an object of type const T or a non-mutable subobject
3601   //   of a const object.
3602   if (ObjType.isConstQualified() && !IsMutable)
3603     SubobjType.addConst();
3604   // - A volatile object is an object of type const T or a subobject of a
3605   //   volatile object.
3606   if (ObjType.isVolatileQualified())
3607     SubobjType.addVolatile();
3608   return SubobjType;
3609 }
3610 
3611 /// Find the designated sub-object of an rvalue.
3612 template<typename SubobjectHandler>
3613 typename SubobjectHandler::result_type
3614 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3615               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3616   if (Sub.Invalid)
3617     // A diagnostic will have already been produced.
3618     return handler.failed();
3619   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3620     if (Info.getLangOpts().CPlusPlus11)
3621       Info.FFDiag(E, Sub.isOnePastTheEnd()
3622                          ? diag::note_constexpr_access_past_end
3623                          : diag::note_constexpr_access_unsized_array)
3624           << handler.AccessKind;
3625     else
3626       Info.FFDiag(E);
3627     return handler.failed();
3628   }
3629 
3630   APValue *O = Obj.Value;
3631   QualType ObjType = Obj.Type;
3632   const FieldDecl *LastField = nullptr;
3633   const FieldDecl *VolatileField = nullptr;
3634 
3635   // Walk the designator's path to find the subobject.
3636   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3637     // Reading an indeterminate value is undefined, but assigning over one is OK.
3638     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3639         (O->isIndeterminate() &&
3640          !isValidIndeterminateAccess(handler.AccessKind))) {
3641       if (!Info.checkingPotentialConstantExpression())
3642         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3643             << handler.AccessKind << O->isIndeterminate();
3644       return handler.failed();
3645     }
3646 
3647     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3648     //    const and volatile semantics are not applied on an object under
3649     //    {con,de}struction.
3650     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3651         ObjType->isRecordType() &&
3652         Info.isEvaluatingCtorDtor(
3653             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3654                                          Sub.Entries.begin() + I)) !=
3655                           ConstructionPhase::None) {
3656       ObjType = Info.Ctx.getCanonicalType(ObjType);
3657       ObjType.removeLocalConst();
3658       ObjType.removeLocalVolatile();
3659     }
3660 
3661     // If this is our last pass, check that the final object type is OK.
3662     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3663       // Accesses to volatile objects are prohibited.
3664       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3665         if (Info.getLangOpts().CPlusPlus) {
3666           int DiagKind;
3667           SourceLocation Loc;
3668           const NamedDecl *Decl = nullptr;
3669           if (VolatileField) {
3670             DiagKind = 2;
3671             Loc = VolatileField->getLocation();
3672             Decl = VolatileField;
3673           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3674             DiagKind = 1;
3675             Loc = VD->getLocation();
3676             Decl = VD;
3677           } else {
3678             DiagKind = 0;
3679             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3680               Loc = E->getExprLoc();
3681           }
3682           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3683               << handler.AccessKind << DiagKind << Decl;
3684           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3685         } else {
3686           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3687         }
3688         return handler.failed();
3689       }
3690 
3691       // If we are reading an object of class type, there may still be more
3692       // things we need to check: if there are any mutable subobjects, we
3693       // cannot perform this read. (This only happens when performing a trivial
3694       // copy or assignment.)
3695       if (ObjType->isRecordType() &&
3696           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3697           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3698         return handler.failed();
3699     }
3700 
3701     if (I == N) {
3702       if (!handler.found(*O, ObjType))
3703         return false;
3704 
3705       // If we modified a bit-field, truncate it to the right width.
3706       if (isModification(handler.AccessKind) &&
3707           LastField && LastField->isBitField() &&
3708           !truncateBitfieldValue(Info, E, *O, LastField))
3709         return false;
3710 
3711       return true;
3712     }
3713 
3714     LastField = nullptr;
3715     if (ObjType->isArrayType()) {
3716       // Next subobject is an array element.
3717       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3718       assert(CAT && "vla in literal type?");
3719       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3720       if (CAT->getSize().ule(Index)) {
3721         // Note, it should not be possible to form a pointer with a valid
3722         // designator which points more than one past the end of the array.
3723         if (Info.getLangOpts().CPlusPlus11)
3724           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3725             << handler.AccessKind;
3726         else
3727           Info.FFDiag(E);
3728         return handler.failed();
3729       }
3730 
3731       ObjType = CAT->getElementType();
3732 
3733       if (O->getArrayInitializedElts() > Index)
3734         O = &O->getArrayInitializedElt(Index);
3735       else if (!isRead(handler.AccessKind)) {
3736         expandArray(*O, Index);
3737         O = &O->getArrayInitializedElt(Index);
3738       } else
3739         O = &O->getArrayFiller();
3740     } else if (ObjType->isAnyComplexType()) {
3741       // Next subobject is a complex number.
3742       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3743       if (Index > 1) {
3744         if (Info.getLangOpts().CPlusPlus11)
3745           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3746             << handler.AccessKind;
3747         else
3748           Info.FFDiag(E);
3749         return handler.failed();
3750       }
3751 
3752       ObjType = getSubobjectType(
3753           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3754 
3755       assert(I == N - 1 && "extracting subobject of scalar?");
3756       if (O->isComplexInt()) {
3757         return handler.found(Index ? O->getComplexIntImag()
3758                                    : O->getComplexIntReal(), ObjType);
3759       } else {
3760         assert(O->isComplexFloat());
3761         return handler.found(Index ? O->getComplexFloatImag()
3762                                    : O->getComplexFloatReal(), ObjType);
3763       }
3764     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3765       if (Field->isMutable() &&
3766           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3767         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3768           << handler.AccessKind << Field;
3769         Info.Note(Field->getLocation(), diag::note_declared_at);
3770         return handler.failed();
3771       }
3772 
3773       // Next subobject is a class, struct or union field.
3774       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3775       if (RD->isUnion()) {
3776         const FieldDecl *UnionField = O->getUnionField();
3777         if (!UnionField ||
3778             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3779           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3780             // Placement new onto an inactive union member makes it active.
3781             O->setUnion(Field, APValue());
3782           } else {
3783             // FIXME: If O->getUnionValue() is absent, report that there's no
3784             // active union member rather than reporting the prior active union
3785             // member. We'll need to fix nullptr_t to not use APValue() as its
3786             // representation first.
3787             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3788                 << handler.AccessKind << Field << !UnionField << UnionField;
3789             return handler.failed();
3790           }
3791         }
3792         O = &O->getUnionValue();
3793       } else
3794         O = &O->getStructField(Field->getFieldIndex());
3795 
3796       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3797       LastField = Field;
3798       if (Field->getType().isVolatileQualified())
3799         VolatileField = Field;
3800     } else {
3801       // Next subobject is a base class.
3802       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3803       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3804       O = &O->getStructBase(getBaseIndex(Derived, Base));
3805 
3806       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3807     }
3808   }
3809 }
3810 
3811 namespace {
3812 struct ExtractSubobjectHandler {
3813   EvalInfo &Info;
3814   const Expr *E;
3815   APValue &Result;
3816   const AccessKinds AccessKind;
3817 
3818   typedef bool result_type;
3819   bool failed() { return false; }
3820   bool found(APValue &Subobj, QualType SubobjType) {
3821     Result = Subobj;
3822     if (AccessKind == AK_ReadObjectRepresentation)
3823       return true;
3824     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3825   }
3826   bool found(APSInt &Value, QualType SubobjType) {
3827     Result = APValue(Value);
3828     return true;
3829   }
3830   bool found(APFloat &Value, QualType SubobjType) {
3831     Result = APValue(Value);
3832     return true;
3833   }
3834 };
3835 } // end anonymous namespace
3836 
3837 /// Extract the designated sub-object of an rvalue.
3838 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3839                              const CompleteObject &Obj,
3840                              const SubobjectDesignator &Sub, APValue &Result,
3841                              AccessKinds AK = AK_Read) {
3842   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3843   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3844   return findSubobject(Info, E, Obj, Sub, Handler);
3845 }
3846 
3847 namespace {
3848 struct ModifySubobjectHandler {
3849   EvalInfo &Info;
3850   APValue &NewVal;
3851   const Expr *E;
3852 
3853   typedef bool result_type;
3854   static const AccessKinds AccessKind = AK_Assign;
3855 
3856   bool checkConst(QualType QT) {
3857     // Assigning to a const object has undefined behavior.
3858     if (QT.isConstQualified()) {
3859       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3860       return false;
3861     }
3862     return true;
3863   }
3864 
3865   bool failed() { return false; }
3866   bool found(APValue &Subobj, QualType SubobjType) {
3867     if (!checkConst(SubobjType))
3868       return false;
3869     // We've been given ownership of NewVal, so just swap it in.
3870     Subobj.swap(NewVal);
3871     return true;
3872   }
3873   bool found(APSInt &Value, QualType SubobjType) {
3874     if (!checkConst(SubobjType))
3875       return false;
3876     if (!NewVal.isInt()) {
3877       // Maybe trying to write a cast pointer value into a complex?
3878       Info.FFDiag(E);
3879       return false;
3880     }
3881     Value = NewVal.getInt();
3882     return true;
3883   }
3884   bool found(APFloat &Value, QualType SubobjType) {
3885     if (!checkConst(SubobjType))
3886       return false;
3887     Value = NewVal.getFloat();
3888     return true;
3889   }
3890 };
3891 } // end anonymous namespace
3892 
3893 const AccessKinds ModifySubobjectHandler::AccessKind;
3894 
3895 /// Update the designated sub-object of an rvalue to the given value.
3896 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3897                             const CompleteObject &Obj,
3898                             const SubobjectDesignator &Sub,
3899                             APValue &NewVal) {
3900   ModifySubobjectHandler Handler = { Info, NewVal, E };
3901   return findSubobject(Info, E, Obj, Sub, Handler);
3902 }
3903 
3904 /// Find the position where two subobject designators diverge, or equivalently
3905 /// the length of the common initial subsequence.
3906 static unsigned FindDesignatorMismatch(QualType ObjType,
3907                                        const SubobjectDesignator &A,
3908                                        const SubobjectDesignator &B,
3909                                        bool &WasArrayIndex) {
3910   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3911   for (/**/; I != N; ++I) {
3912     if (!ObjType.isNull() &&
3913         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3914       // Next subobject is an array element.
3915       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3916         WasArrayIndex = true;
3917         return I;
3918       }
3919       if (ObjType->isAnyComplexType())
3920         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3921       else
3922         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3923     } else {
3924       if (A.Entries[I].getAsBaseOrMember() !=
3925           B.Entries[I].getAsBaseOrMember()) {
3926         WasArrayIndex = false;
3927         return I;
3928       }
3929       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3930         // Next subobject is a field.
3931         ObjType = FD->getType();
3932       else
3933         // Next subobject is a base class.
3934         ObjType = QualType();
3935     }
3936   }
3937   WasArrayIndex = false;
3938   return I;
3939 }
3940 
3941 /// Determine whether the given subobject designators refer to elements of the
3942 /// same array object.
3943 static bool AreElementsOfSameArray(QualType ObjType,
3944                                    const SubobjectDesignator &A,
3945                                    const SubobjectDesignator &B) {
3946   if (A.Entries.size() != B.Entries.size())
3947     return false;
3948 
3949   bool IsArray = A.MostDerivedIsArrayElement;
3950   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3951     // A is a subobject of the array element.
3952     return false;
3953 
3954   // If A (and B) designates an array element, the last entry will be the array
3955   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3956   // of length 1' case, and the entire path must match.
3957   bool WasArrayIndex;
3958   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3959   return CommonLength >= A.Entries.size() - IsArray;
3960 }
3961 
3962 /// Find the complete object to which an LValue refers.
3963 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3964                                          AccessKinds AK, const LValue &LVal,
3965                                          QualType LValType) {
3966   if (LVal.InvalidBase) {
3967     Info.FFDiag(E);
3968     return CompleteObject();
3969   }
3970 
3971   if (!LVal.Base) {
3972     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3973     return CompleteObject();
3974   }
3975 
3976   CallStackFrame *Frame = nullptr;
3977   unsigned Depth = 0;
3978   if (LVal.getLValueCallIndex()) {
3979     std::tie(Frame, Depth) =
3980         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3981     if (!Frame) {
3982       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3983         << AK << LVal.Base.is<const ValueDecl*>();
3984       NoteLValueLocation(Info, LVal.Base);
3985       return CompleteObject();
3986     }
3987   }
3988 
3989   bool IsAccess = isAnyAccess(AK);
3990 
3991   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3992   // is not a constant expression (even if the object is non-volatile). We also
3993   // apply this rule to C++98, in order to conform to the expected 'volatile'
3994   // semantics.
3995   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3996     if (Info.getLangOpts().CPlusPlus)
3997       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3998         << AK << LValType;
3999     else
4000       Info.FFDiag(E);
4001     return CompleteObject();
4002   }
4003 
4004   // Compute value storage location and type of base object.
4005   APValue *BaseVal = nullptr;
4006   QualType BaseType = getType(LVal.Base);
4007 
4008   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4009       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4010     // This is the object whose initializer we're evaluating, so its lifetime
4011     // started in the current evaluation.
4012     BaseVal = Info.EvaluatingDeclValue;
4013   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4014     // Allow reading from a GUID declaration.
4015     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4016       if (isModification(AK)) {
4017         // All the remaining cases do not permit modification of the object.
4018         Info.FFDiag(E, diag::note_constexpr_modify_global);
4019         return CompleteObject();
4020       }
4021       APValue &V = GD->getAsAPValue();
4022       if (V.isAbsent()) {
4023         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4024             << GD->getType();
4025         return CompleteObject();
4026       }
4027       return CompleteObject(LVal.Base, &V, GD->getType());
4028     }
4029 
4030     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4031     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4032       if (isModification(AK)) {
4033         Info.FFDiag(E, diag::note_constexpr_modify_global);
4034         return CompleteObject();
4035       }
4036       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4037                             GCD->getType());
4038     }
4039 
4040     // Allow reading from template parameter objects.
4041     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4042       if (isModification(AK)) {
4043         Info.FFDiag(E, diag::note_constexpr_modify_global);
4044         return CompleteObject();
4045       }
4046       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4047                             TPO->getType());
4048     }
4049 
4050     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4051     // In C++11, constexpr, non-volatile variables initialized with constant
4052     // expressions are constant expressions too. Inside constexpr functions,
4053     // parameters are constant expressions even if they're non-const.
4054     // In C++1y, objects local to a constant expression (those with a Frame) are
4055     // both readable and writable inside constant expressions.
4056     // In C, such things can also be folded, although they are not ICEs.
4057     const VarDecl *VD = dyn_cast<VarDecl>(D);
4058     if (VD) {
4059       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4060         VD = VDef;
4061     }
4062     if (!VD || VD->isInvalidDecl()) {
4063       Info.FFDiag(E);
4064       return CompleteObject();
4065     }
4066 
4067     bool IsConstant = BaseType.isConstant(Info.Ctx);
4068 
4069     // Unless we're looking at a local variable or argument in a constexpr call,
4070     // the variable we're reading must be const.
4071     if (!Frame) {
4072       if (IsAccess && isa<ParmVarDecl>(VD)) {
4073         // Access of a parameter that's not associated with a frame isn't going
4074         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4075         // suitable diagnostic.
4076       } else if (Info.getLangOpts().CPlusPlus14 &&
4077                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4078         // OK, we can read and modify an object if we're in the process of
4079         // evaluating its initializer, because its lifetime began in this
4080         // evaluation.
4081       } else if (isModification(AK)) {
4082         // All the remaining cases do not permit modification of the object.
4083         Info.FFDiag(E, diag::note_constexpr_modify_global);
4084         return CompleteObject();
4085       } else if (VD->isConstexpr()) {
4086         // OK, we can read this variable.
4087       } else if (BaseType->isIntegralOrEnumerationType()) {
4088         if (!IsConstant) {
4089           if (!IsAccess)
4090             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4091           if (Info.getLangOpts().CPlusPlus) {
4092             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4093             Info.Note(VD->getLocation(), diag::note_declared_at);
4094           } else {
4095             Info.FFDiag(E);
4096           }
4097           return CompleteObject();
4098         }
4099       } else if (!IsAccess) {
4100         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4101       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4102                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4103         // This variable might end up being constexpr. Don't diagnose it yet.
4104       } else if (IsConstant) {
4105         // Keep evaluating to see what we can do. In particular, we support
4106         // folding of const floating-point types, in order to make static const
4107         // data members of such types (supported as an extension) more useful.
4108         if (Info.getLangOpts().CPlusPlus) {
4109           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4110                               ? diag::note_constexpr_ltor_non_constexpr
4111                               : diag::note_constexpr_ltor_non_integral, 1)
4112               << VD << BaseType;
4113           Info.Note(VD->getLocation(), diag::note_declared_at);
4114         } else {
4115           Info.CCEDiag(E);
4116         }
4117       } else {
4118         // Never allow reading a non-const value.
4119         if (Info.getLangOpts().CPlusPlus) {
4120           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4121                              ? diag::note_constexpr_ltor_non_constexpr
4122                              : diag::note_constexpr_ltor_non_integral, 1)
4123               << VD << BaseType;
4124           Info.Note(VD->getLocation(), diag::note_declared_at);
4125         } else {
4126           Info.FFDiag(E);
4127         }
4128         return CompleteObject();
4129       }
4130     }
4131 
4132     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4133       return CompleteObject();
4134   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4135     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4136     if (!Alloc) {
4137       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4138       return CompleteObject();
4139     }
4140     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4141                           LVal.Base.getDynamicAllocType());
4142   } else {
4143     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4144 
4145     if (!Frame) {
4146       if (const MaterializeTemporaryExpr *MTE =
4147               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4148         assert(MTE->getStorageDuration() == SD_Static &&
4149                "should have a frame for a non-global materialized temporary");
4150 
4151         // C++20 [expr.const]p4: [DR2126]
4152         //   An object or reference is usable in constant expressions if it is
4153         //   - a temporary object of non-volatile const-qualified literal type
4154         //     whose lifetime is extended to that of a variable that is usable
4155         //     in constant expressions
4156         //
4157         // C++20 [expr.const]p5:
4158         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4159         //   - a non-volatile glvalue that refers to an object that is usable
4160         //     in constant expressions, or
4161         //   - a non-volatile glvalue of literal type that refers to a
4162         //     non-volatile object whose lifetime began within the evaluation
4163         //     of E;
4164         //
4165         // C++11 misses the 'began within the evaluation of e' check and
4166         // instead allows all temporaries, including things like:
4167         //   int &&r = 1;
4168         //   int x = ++r;
4169         //   constexpr int k = r;
4170         // Therefore we use the C++14-onwards rules in C++11 too.
4171         //
4172         // Note that temporaries whose lifetimes began while evaluating a
4173         // variable's constructor are not usable while evaluating the
4174         // corresponding destructor, not even if they're of const-qualified
4175         // types.
4176         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4177             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4178           if (!IsAccess)
4179             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4180           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4181           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4182           return CompleteObject();
4183         }
4184 
4185         BaseVal = MTE->getOrCreateValue(false);
4186         assert(BaseVal && "got reference to unevaluated temporary");
4187       } else {
4188         if (!IsAccess)
4189           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4190         APValue Val;
4191         LVal.moveInto(Val);
4192         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4193             << AK
4194             << Val.getAsString(Info.Ctx,
4195                                Info.Ctx.getLValueReferenceType(LValType));
4196         NoteLValueLocation(Info, LVal.Base);
4197         return CompleteObject();
4198       }
4199     } else {
4200       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4201       assert(BaseVal && "missing value for temporary");
4202     }
4203   }
4204 
4205   // In C++14, we can't safely access any mutable state when we might be
4206   // evaluating after an unmodeled side effect. Parameters are modeled as state
4207   // in the caller, but aren't visible once the call returns, so they can be
4208   // modified in a speculatively-evaluated call.
4209   //
4210   // FIXME: Not all local state is mutable. Allow local constant subobjects
4211   // to be read here (but take care with 'mutable' fields).
4212   unsigned VisibleDepth = Depth;
4213   if (llvm::isa_and_nonnull<ParmVarDecl>(
4214           LVal.Base.dyn_cast<const ValueDecl *>()))
4215     ++VisibleDepth;
4216   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4217        Info.EvalStatus.HasSideEffects) ||
4218       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4219     return CompleteObject();
4220 
4221   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4222 }
4223 
4224 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4225 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4226 /// glvalue referred to by an entity of reference type.
4227 ///
4228 /// \param Info - Information about the ongoing evaluation.
4229 /// \param Conv - The expression for which we are performing the conversion.
4230 ///               Used for diagnostics.
4231 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4232 ///               case of a non-class type).
4233 /// \param LVal - The glvalue on which we are attempting to perform this action.
4234 /// \param RVal - The produced value will be placed here.
4235 /// \param WantObjectRepresentation - If true, we're looking for the object
4236 ///               representation rather than the value, and in particular,
4237 ///               there is no requirement that the result be fully initialized.
4238 static bool
4239 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4240                                const LValue &LVal, APValue &RVal,
4241                                bool WantObjectRepresentation = false) {
4242   if (LVal.Designator.Invalid)
4243     return false;
4244 
4245   // Check for special cases where there is no existing APValue to look at.
4246   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4247 
4248   AccessKinds AK =
4249       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4250 
4251   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4252     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4253       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4254       // initializer until now for such expressions. Such an expression can't be
4255       // an ICE in C, so this only matters for fold.
4256       if (Type.isVolatileQualified()) {
4257         Info.FFDiag(Conv);
4258         return false;
4259       }
4260 
4261       APValue Lit;
4262       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4263         return false;
4264 
4265       // According to GCC info page:
4266       //
4267       // 6.28 Compound Literals
4268       //
4269       // As an optimization, G++ sometimes gives array compound literals longer
4270       // lifetimes: when the array either appears outside a function or has a
4271       // const-qualified type. If foo and its initializer had elements of type
4272       // char *const rather than char *, or if foo were a global variable, the
4273       // array would have static storage duration. But it is probably safest
4274       // just to avoid the use of array compound literals in C++ code.
4275       //
4276       // Obey that rule by checking constness for converted array types.
4277 
4278       QualType CLETy = CLE->getType();
4279       if (CLETy->isArrayType() && !Type->isArrayType()) {
4280         if (!CLETy.isConstant(Info.Ctx)) {
4281           Info.FFDiag(Conv);
4282           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4283           return false;
4284         }
4285       }
4286 
4287       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4288       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4289     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4290       // Special-case character extraction so we don't have to construct an
4291       // APValue for the whole string.
4292       assert(LVal.Designator.Entries.size() <= 1 &&
4293              "Can only read characters from string literals");
4294       if (LVal.Designator.Entries.empty()) {
4295         // Fail for now for LValue to RValue conversion of an array.
4296         // (This shouldn't show up in C/C++, but it could be triggered by a
4297         // weird EvaluateAsRValue call from a tool.)
4298         Info.FFDiag(Conv);
4299         return false;
4300       }
4301       if (LVal.Designator.isOnePastTheEnd()) {
4302         if (Info.getLangOpts().CPlusPlus11)
4303           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4304         else
4305           Info.FFDiag(Conv);
4306         return false;
4307       }
4308       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4309       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4310       return true;
4311     }
4312   }
4313 
4314   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4315   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4316 }
4317 
4318 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4319 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4320                              QualType LValType, APValue &Val) {
4321   if (LVal.Designator.Invalid)
4322     return false;
4323 
4324   if (!Info.getLangOpts().CPlusPlus14) {
4325     Info.FFDiag(E);
4326     return false;
4327   }
4328 
4329   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4330   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4331 }
4332 
4333 namespace {
4334 struct CompoundAssignSubobjectHandler {
4335   EvalInfo &Info;
4336   const CompoundAssignOperator *E;
4337   QualType PromotedLHSType;
4338   BinaryOperatorKind Opcode;
4339   const APValue &RHS;
4340 
4341   static const AccessKinds AccessKind = AK_Assign;
4342 
4343   typedef bool result_type;
4344 
4345   bool checkConst(QualType QT) {
4346     // Assigning to a const object has undefined behavior.
4347     if (QT.isConstQualified()) {
4348       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4349       return false;
4350     }
4351     return true;
4352   }
4353 
4354   bool failed() { return false; }
4355   bool found(APValue &Subobj, QualType SubobjType) {
4356     switch (Subobj.getKind()) {
4357     case APValue::Int:
4358       return found(Subobj.getInt(), SubobjType);
4359     case APValue::Float:
4360       return found(Subobj.getFloat(), SubobjType);
4361     case APValue::ComplexInt:
4362     case APValue::ComplexFloat:
4363       // FIXME: Implement complex compound assignment.
4364       Info.FFDiag(E);
4365       return false;
4366     case APValue::LValue:
4367       return foundPointer(Subobj, SubobjType);
4368     case APValue::Vector:
4369       return foundVector(Subobj, SubobjType);
4370     default:
4371       // FIXME: can this happen?
4372       Info.FFDiag(E);
4373       return false;
4374     }
4375   }
4376 
4377   bool foundVector(APValue &Value, QualType SubobjType) {
4378     if (!checkConst(SubobjType))
4379       return false;
4380 
4381     if (!SubobjType->isVectorType()) {
4382       Info.FFDiag(E);
4383       return false;
4384     }
4385     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4386   }
4387 
4388   bool found(APSInt &Value, QualType SubobjType) {
4389     if (!checkConst(SubobjType))
4390       return false;
4391 
4392     if (!SubobjType->isIntegerType()) {
4393       // We don't support compound assignment on integer-cast-to-pointer
4394       // values.
4395       Info.FFDiag(E);
4396       return false;
4397     }
4398 
4399     if (RHS.isInt()) {
4400       APSInt LHS =
4401           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4402       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4403         return false;
4404       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4405       return true;
4406     } else if (RHS.isFloat()) {
4407       const FPOptions FPO = E->getFPFeaturesInEffect(
4408                                     Info.Ctx.getLangOpts());
4409       APFloat FValue(0.0);
4410       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4411                                   PromotedLHSType, FValue) &&
4412              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4413              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4414                                   Value);
4415     }
4416 
4417     Info.FFDiag(E);
4418     return false;
4419   }
4420   bool found(APFloat &Value, QualType SubobjType) {
4421     return checkConst(SubobjType) &&
4422            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4423                                   Value) &&
4424            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4425            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4426   }
4427   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4428     if (!checkConst(SubobjType))
4429       return false;
4430 
4431     QualType PointeeType;
4432     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4433       PointeeType = PT->getPointeeType();
4434 
4435     if (PointeeType.isNull() || !RHS.isInt() ||
4436         (Opcode != BO_Add && Opcode != BO_Sub)) {
4437       Info.FFDiag(E);
4438       return false;
4439     }
4440 
4441     APSInt Offset = RHS.getInt();
4442     if (Opcode == BO_Sub)
4443       negateAsSigned(Offset);
4444 
4445     LValue LVal;
4446     LVal.setFrom(Info.Ctx, Subobj);
4447     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4448       return false;
4449     LVal.moveInto(Subobj);
4450     return true;
4451   }
4452 };
4453 } // end anonymous namespace
4454 
4455 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4456 
4457 /// Perform a compound assignment of LVal <op>= RVal.
4458 static bool handleCompoundAssignment(EvalInfo &Info,
4459                                      const CompoundAssignOperator *E,
4460                                      const LValue &LVal, QualType LValType,
4461                                      QualType PromotedLValType,
4462                                      BinaryOperatorKind Opcode,
4463                                      const APValue &RVal) {
4464   if (LVal.Designator.Invalid)
4465     return false;
4466 
4467   if (!Info.getLangOpts().CPlusPlus14) {
4468     Info.FFDiag(E);
4469     return false;
4470   }
4471 
4472   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4473   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4474                                              RVal };
4475   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4476 }
4477 
4478 namespace {
4479 struct IncDecSubobjectHandler {
4480   EvalInfo &Info;
4481   const UnaryOperator *E;
4482   AccessKinds AccessKind;
4483   APValue *Old;
4484 
4485   typedef bool result_type;
4486 
4487   bool checkConst(QualType QT) {
4488     // Assigning to a const object has undefined behavior.
4489     if (QT.isConstQualified()) {
4490       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4491       return false;
4492     }
4493     return true;
4494   }
4495 
4496   bool failed() { return false; }
4497   bool found(APValue &Subobj, QualType SubobjType) {
4498     // Stash the old value. Also clear Old, so we don't clobber it later
4499     // if we're post-incrementing a complex.
4500     if (Old) {
4501       *Old = Subobj;
4502       Old = nullptr;
4503     }
4504 
4505     switch (Subobj.getKind()) {
4506     case APValue::Int:
4507       return found(Subobj.getInt(), SubobjType);
4508     case APValue::Float:
4509       return found(Subobj.getFloat(), SubobjType);
4510     case APValue::ComplexInt:
4511       return found(Subobj.getComplexIntReal(),
4512                    SubobjType->castAs<ComplexType>()->getElementType()
4513                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4514     case APValue::ComplexFloat:
4515       return found(Subobj.getComplexFloatReal(),
4516                    SubobjType->castAs<ComplexType>()->getElementType()
4517                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4518     case APValue::LValue:
4519       return foundPointer(Subobj, SubobjType);
4520     default:
4521       // FIXME: can this happen?
4522       Info.FFDiag(E);
4523       return false;
4524     }
4525   }
4526   bool found(APSInt &Value, QualType SubobjType) {
4527     if (!checkConst(SubobjType))
4528       return false;
4529 
4530     if (!SubobjType->isIntegerType()) {
4531       // We don't support increment / decrement on integer-cast-to-pointer
4532       // values.
4533       Info.FFDiag(E);
4534       return false;
4535     }
4536 
4537     if (Old) *Old = APValue(Value);
4538 
4539     // bool arithmetic promotes to int, and the conversion back to bool
4540     // doesn't reduce mod 2^n, so special-case it.
4541     if (SubobjType->isBooleanType()) {
4542       if (AccessKind == AK_Increment)
4543         Value = 1;
4544       else
4545         Value = !Value;
4546       return true;
4547     }
4548 
4549     bool WasNegative = Value.isNegative();
4550     if (AccessKind == AK_Increment) {
4551       ++Value;
4552 
4553       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4554         APSInt ActualValue(Value, /*IsUnsigned*/true);
4555         return HandleOverflow(Info, E, ActualValue, SubobjType);
4556       }
4557     } else {
4558       --Value;
4559 
4560       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4561         unsigned BitWidth = Value.getBitWidth();
4562         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4563         ActualValue.setBit(BitWidth);
4564         return HandleOverflow(Info, E, ActualValue, SubobjType);
4565       }
4566     }
4567     return true;
4568   }
4569   bool found(APFloat &Value, QualType SubobjType) {
4570     if (!checkConst(SubobjType))
4571       return false;
4572 
4573     if (Old) *Old = APValue(Value);
4574 
4575     APFloat One(Value.getSemantics(), 1);
4576     if (AccessKind == AK_Increment)
4577       Value.add(One, APFloat::rmNearestTiesToEven);
4578     else
4579       Value.subtract(One, APFloat::rmNearestTiesToEven);
4580     return true;
4581   }
4582   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4583     if (!checkConst(SubobjType))
4584       return false;
4585 
4586     QualType PointeeType;
4587     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4588       PointeeType = PT->getPointeeType();
4589     else {
4590       Info.FFDiag(E);
4591       return false;
4592     }
4593 
4594     LValue LVal;
4595     LVal.setFrom(Info.Ctx, Subobj);
4596     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4597                                      AccessKind == AK_Increment ? 1 : -1))
4598       return false;
4599     LVal.moveInto(Subobj);
4600     return true;
4601   }
4602 };
4603 } // end anonymous namespace
4604 
4605 /// Perform an increment or decrement on LVal.
4606 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4607                          QualType LValType, bool IsIncrement, APValue *Old) {
4608   if (LVal.Designator.Invalid)
4609     return false;
4610 
4611   if (!Info.getLangOpts().CPlusPlus14) {
4612     Info.FFDiag(E);
4613     return false;
4614   }
4615 
4616   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4617   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4618   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4619   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4620 }
4621 
4622 /// Build an lvalue for the object argument of a member function call.
4623 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4624                                    LValue &This) {
4625   if (Object->getType()->isPointerType() && Object->isPRValue())
4626     return EvaluatePointer(Object, This, Info);
4627 
4628   if (Object->isGLValue())
4629     return EvaluateLValue(Object, This, Info);
4630 
4631   if (Object->getType()->isLiteralType(Info.Ctx))
4632     return EvaluateTemporary(Object, This, Info);
4633 
4634   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4635   return false;
4636 }
4637 
4638 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4639 /// lvalue referring to the result.
4640 ///
4641 /// \param Info - Information about the ongoing evaluation.
4642 /// \param LV - An lvalue referring to the base of the member pointer.
4643 /// \param RHS - The member pointer expression.
4644 /// \param IncludeMember - Specifies whether the member itself is included in
4645 ///        the resulting LValue subobject designator. This is not possible when
4646 ///        creating a bound member function.
4647 /// \return The field or method declaration to which the member pointer refers,
4648 ///         or 0 if evaluation fails.
4649 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4650                                                   QualType LVType,
4651                                                   LValue &LV,
4652                                                   const Expr *RHS,
4653                                                   bool IncludeMember = true) {
4654   MemberPtr MemPtr;
4655   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4656     return nullptr;
4657 
4658   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4659   // member value, the behavior is undefined.
4660   if (!MemPtr.getDecl()) {
4661     // FIXME: Specific diagnostic.
4662     Info.FFDiag(RHS);
4663     return nullptr;
4664   }
4665 
4666   if (MemPtr.isDerivedMember()) {
4667     // This is a member of some derived class. Truncate LV appropriately.
4668     // The end of the derived-to-base path for the base object must match the
4669     // derived-to-base path for the member pointer.
4670     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4671         LV.Designator.Entries.size()) {
4672       Info.FFDiag(RHS);
4673       return nullptr;
4674     }
4675     unsigned PathLengthToMember =
4676         LV.Designator.Entries.size() - MemPtr.Path.size();
4677     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4678       const CXXRecordDecl *LVDecl = getAsBaseClass(
4679           LV.Designator.Entries[PathLengthToMember + I]);
4680       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4681       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4682         Info.FFDiag(RHS);
4683         return nullptr;
4684       }
4685     }
4686 
4687     // Truncate the lvalue to the appropriate derived class.
4688     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4689                             PathLengthToMember))
4690       return nullptr;
4691   } else if (!MemPtr.Path.empty()) {
4692     // Extend the LValue path with the member pointer's path.
4693     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4694                                   MemPtr.Path.size() + IncludeMember);
4695 
4696     // Walk down to the appropriate base class.
4697     if (const PointerType *PT = LVType->getAs<PointerType>())
4698       LVType = PT->getPointeeType();
4699     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4700     assert(RD && "member pointer access on non-class-type expression");
4701     // The first class in the path is that of the lvalue.
4702     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4703       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4704       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4705         return nullptr;
4706       RD = Base;
4707     }
4708     // Finally cast to the class containing the member.
4709     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4710                                 MemPtr.getContainingRecord()))
4711       return nullptr;
4712   }
4713 
4714   // Add the member. Note that we cannot build bound member functions here.
4715   if (IncludeMember) {
4716     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4717       if (!HandleLValueMember(Info, RHS, LV, FD))
4718         return nullptr;
4719     } else if (const IndirectFieldDecl *IFD =
4720                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4721       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4722         return nullptr;
4723     } else {
4724       llvm_unreachable("can't construct reference to bound member function");
4725     }
4726   }
4727 
4728   return MemPtr.getDecl();
4729 }
4730 
4731 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4732                                                   const BinaryOperator *BO,
4733                                                   LValue &LV,
4734                                                   bool IncludeMember = true) {
4735   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4736 
4737   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4738     if (Info.noteFailure()) {
4739       MemberPtr MemPtr;
4740       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4741     }
4742     return nullptr;
4743   }
4744 
4745   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4746                                    BO->getRHS(), IncludeMember);
4747 }
4748 
4749 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4750 /// the provided lvalue, which currently refers to the base object.
4751 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4752                                     LValue &Result) {
4753   SubobjectDesignator &D = Result.Designator;
4754   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4755     return false;
4756 
4757   QualType TargetQT = E->getType();
4758   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4759     TargetQT = PT->getPointeeType();
4760 
4761   // Check this cast lands within the final derived-to-base subobject path.
4762   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4763     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4764       << D.MostDerivedType << TargetQT;
4765     return false;
4766   }
4767 
4768   // Check the type of the final cast. We don't need to check the path,
4769   // since a cast can only be formed if the path is unique.
4770   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4771   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4772   const CXXRecordDecl *FinalType;
4773   if (NewEntriesSize == D.MostDerivedPathLength)
4774     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4775   else
4776     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4777   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4778     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4779       << D.MostDerivedType << TargetQT;
4780     return false;
4781   }
4782 
4783   // Truncate the lvalue to the appropriate derived class.
4784   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4785 }
4786 
4787 /// Get the value to use for a default-initialized object of type T.
4788 /// Return false if it encounters something invalid.
4789 static bool getDefaultInitValue(QualType T, APValue &Result) {
4790   bool Success = true;
4791   if (auto *RD = T->getAsCXXRecordDecl()) {
4792     if (RD->isInvalidDecl()) {
4793       Result = APValue();
4794       return false;
4795     }
4796     if (RD->isUnion()) {
4797       Result = APValue((const FieldDecl *)nullptr);
4798       return true;
4799     }
4800     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4801                      std::distance(RD->field_begin(), RD->field_end()));
4802 
4803     unsigned Index = 0;
4804     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4805                                                   End = RD->bases_end();
4806          I != End; ++I, ++Index)
4807       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4808 
4809     for (const auto *I : RD->fields()) {
4810       if (I->isUnnamedBitfield())
4811         continue;
4812       Success &= getDefaultInitValue(I->getType(),
4813                                      Result.getStructField(I->getFieldIndex()));
4814     }
4815     return Success;
4816   }
4817 
4818   if (auto *AT =
4819           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4820     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4821     if (Result.hasArrayFiller())
4822       Success &=
4823           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4824 
4825     return Success;
4826   }
4827 
4828   Result = APValue::IndeterminateValue();
4829   return true;
4830 }
4831 
4832 namespace {
4833 enum EvalStmtResult {
4834   /// Evaluation failed.
4835   ESR_Failed,
4836   /// Hit a 'return' statement.
4837   ESR_Returned,
4838   /// Evaluation succeeded.
4839   ESR_Succeeded,
4840   /// Hit a 'continue' statement.
4841   ESR_Continue,
4842   /// Hit a 'break' statement.
4843   ESR_Break,
4844   /// Still scanning for 'case' or 'default' statement.
4845   ESR_CaseNotFound
4846 };
4847 }
4848 
4849 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4850   // We don't need to evaluate the initializer for a static local.
4851   if (!VD->hasLocalStorage())
4852     return true;
4853 
4854   LValue Result;
4855   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4856                                                    ScopeKind::Block, Result);
4857 
4858   const Expr *InitE = VD->getInit();
4859   if (!InitE) {
4860     if (VD->getType()->isDependentType())
4861       return Info.noteSideEffect();
4862     return getDefaultInitValue(VD->getType(), Val);
4863   }
4864   if (InitE->isValueDependent())
4865     return false;
4866 
4867   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4868     // Wipe out any partially-computed value, to allow tracking that this
4869     // evaluation failed.
4870     Val = APValue();
4871     return false;
4872   }
4873 
4874   return true;
4875 }
4876 
4877 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4878   bool OK = true;
4879 
4880   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4881     OK &= EvaluateVarDecl(Info, VD);
4882 
4883   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4884     for (auto *BD : DD->bindings())
4885       if (auto *VD = BD->getHoldingVar())
4886         OK &= EvaluateDecl(Info, VD);
4887 
4888   return OK;
4889 }
4890 
4891 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4892   assert(E->isValueDependent());
4893   if (Info.noteSideEffect())
4894     return true;
4895   assert(E->containsErrors() && "valid value-dependent expression should never "
4896                                 "reach invalid code path.");
4897   return false;
4898 }
4899 
4900 /// Evaluate a condition (either a variable declaration or an expression).
4901 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4902                          const Expr *Cond, bool &Result) {
4903   if (Cond->isValueDependent())
4904     return false;
4905   FullExpressionRAII Scope(Info);
4906   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4907     return false;
4908   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4909     return false;
4910   return Scope.destroy();
4911 }
4912 
4913 namespace {
4914 /// A location where the result (returned value) of evaluating a
4915 /// statement should be stored.
4916 struct StmtResult {
4917   /// The APValue that should be filled in with the returned value.
4918   APValue &Value;
4919   /// The location containing the result, if any (used to support RVO).
4920   const LValue *Slot;
4921 };
4922 
4923 struct TempVersionRAII {
4924   CallStackFrame &Frame;
4925 
4926   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4927     Frame.pushTempVersion();
4928   }
4929 
4930   ~TempVersionRAII() {
4931     Frame.popTempVersion();
4932   }
4933 };
4934 
4935 }
4936 
4937 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4938                                    const Stmt *S,
4939                                    const SwitchCase *SC = nullptr);
4940 
4941 /// Evaluate the body of a loop, and translate the result as appropriate.
4942 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4943                                        const Stmt *Body,
4944                                        const SwitchCase *Case = nullptr) {
4945   BlockScopeRAII Scope(Info);
4946 
4947   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4948   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4949     ESR = ESR_Failed;
4950 
4951   switch (ESR) {
4952   case ESR_Break:
4953     return ESR_Succeeded;
4954   case ESR_Succeeded:
4955   case ESR_Continue:
4956     return ESR_Continue;
4957   case ESR_Failed:
4958   case ESR_Returned:
4959   case ESR_CaseNotFound:
4960     return ESR;
4961   }
4962   llvm_unreachable("Invalid EvalStmtResult!");
4963 }
4964 
4965 /// Evaluate a switch statement.
4966 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4967                                      const SwitchStmt *SS) {
4968   BlockScopeRAII Scope(Info);
4969 
4970   // Evaluate the switch condition.
4971   APSInt Value;
4972   {
4973     if (const Stmt *Init = SS->getInit()) {
4974       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4975       if (ESR != ESR_Succeeded) {
4976         if (ESR != ESR_Failed && !Scope.destroy())
4977           ESR = ESR_Failed;
4978         return ESR;
4979       }
4980     }
4981 
4982     FullExpressionRAII CondScope(Info);
4983     if (SS->getConditionVariable() &&
4984         !EvaluateDecl(Info, SS->getConditionVariable()))
4985       return ESR_Failed;
4986     if (SS->getCond()->isValueDependent()) {
4987       if (!EvaluateDependentExpr(SS->getCond(), Info))
4988         return ESR_Failed;
4989     } else {
4990       if (!EvaluateInteger(SS->getCond(), Value, Info))
4991         return ESR_Failed;
4992     }
4993     if (!CondScope.destroy())
4994       return ESR_Failed;
4995   }
4996 
4997   // Find the switch case corresponding to the value of the condition.
4998   // FIXME: Cache this lookup.
4999   const SwitchCase *Found = nullptr;
5000   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5001        SC = SC->getNextSwitchCase()) {
5002     if (isa<DefaultStmt>(SC)) {
5003       Found = SC;
5004       continue;
5005     }
5006 
5007     const CaseStmt *CS = cast<CaseStmt>(SC);
5008     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5009     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5010                               : LHS;
5011     if (LHS <= Value && Value <= RHS) {
5012       Found = SC;
5013       break;
5014     }
5015   }
5016 
5017   if (!Found)
5018     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5019 
5020   // Search the switch body for the switch case and evaluate it from there.
5021   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5022   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5023     return ESR_Failed;
5024 
5025   switch (ESR) {
5026   case ESR_Break:
5027     return ESR_Succeeded;
5028   case ESR_Succeeded:
5029   case ESR_Continue:
5030   case ESR_Failed:
5031   case ESR_Returned:
5032     return ESR;
5033   case ESR_CaseNotFound:
5034     // This can only happen if the switch case is nested within a statement
5035     // expression. We have no intention of supporting that.
5036     Info.FFDiag(Found->getBeginLoc(),
5037                 diag::note_constexpr_stmt_expr_unsupported);
5038     return ESR_Failed;
5039   }
5040   llvm_unreachable("Invalid EvalStmtResult!");
5041 }
5042 
5043 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5044   // An expression E is a core constant expression unless the evaluation of E
5045   // would evaluate one of the following: [C++2b] - a control flow that passes
5046   // through a declaration of a variable with static or thread storage duration.
5047   if (VD->isLocalVarDecl() && VD->isStaticLocal()) {
5048     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5049         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5050     return false;
5051   }
5052   return true;
5053 }
5054 
5055 // Evaluate a statement.
5056 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5057                                    const Stmt *S, const SwitchCase *Case) {
5058   if (!Info.nextStep(S))
5059     return ESR_Failed;
5060 
5061   // If we're hunting down a 'case' or 'default' label, recurse through
5062   // substatements until we hit the label.
5063   if (Case) {
5064     switch (S->getStmtClass()) {
5065     case Stmt::CompoundStmtClass:
5066       // FIXME: Precompute which substatement of a compound statement we
5067       // would jump to, and go straight there rather than performing a
5068       // linear scan each time.
5069     case Stmt::LabelStmtClass:
5070     case Stmt::AttributedStmtClass:
5071     case Stmt::DoStmtClass:
5072       break;
5073 
5074     case Stmt::CaseStmtClass:
5075     case Stmt::DefaultStmtClass:
5076       if (Case == S)
5077         Case = nullptr;
5078       break;
5079 
5080     case Stmt::IfStmtClass: {
5081       // FIXME: Precompute which side of an 'if' we would jump to, and go
5082       // straight there rather than scanning both sides.
5083       const IfStmt *IS = cast<IfStmt>(S);
5084 
5085       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5086       // preceded by our switch label.
5087       BlockScopeRAII Scope(Info);
5088 
5089       // Step into the init statement in case it brings an (uninitialized)
5090       // variable into scope.
5091       if (const Stmt *Init = IS->getInit()) {
5092         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5093         if (ESR != ESR_CaseNotFound) {
5094           assert(ESR != ESR_Succeeded);
5095           return ESR;
5096         }
5097       }
5098 
5099       // Condition variable must be initialized if it exists.
5100       // FIXME: We can skip evaluating the body if there's a condition
5101       // variable, as there can't be any case labels within it.
5102       // (The same is true for 'for' statements.)
5103 
5104       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5105       if (ESR == ESR_Failed)
5106         return ESR;
5107       if (ESR != ESR_CaseNotFound)
5108         return Scope.destroy() ? ESR : ESR_Failed;
5109       if (!IS->getElse())
5110         return ESR_CaseNotFound;
5111 
5112       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5113       if (ESR == ESR_Failed)
5114         return ESR;
5115       if (ESR != ESR_CaseNotFound)
5116         return Scope.destroy() ? ESR : ESR_Failed;
5117       return ESR_CaseNotFound;
5118     }
5119 
5120     case Stmt::WhileStmtClass: {
5121       EvalStmtResult ESR =
5122           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5123       if (ESR != ESR_Continue)
5124         return ESR;
5125       break;
5126     }
5127 
5128     case Stmt::ForStmtClass: {
5129       const ForStmt *FS = cast<ForStmt>(S);
5130       BlockScopeRAII Scope(Info);
5131 
5132       // Step into the init statement in case it brings an (uninitialized)
5133       // variable into scope.
5134       if (const Stmt *Init = FS->getInit()) {
5135         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5136         if (ESR != ESR_CaseNotFound) {
5137           assert(ESR != ESR_Succeeded);
5138           return ESR;
5139         }
5140       }
5141 
5142       EvalStmtResult ESR =
5143           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5144       if (ESR != ESR_Continue)
5145         return ESR;
5146       if (const auto *Inc = FS->getInc()) {
5147         if (Inc->isValueDependent()) {
5148           if (!EvaluateDependentExpr(Inc, Info))
5149             return ESR_Failed;
5150         } else {
5151           FullExpressionRAII IncScope(Info);
5152           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5153             return ESR_Failed;
5154         }
5155       }
5156       break;
5157     }
5158 
5159     case Stmt::DeclStmtClass: {
5160       // Start the lifetime of any uninitialized variables we encounter. They
5161       // might be used by the selected branch of the switch.
5162       const DeclStmt *DS = cast<DeclStmt>(S);
5163       for (const auto *D : DS->decls()) {
5164         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5165           if (!CheckLocalVariableDeclaration(Info, VD))
5166             return ESR_Failed;
5167           if (VD->hasLocalStorage() && !VD->getInit())
5168             if (!EvaluateVarDecl(Info, VD))
5169               return ESR_Failed;
5170           // FIXME: If the variable has initialization that can't be jumped
5171           // over, bail out of any immediately-surrounding compound-statement
5172           // too. There can't be any case labels here.
5173         }
5174       }
5175       return ESR_CaseNotFound;
5176     }
5177 
5178     default:
5179       return ESR_CaseNotFound;
5180     }
5181   }
5182 
5183   switch (S->getStmtClass()) {
5184   default:
5185     if (const Expr *E = dyn_cast<Expr>(S)) {
5186       if (E->isValueDependent()) {
5187         if (!EvaluateDependentExpr(E, Info))
5188           return ESR_Failed;
5189       } else {
5190         // Don't bother evaluating beyond an expression-statement which couldn't
5191         // be evaluated.
5192         // FIXME: Do we need the FullExpressionRAII object here?
5193         // VisitExprWithCleanups should create one when necessary.
5194         FullExpressionRAII Scope(Info);
5195         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5196           return ESR_Failed;
5197       }
5198       return ESR_Succeeded;
5199     }
5200 
5201     Info.FFDiag(S->getBeginLoc());
5202     return ESR_Failed;
5203 
5204   case Stmt::NullStmtClass:
5205     return ESR_Succeeded;
5206 
5207   case Stmt::DeclStmtClass: {
5208     const DeclStmt *DS = cast<DeclStmt>(S);
5209     for (const auto *D : DS->decls()) {
5210       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5211       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5212         return ESR_Failed;
5213       // Each declaration initialization is its own full-expression.
5214       FullExpressionRAII Scope(Info);
5215       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5216         return ESR_Failed;
5217       if (!Scope.destroy())
5218         return ESR_Failed;
5219     }
5220     return ESR_Succeeded;
5221   }
5222 
5223   case Stmt::ReturnStmtClass: {
5224     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5225     FullExpressionRAII Scope(Info);
5226     if (RetExpr && RetExpr->isValueDependent()) {
5227       EvaluateDependentExpr(RetExpr, Info);
5228       // We know we returned, but we don't know what the value is.
5229       return ESR_Failed;
5230     }
5231     if (RetExpr &&
5232         !(Result.Slot
5233               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5234               : Evaluate(Result.Value, Info, RetExpr)))
5235       return ESR_Failed;
5236     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5237   }
5238 
5239   case Stmt::CompoundStmtClass: {
5240     BlockScopeRAII Scope(Info);
5241 
5242     const CompoundStmt *CS = cast<CompoundStmt>(S);
5243     for (const auto *BI : CS->body()) {
5244       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5245       if (ESR == ESR_Succeeded)
5246         Case = nullptr;
5247       else if (ESR != ESR_CaseNotFound) {
5248         if (ESR != ESR_Failed && !Scope.destroy())
5249           return ESR_Failed;
5250         return ESR;
5251       }
5252     }
5253     if (Case)
5254       return ESR_CaseNotFound;
5255     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5256   }
5257 
5258   case Stmt::IfStmtClass: {
5259     const IfStmt *IS = cast<IfStmt>(S);
5260 
5261     // Evaluate the condition, as either a var decl or as an expression.
5262     BlockScopeRAII Scope(Info);
5263     if (const Stmt *Init = IS->getInit()) {
5264       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5265       if (ESR != ESR_Succeeded) {
5266         if (ESR != ESR_Failed && !Scope.destroy())
5267           return ESR_Failed;
5268         return ESR;
5269       }
5270     }
5271     bool Cond;
5272     if (IS->isConsteval())
5273       Cond = IS->isNonNegatedConsteval();
5274     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5275                            Cond))
5276       return ESR_Failed;
5277 
5278     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5279       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5280       if (ESR != ESR_Succeeded) {
5281         if (ESR != ESR_Failed && !Scope.destroy())
5282           return ESR_Failed;
5283         return ESR;
5284       }
5285     }
5286     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5287   }
5288 
5289   case Stmt::WhileStmtClass: {
5290     const WhileStmt *WS = cast<WhileStmt>(S);
5291     while (true) {
5292       BlockScopeRAII Scope(Info);
5293       bool Continue;
5294       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5295                         Continue))
5296         return ESR_Failed;
5297       if (!Continue)
5298         break;
5299 
5300       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5301       if (ESR != ESR_Continue) {
5302         if (ESR != ESR_Failed && !Scope.destroy())
5303           return ESR_Failed;
5304         return ESR;
5305       }
5306       if (!Scope.destroy())
5307         return ESR_Failed;
5308     }
5309     return ESR_Succeeded;
5310   }
5311 
5312   case Stmt::DoStmtClass: {
5313     const DoStmt *DS = cast<DoStmt>(S);
5314     bool Continue;
5315     do {
5316       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5317       if (ESR != ESR_Continue)
5318         return ESR;
5319       Case = nullptr;
5320 
5321       if (DS->getCond()->isValueDependent()) {
5322         EvaluateDependentExpr(DS->getCond(), Info);
5323         // Bailout as we don't know whether to keep going or terminate the loop.
5324         return ESR_Failed;
5325       }
5326       FullExpressionRAII CondScope(Info);
5327       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5328           !CondScope.destroy())
5329         return ESR_Failed;
5330     } while (Continue);
5331     return ESR_Succeeded;
5332   }
5333 
5334   case Stmt::ForStmtClass: {
5335     const ForStmt *FS = cast<ForStmt>(S);
5336     BlockScopeRAII ForScope(Info);
5337     if (FS->getInit()) {
5338       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5339       if (ESR != ESR_Succeeded) {
5340         if (ESR != ESR_Failed && !ForScope.destroy())
5341           return ESR_Failed;
5342         return ESR;
5343       }
5344     }
5345     while (true) {
5346       BlockScopeRAII IterScope(Info);
5347       bool Continue = true;
5348       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5349                                          FS->getCond(), Continue))
5350         return ESR_Failed;
5351       if (!Continue)
5352         break;
5353 
5354       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5355       if (ESR != ESR_Continue) {
5356         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5357           return ESR_Failed;
5358         return ESR;
5359       }
5360 
5361       if (const auto *Inc = FS->getInc()) {
5362         if (Inc->isValueDependent()) {
5363           if (!EvaluateDependentExpr(Inc, Info))
5364             return ESR_Failed;
5365         } else {
5366           FullExpressionRAII IncScope(Info);
5367           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5368             return ESR_Failed;
5369         }
5370       }
5371 
5372       if (!IterScope.destroy())
5373         return ESR_Failed;
5374     }
5375     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5376   }
5377 
5378   case Stmt::CXXForRangeStmtClass: {
5379     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5380     BlockScopeRAII Scope(Info);
5381 
5382     // Evaluate the init-statement if present.
5383     if (FS->getInit()) {
5384       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5385       if (ESR != ESR_Succeeded) {
5386         if (ESR != ESR_Failed && !Scope.destroy())
5387           return ESR_Failed;
5388         return ESR;
5389       }
5390     }
5391 
5392     // Initialize the __range variable.
5393     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5394     if (ESR != ESR_Succeeded) {
5395       if (ESR != ESR_Failed && !Scope.destroy())
5396         return ESR_Failed;
5397       return ESR;
5398     }
5399 
5400     // In error-recovery cases it's possible to get here even if we failed to
5401     // synthesize the __begin and __end variables.
5402     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5403       return ESR_Failed;
5404 
5405     // Create the __begin and __end iterators.
5406     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5407     if (ESR != ESR_Succeeded) {
5408       if (ESR != ESR_Failed && !Scope.destroy())
5409         return ESR_Failed;
5410       return ESR;
5411     }
5412     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5413     if (ESR != ESR_Succeeded) {
5414       if (ESR != ESR_Failed && !Scope.destroy())
5415         return ESR_Failed;
5416       return ESR;
5417     }
5418 
5419     while (true) {
5420       // Condition: __begin != __end.
5421       {
5422         if (FS->getCond()->isValueDependent()) {
5423           EvaluateDependentExpr(FS->getCond(), Info);
5424           // We don't know whether to keep going or terminate the loop.
5425           return ESR_Failed;
5426         }
5427         bool Continue = true;
5428         FullExpressionRAII CondExpr(Info);
5429         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5430           return ESR_Failed;
5431         if (!Continue)
5432           break;
5433       }
5434 
5435       // User's variable declaration, initialized by *__begin.
5436       BlockScopeRAII InnerScope(Info);
5437       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5438       if (ESR != ESR_Succeeded) {
5439         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5440           return ESR_Failed;
5441         return ESR;
5442       }
5443 
5444       // Loop body.
5445       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5446       if (ESR != ESR_Continue) {
5447         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5448           return ESR_Failed;
5449         return ESR;
5450       }
5451       if (FS->getInc()->isValueDependent()) {
5452         if (!EvaluateDependentExpr(FS->getInc(), Info))
5453           return ESR_Failed;
5454       } else {
5455         // Increment: ++__begin
5456         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5457           return ESR_Failed;
5458       }
5459 
5460       if (!InnerScope.destroy())
5461         return ESR_Failed;
5462     }
5463 
5464     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5465   }
5466 
5467   case Stmt::SwitchStmtClass:
5468     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5469 
5470   case Stmt::ContinueStmtClass:
5471     return ESR_Continue;
5472 
5473   case Stmt::BreakStmtClass:
5474     return ESR_Break;
5475 
5476   case Stmt::LabelStmtClass:
5477     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5478 
5479   case Stmt::AttributedStmtClass:
5480     // As a general principle, C++11 attributes can be ignored without
5481     // any semantic impact.
5482     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5483                         Case);
5484 
5485   case Stmt::CaseStmtClass:
5486   case Stmt::DefaultStmtClass:
5487     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5488   case Stmt::CXXTryStmtClass:
5489     // Evaluate try blocks by evaluating all sub statements.
5490     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5491   }
5492 }
5493 
5494 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5495 /// default constructor. If so, we'll fold it whether or not it's marked as
5496 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5497 /// so we need special handling.
5498 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5499                                            const CXXConstructorDecl *CD,
5500                                            bool IsValueInitialization) {
5501   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5502     return false;
5503 
5504   // Value-initialization does not call a trivial default constructor, so such a
5505   // call is a core constant expression whether or not the constructor is
5506   // constexpr.
5507   if (!CD->isConstexpr() && !IsValueInitialization) {
5508     if (Info.getLangOpts().CPlusPlus11) {
5509       // FIXME: If DiagDecl is an implicitly-declared special member function,
5510       // we should be much more explicit about why it's not constexpr.
5511       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5512         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5513       Info.Note(CD->getLocation(), diag::note_declared_at);
5514     } else {
5515       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5516     }
5517   }
5518   return true;
5519 }
5520 
5521 /// CheckConstexprFunction - Check that a function can be called in a constant
5522 /// expression.
5523 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5524                                    const FunctionDecl *Declaration,
5525                                    const FunctionDecl *Definition,
5526                                    const Stmt *Body) {
5527   // Potential constant expressions can contain calls to declared, but not yet
5528   // defined, constexpr functions.
5529   if (Info.checkingPotentialConstantExpression() && !Definition &&
5530       Declaration->isConstexpr())
5531     return false;
5532 
5533   // Bail out if the function declaration itself is invalid.  We will
5534   // have produced a relevant diagnostic while parsing it, so just
5535   // note the problematic sub-expression.
5536   if (Declaration->isInvalidDecl()) {
5537     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5538     return false;
5539   }
5540 
5541   // DR1872: An instantiated virtual constexpr function can't be called in a
5542   // constant expression (prior to C++20). We can still constant-fold such a
5543   // call.
5544   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5545       cast<CXXMethodDecl>(Declaration)->isVirtual())
5546     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5547 
5548   if (Definition && Definition->isInvalidDecl()) {
5549     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5550     return false;
5551   }
5552 
5553   // Can we evaluate this function call?
5554   if (Definition && Definition->isConstexpr() && Body)
5555     return true;
5556 
5557   if (Info.getLangOpts().CPlusPlus11) {
5558     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5559 
5560     // If this function is not constexpr because it is an inherited
5561     // non-constexpr constructor, diagnose that directly.
5562     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5563     if (CD && CD->isInheritingConstructor()) {
5564       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5565       if (!Inherited->isConstexpr())
5566         DiagDecl = CD = Inherited;
5567     }
5568 
5569     // FIXME: If DiagDecl is an implicitly-declared special member function
5570     // or an inheriting constructor, we should be much more explicit about why
5571     // it's not constexpr.
5572     if (CD && CD->isInheritingConstructor())
5573       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5574         << CD->getInheritedConstructor().getConstructor()->getParent();
5575     else
5576       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5577         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5578     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5579   } else {
5580     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5581   }
5582   return false;
5583 }
5584 
5585 namespace {
5586 struct CheckDynamicTypeHandler {
5587   AccessKinds AccessKind;
5588   typedef bool result_type;
5589   bool failed() { return false; }
5590   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5591   bool found(APSInt &Value, QualType SubobjType) { return true; }
5592   bool found(APFloat &Value, QualType SubobjType) { return true; }
5593 };
5594 } // end anonymous namespace
5595 
5596 /// Check that we can access the notional vptr of an object / determine its
5597 /// dynamic type.
5598 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5599                              AccessKinds AK, bool Polymorphic) {
5600   if (This.Designator.Invalid)
5601     return false;
5602 
5603   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5604 
5605   if (!Obj)
5606     return false;
5607 
5608   if (!Obj.Value) {
5609     // The object is not usable in constant expressions, so we can't inspect
5610     // its value to see if it's in-lifetime or what the active union members
5611     // are. We can still check for a one-past-the-end lvalue.
5612     if (This.Designator.isOnePastTheEnd() ||
5613         This.Designator.isMostDerivedAnUnsizedArray()) {
5614       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5615                          ? diag::note_constexpr_access_past_end
5616                          : diag::note_constexpr_access_unsized_array)
5617           << AK;
5618       return false;
5619     } else if (Polymorphic) {
5620       // Conservatively refuse to perform a polymorphic operation if we would
5621       // not be able to read a notional 'vptr' value.
5622       APValue Val;
5623       This.moveInto(Val);
5624       QualType StarThisType =
5625           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5626       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5627           << AK << Val.getAsString(Info.Ctx, StarThisType);
5628       return false;
5629     }
5630     return true;
5631   }
5632 
5633   CheckDynamicTypeHandler Handler{AK};
5634   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5635 }
5636 
5637 /// Check that the pointee of the 'this' pointer in a member function call is
5638 /// either within its lifetime or in its period of construction or destruction.
5639 static bool
5640 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5641                                      const LValue &This,
5642                                      const CXXMethodDecl *NamedMember) {
5643   return checkDynamicType(
5644       Info, E, This,
5645       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5646 }
5647 
5648 struct DynamicType {
5649   /// The dynamic class type of the object.
5650   const CXXRecordDecl *Type;
5651   /// The corresponding path length in the lvalue.
5652   unsigned PathLength;
5653 };
5654 
5655 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5656                                              unsigned PathLength) {
5657   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5658       Designator.Entries.size() && "invalid path length");
5659   return (PathLength == Designator.MostDerivedPathLength)
5660              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5661              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5662 }
5663 
5664 /// Determine the dynamic type of an object.
5665 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5666                                                 LValue &This, AccessKinds AK) {
5667   // If we don't have an lvalue denoting an object of class type, there is no
5668   // meaningful dynamic type. (We consider objects of non-class type to have no
5669   // dynamic type.)
5670   if (!checkDynamicType(Info, E, This, AK, true))
5671     return None;
5672 
5673   // Refuse to compute a dynamic type in the presence of virtual bases. This
5674   // shouldn't happen other than in constant-folding situations, since literal
5675   // types can't have virtual bases.
5676   //
5677   // Note that consumers of DynamicType assume that the type has no virtual
5678   // bases, and will need modifications if this restriction is relaxed.
5679   const CXXRecordDecl *Class =
5680       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5681   if (!Class || Class->getNumVBases()) {
5682     Info.FFDiag(E);
5683     return None;
5684   }
5685 
5686   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5687   // binary search here instead. But the overwhelmingly common case is that
5688   // we're not in the middle of a constructor, so it probably doesn't matter
5689   // in practice.
5690   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5691   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5692        PathLength <= Path.size(); ++PathLength) {
5693     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5694                                       Path.slice(0, PathLength))) {
5695     case ConstructionPhase::Bases:
5696     case ConstructionPhase::DestroyingBases:
5697       // We're constructing or destroying a base class. This is not the dynamic
5698       // type.
5699       break;
5700 
5701     case ConstructionPhase::None:
5702     case ConstructionPhase::AfterBases:
5703     case ConstructionPhase::AfterFields:
5704     case ConstructionPhase::Destroying:
5705       // We've finished constructing the base classes and not yet started
5706       // destroying them again, so this is the dynamic type.
5707       return DynamicType{getBaseClassType(This.Designator, PathLength),
5708                          PathLength};
5709     }
5710   }
5711 
5712   // CWG issue 1517: we're constructing a base class of the object described by
5713   // 'This', so that object has not yet begun its period of construction and
5714   // any polymorphic operation on it results in undefined behavior.
5715   Info.FFDiag(E);
5716   return None;
5717 }
5718 
5719 /// Perform virtual dispatch.
5720 static const CXXMethodDecl *HandleVirtualDispatch(
5721     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5722     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5723   Optional<DynamicType> DynType = ComputeDynamicType(
5724       Info, E, This,
5725       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5726   if (!DynType)
5727     return nullptr;
5728 
5729   // Find the final overrider. It must be declared in one of the classes on the
5730   // path from the dynamic type to the static type.
5731   // FIXME: If we ever allow literal types to have virtual base classes, that
5732   // won't be true.
5733   const CXXMethodDecl *Callee = Found;
5734   unsigned PathLength = DynType->PathLength;
5735   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5736     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5737     const CXXMethodDecl *Overrider =
5738         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5739     if (Overrider) {
5740       Callee = Overrider;
5741       break;
5742     }
5743   }
5744 
5745   // C++2a [class.abstract]p6:
5746   //   the effect of making a virtual call to a pure virtual function [...] is
5747   //   undefined
5748   if (Callee->isPure()) {
5749     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5750     Info.Note(Callee->getLocation(), diag::note_declared_at);
5751     return nullptr;
5752   }
5753 
5754   // If necessary, walk the rest of the path to determine the sequence of
5755   // covariant adjustment steps to apply.
5756   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5757                                        Found->getReturnType())) {
5758     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5759     for (unsigned CovariantPathLength = PathLength + 1;
5760          CovariantPathLength != This.Designator.Entries.size();
5761          ++CovariantPathLength) {
5762       const CXXRecordDecl *NextClass =
5763           getBaseClassType(This.Designator, CovariantPathLength);
5764       const CXXMethodDecl *Next =
5765           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5766       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5767                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5768         CovariantAdjustmentPath.push_back(Next->getReturnType());
5769     }
5770     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5771                                          CovariantAdjustmentPath.back()))
5772       CovariantAdjustmentPath.push_back(Found->getReturnType());
5773   }
5774 
5775   // Perform 'this' adjustment.
5776   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5777     return nullptr;
5778 
5779   return Callee;
5780 }
5781 
5782 /// Perform the adjustment from a value returned by a virtual function to
5783 /// a value of the statically expected type, which may be a pointer or
5784 /// reference to a base class of the returned type.
5785 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5786                                             APValue &Result,
5787                                             ArrayRef<QualType> Path) {
5788   assert(Result.isLValue() &&
5789          "unexpected kind of APValue for covariant return");
5790   if (Result.isNullPointer())
5791     return true;
5792 
5793   LValue LVal;
5794   LVal.setFrom(Info.Ctx, Result);
5795 
5796   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5797   for (unsigned I = 1; I != Path.size(); ++I) {
5798     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5799     assert(OldClass && NewClass && "unexpected kind of covariant return");
5800     if (OldClass != NewClass &&
5801         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5802       return false;
5803     OldClass = NewClass;
5804   }
5805 
5806   LVal.moveInto(Result);
5807   return true;
5808 }
5809 
5810 /// Determine whether \p Base, which is known to be a direct base class of
5811 /// \p Derived, is a public base class.
5812 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5813                               const CXXRecordDecl *Base) {
5814   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5815     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5816     if (BaseClass && declaresSameEntity(BaseClass, Base))
5817       return BaseSpec.getAccessSpecifier() == AS_public;
5818   }
5819   llvm_unreachable("Base is not a direct base of Derived");
5820 }
5821 
5822 /// Apply the given dynamic cast operation on the provided lvalue.
5823 ///
5824 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5825 /// to find a suitable target subobject.
5826 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5827                               LValue &Ptr) {
5828   // We can't do anything with a non-symbolic pointer value.
5829   SubobjectDesignator &D = Ptr.Designator;
5830   if (D.Invalid)
5831     return false;
5832 
5833   // C++ [expr.dynamic.cast]p6:
5834   //   If v is a null pointer value, the result is a null pointer value.
5835   if (Ptr.isNullPointer() && !E->isGLValue())
5836     return true;
5837 
5838   // For all the other cases, we need the pointer to point to an object within
5839   // its lifetime / period of construction / destruction, and we need to know
5840   // its dynamic type.
5841   Optional<DynamicType> DynType =
5842       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5843   if (!DynType)
5844     return false;
5845 
5846   // C++ [expr.dynamic.cast]p7:
5847   //   If T is "pointer to cv void", then the result is a pointer to the most
5848   //   derived object
5849   if (E->getType()->isVoidPointerType())
5850     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5851 
5852   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5853   assert(C && "dynamic_cast target is not void pointer nor class");
5854   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5855 
5856   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5857     // C++ [expr.dynamic.cast]p9:
5858     if (!E->isGLValue()) {
5859       //   The value of a failed cast to pointer type is the null pointer value
5860       //   of the required result type.
5861       Ptr.setNull(Info.Ctx, E->getType());
5862       return true;
5863     }
5864 
5865     //   A failed cast to reference type throws [...] std::bad_cast.
5866     unsigned DiagKind;
5867     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5868                    DynType->Type->isDerivedFrom(C)))
5869       DiagKind = 0;
5870     else if (!Paths || Paths->begin() == Paths->end())
5871       DiagKind = 1;
5872     else if (Paths->isAmbiguous(CQT))
5873       DiagKind = 2;
5874     else {
5875       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5876       DiagKind = 3;
5877     }
5878     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5879         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5880         << Info.Ctx.getRecordType(DynType->Type)
5881         << E->getType().getUnqualifiedType();
5882     return false;
5883   };
5884 
5885   // Runtime check, phase 1:
5886   //   Walk from the base subobject towards the derived object looking for the
5887   //   target type.
5888   for (int PathLength = Ptr.Designator.Entries.size();
5889        PathLength >= (int)DynType->PathLength; --PathLength) {
5890     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5891     if (declaresSameEntity(Class, C))
5892       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5893     // We can only walk across public inheritance edges.
5894     if (PathLength > (int)DynType->PathLength &&
5895         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5896                            Class))
5897       return RuntimeCheckFailed(nullptr);
5898   }
5899 
5900   // Runtime check, phase 2:
5901   //   Search the dynamic type for an unambiguous public base of type C.
5902   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5903                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5904   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5905       Paths.front().Access == AS_public) {
5906     // Downcast to the dynamic type...
5907     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5908       return false;
5909     // ... then upcast to the chosen base class subobject.
5910     for (CXXBasePathElement &Elem : Paths.front())
5911       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5912         return false;
5913     return true;
5914   }
5915 
5916   // Otherwise, the runtime check fails.
5917   return RuntimeCheckFailed(&Paths);
5918 }
5919 
5920 namespace {
5921 struct StartLifetimeOfUnionMemberHandler {
5922   EvalInfo &Info;
5923   const Expr *LHSExpr;
5924   const FieldDecl *Field;
5925   bool DuringInit;
5926   bool Failed = false;
5927   static const AccessKinds AccessKind = AK_Assign;
5928 
5929   typedef bool result_type;
5930   bool failed() { return Failed; }
5931   bool found(APValue &Subobj, QualType SubobjType) {
5932     // We are supposed to perform no initialization but begin the lifetime of
5933     // the object. We interpret that as meaning to do what default
5934     // initialization of the object would do if all constructors involved were
5935     // trivial:
5936     //  * All base, non-variant member, and array element subobjects' lifetimes
5937     //    begin
5938     //  * No variant members' lifetimes begin
5939     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5940     assert(SubobjType->isUnionType());
5941     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5942       // This union member is already active. If it's also in-lifetime, there's
5943       // nothing to do.
5944       if (Subobj.getUnionValue().hasValue())
5945         return true;
5946     } else if (DuringInit) {
5947       // We're currently in the process of initializing a different union
5948       // member.  If we carried on, that initialization would attempt to
5949       // store to an inactive union member, resulting in undefined behavior.
5950       Info.FFDiag(LHSExpr,
5951                   diag::note_constexpr_union_member_change_during_init);
5952       return false;
5953     }
5954     APValue Result;
5955     Failed = !getDefaultInitValue(Field->getType(), Result);
5956     Subobj.setUnion(Field, Result);
5957     return true;
5958   }
5959   bool found(APSInt &Value, QualType SubobjType) {
5960     llvm_unreachable("wrong value kind for union object");
5961   }
5962   bool found(APFloat &Value, QualType SubobjType) {
5963     llvm_unreachable("wrong value kind for union object");
5964   }
5965 };
5966 } // end anonymous namespace
5967 
5968 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5969 
5970 /// Handle a builtin simple-assignment or a call to a trivial assignment
5971 /// operator whose left-hand side might involve a union member access. If it
5972 /// does, implicitly start the lifetime of any accessed union elements per
5973 /// C++20 [class.union]5.
5974 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5975                                           const LValue &LHS) {
5976   if (LHS.InvalidBase || LHS.Designator.Invalid)
5977     return false;
5978 
5979   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5980   // C++ [class.union]p5:
5981   //   define the set S(E) of subexpressions of E as follows:
5982   unsigned PathLength = LHS.Designator.Entries.size();
5983   for (const Expr *E = LHSExpr; E != nullptr;) {
5984     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5985     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5986       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5987       // Note that we can't implicitly start the lifetime of a reference,
5988       // so we don't need to proceed any further if we reach one.
5989       if (!FD || FD->getType()->isReferenceType())
5990         break;
5991 
5992       //    ... and also contains A.B if B names a union member ...
5993       if (FD->getParent()->isUnion()) {
5994         //    ... of a non-class, non-array type, or of a class type with a
5995         //    trivial default constructor that is not deleted, or an array of
5996         //    such types.
5997         auto *RD =
5998             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5999         if (!RD || RD->hasTrivialDefaultConstructor())
6000           UnionPathLengths.push_back({PathLength - 1, FD});
6001       }
6002 
6003       E = ME->getBase();
6004       --PathLength;
6005       assert(declaresSameEntity(FD,
6006                                 LHS.Designator.Entries[PathLength]
6007                                     .getAsBaseOrMember().getPointer()));
6008 
6009       //   -- If E is of the form A[B] and is interpreted as a built-in array
6010       //      subscripting operator, S(E) is [S(the array operand, if any)].
6011     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6012       // Step over an ArrayToPointerDecay implicit cast.
6013       auto *Base = ASE->getBase()->IgnoreImplicit();
6014       if (!Base->getType()->isArrayType())
6015         break;
6016 
6017       E = Base;
6018       --PathLength;
6019 
6020     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6021       // Step over a derived-to-base conversion.
6022       E = ICE->getSubExpr();
6023       if (ICE->getCastKind() == CK_NoOp)
6024         continue;
6025       if (ICE->getCastKind() != CK_DerivedToBase &&
6026           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6027         break;
6028       // Walk path backwards as we walk up from the base to the derived class.
6029       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6030         --PathLength;
6031         (void)Elt;
6032         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6033                                   LHS.Designator.Entries[PathLength]
6034                                       .getAsBaseOrMember().getPointer()));
6035       }
6036 
6037     //   -- Otherwise, S(E) is empty.
6038     } else {
6039       break;
6040     }
6041   }
6042 
6043   // Common case: no unions' lifetimes are started.
6044   if (UnionPathLengths.empty())
6045     return true;
6046 
6047   //   if modification of X [would access an inactive union member], an object
6048   //   of the type of X is implicitly created
6049   CompleteObject Obj =
6050       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6051   if (!Obj)
6052     return false;
6053   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6054            llvm::reverse(UnionPathLengths)) {
6055     // Form a designator for the union object.
6056     SubobjectDesignator D = LHS.Designator;
6057     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6058 
6059     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6060                       ConstructionPhase::AfterBases;
6061     StartLifetimeOfUnionMemberHandler StartLifetime{
6062         Info, LHSExpr, LengthAndField.second, DuringInit};
6063     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6064       return false;
6065   }
6066 
6067   return true;
6068 }
6069 
6070 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6071                             CallRef Call, EvalInfo &Info,
6072                             bool NonNull = false) {
6073   LValue LV;
6074   // Create the parameter slot and register its destruction. For a vararg
6075   // argument, create a temporary.
6076   // FIXME: For calling conventions that destroy parameters in the callee,
6077   // should we consider performing destruction when the function returns
6078   // instead?
6079   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6080                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6081                                                        ScopeKind::Call, LV);
6082   if (!EvaluateInPlace(V, Info, LV, Arg))
6083     return false;
6084 
6085   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6086   // undefined behavior, so is non-constant.
6087   if (NonNull && V.isLValue() && V.isNullPointer()) {
6088     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6089     return false;
6090   }
6091 
6092   return true;
6093 }
6094 
6095 /// Evaluate the arguments to a function call.
6096 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6097                          EvalInfo &Info, const FunctionDecl *Callee,
6098                          bool RightToLeft = false) {
6099   bool Success = true;
6100   llvm::SmallBitVector ForbiddenNullArgs;
6101   if (Callee->hasAttr<NonNullAttr>()) {
6102     ForbiddenNullArgs.resize(Args.size());
6103     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6104       if (!Attr->args_size()) {
6105         ForbiddenNullArgs.set();
6106         break;
6107       } else
6108         for (auto Idx : Attr->args()) {
6109           unsigned ASTIdx = Idx.getASTIndex();
6110           if (ASTIdx >= Args.size())
6111             continue;
6112           ForbiddenNullArgs[ASTIdx] = true;
6113         }
6114     }
6115   }
6116   for (unsigned I = 0; I < Args.size(); I++) {
6117     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6118     const ParmVarDecl *PVD =
6119         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6120     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6121     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6122       // If we're checking for a potential constant expression, evaluate all
6123       // initializers even if some of them fail.
6124       if (!Info.noteFailure())
6125         return false;
6126       Success = false;
6127     }
6128   }
6129   return Success;
6130 }
6131 
6132 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6133 /// constructor or assignment operator.
6134 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6135                               const Expr *E, APValue &Result,
6136                               bool CopyObjectRepresentation) {
6137   // Find the reference argument.
6138   CallStackFrame *Frame = Info.CurrentCall;
6139   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6140   if (!RefValue) {
6141     Info.FFDiag(E);
6142     return false;
6143   }
6144 
6145   // Copy out the contents of the RHS object.
6146   LValue RefLValue;
6147   RefLValue.setFrom(Info.Ctx, *RefValue);
6148   return handleLValueToRValueConversion(
6149       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6150       CopyObjectRepresentation);
6151 }
6152 
6153 /// Evaluate a function call.
6154 static bool HandleFunctionCall(SourceLocation CallLoc,
6155                                const FunctionDecl *Callee, const LValue *This,
6156                                ArrayRef<const Expr *> Args, CallRef Call,
6157                                const Stmt *Body, EvalInfo &Info,
6158                                APValue &Result, const LValue *ResultSlot) {
6159   if (!Info.CheckCallLimit(CallLoc))
6160     return false;
6161 
6162   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6163 
6164   // For a trivial copy or move assignment, perform an APValue copy. This is
6165   // essential for unions, where the operations performed by the assignment
6166   // operator cannot be represented as statements.
6167   //
6168   // Skip this for non-union classes with no fields; in that case, the defaulted
6169   // copy/move does not actually read the object.
6170   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6171   if (MD && MD->isDefaulted() &&
6172       (MD->getParent()->isUnion() ||
6173        (MD->isTrivial() &&
6174         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6175     assert(This &&
6176            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6177     APValue RHSValue;
6178     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6179                            MD->getParent()->isUnion()))
6180       return false;
6181     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6182                           RHSValue))
6183       return false;
6184     This->moveInto(Result);
6185     return true;
6186   } else if (MD && isLambdaCallOperator(MD)) {
6187     // We're in a lambda; determine the lambda capture field maps unless we're
6188     // just constexpr checking a lambda's call operator. constexpr checking is
6189     // done before the captures have been added to the closure object (unless
6190     // we're inferring constexpr-ness), so we don't have access to them in this
6191     // case. But since we don't need the captures to constexpr check, we can
6192     // just ignore them.
6193     if (!Info.checkingPotentialConstantExpression())
6194       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6195                                         Frame.LambdaThisCaptureField);
6196   }
6197 
6198   StmtResult Ret = {Result, ResultSlot};
6199   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6200   if (ESR == ESR_Succeeded) {
6201     if (Callee->getReturnType()->isVoidType())
6202       return true;
6203     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6204   }
6205   return ESR == ESR_Returned;
6206 }
6207 
6208 /// Evaluate a constructor call.
6209 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6210                                   CallRef Call,
6211                                   const CXXConstructorDecl *Definition,
6212                                   EvalInfo &Info, APValue &Result) {
6213   SourceLocation CallLoc = E->getExprLoc();
6214   if (!Info.CheckCallLimit(CallLoc))
6215     return false;
6216 
6217   const CXXRecordDecl *RD = Definition->getParent();
6218   if (RD->getNumVBases()) {
6219     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6220     return false;
6221   }
6222 
6223   EvalInfo::EvaluatingConstructorRAII EvalObj(
6224       Info,
6225       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6226       RD->getNumBases());
6227   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6228 
6229   // FIXME: Creating an APValue just to hold a nonexistent return value is
6230   // wasteful.
6231   APValue RetVal;
6232   StmtResult Ret = {RetVal, nullptr};
6233 
6234   // If it's a delegating constructor, delegate.
6235   if (Definition->isDelegatingConstructor()) {
6236     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6237     if ((*I)->getInit()->isValueDependent()) {
6238       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6239         return false;
6240     } else {
6241       FullExpressionRAII InitScope(Info);
6242       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6243           !InitScope.destroy())
6244         return false;
6245     }
6246     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6247   }
6248 
6249   // For a trivial copy or move constructor, perform an APValue copy. This is
6250   // essential for unions (or classes with anonymous union members), where the
6251   // operations performed by the constructor cannot be represented by
6252   // ctor-initializers.
6253   //
6254   // Skip this for empty non-union classes; we should not perform an
6255   // lvalue-to-rvalue conversion on them because their copy constructor does not
6256   // actually read them.
6257   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6258       (Definition->getParent()->isUnion() ||
6259        (Definition->isTrivial() &&
6260         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6261     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6262                              Definition->getParent()->isUnion());
6263   }
6264 
6265   // Reserve space for the struct members.
6266   if (!Result.hasValue()) {
6267     if (!RD->isUnion())
6268       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6269                        std::distance(RD->field_begin(), RD->field_end()));
6270     else
6271       // A union starts with no active member.
6272       Result = APValue((const FieldDecl*)nullptr);
6273   }
6274 
6275   if (RD->isInvalidDecl()) return false;
6276   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6277 
6278   // A scope for temporaries lifetime-extended by reference members.
6279   BlockScopeRAII LifetimeExtendedScope(Info);
6280 
6281   bool Success = true;
6282   unsigned BasesSeen = 0;
6283 #ifndef NDEBUG
6284   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6285 #endif
6286   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6287   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6288     // We might be initializing the same field again if this is an indirect
6289     // field initialization.
6290     if (FieldIt == RD->field_end() ||
6291         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6292       assert(Indirect && "fields out of order?");
6293       return;
6294     }
6295 
6296     // Default-initialize any fields with no explicit initializer.
6297     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6298       assert(FieldIt != RD->field_end() && "missing field?");
6299       if (!FieldIt->isUnnamedBitfield())
6300         Success &= getDefaultInitValue(
6301             FieldIt->getType(),
6302             Result.getStructField(FieldIt->getFieldIndex()));
6303     }
6304     ++FieldIt;
6305   };
6306   for (const auto *I : Definition->inits()) {
6307     LValue Subobject = This;
6308     LValue SubobjectParent = This;
6309     APValue *Value = &Result;
6310 
6311     // Determine the subobject to initialize.
6312     FieldDecl *FD = nullptr;
6313     if (I->isBaseInitializer()) {
6314       QualType BaseType(I->getBaseClass(), 0);
6315 #ifndef NDEBUG
6316       // Non-virtual base classes are initialized in the order in the class
6317       // definition. We have already checked for virtual base classes.
6318       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6319       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6320              "base class initializers not in expected order");
6321       ++BaseIt;
6322 #endif
6323       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6324                                   BaseType->getAsCXXRecordDecl(), &Layout))
6325         return false;
6326       Value = &Result.getStructBase(BasesSeen++);
6327     } else if ((FD = I->getMember())) {
6328       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6329         return false;
6330       if (RD->isUnion()) {
6331         Result = APValue(FD);
6332         Value = &Result.getUnionValue();
6333       } else {
6334         SkipToField(FD, false);
6335         Value = &Result.getStructField(FD->getFieldIndex());
6336       }
6337     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6338       // Walk the indirect field decl's chain to find the object to initialize,
6339       // and make sure we've initialized every step along it.
6340       auto IndirectFieldChain = IFD->chain();
6341       for (auto *C : IndirectFieldChain) {
6342         FD = cast<FieldDecl>(C);
6343         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6344         // Switch the union field if it differs. This happens if we had
6345         // preceding zero-initialization, and we're now initializing a union
6346         // subobject other than the first.
6347         // FIXME: In this case, the values of the other subobjects are
6348         // specified, since zero-initialization sets all padding bits to zero.
6349         if (!Value->hasValue() ||
6350             (Value->isUnion() && Value->getUnionField() != FD)) {
6351           if (CD->isUnion())
6352             *Value = APValue(FD);
6353           else
6354             // FIXME: This immediately starts the lifetime of all members of
6355             // an anonymous struct. It would be preferable to strictly start
6356             // member lifetime in initialization order.
6357             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6358         }
6359         // Store Subobject as its parent before updating it for the last element
6360         // in the chain.
6361         if (C == IndirectFieldChain.back())
6362           SubobjectParent = Subobject;
6363         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6364           return false;
6365         if (CD->isUnion())
6366           Value = &Value->getUnionValue();
6367         else {
6368           if (C == IndirectFieldChain.front() && !RD->isUnion())
6369             SkipToField(FD, true);
6370           Value = &Value->getStructField(FD->getFieldIndex());
6371         }
6372       }
6373     } else {
6374       llvm_unreachable("unknown base initializer kind");
6375     }
6376 
6377     // Need to override This for implicit field initializers as in this case
6378     // This refers to innermost anonymous struct/union containing initializer,
6379     // not to currently constructed class.
6380     const Expr *Init = I->getInit();
6381     if (Init->isValueDependent()) {
6382       if (!EvaluateDependentExpr(Init, Info))
6383         return false;
6384     } else {
6385       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6386                                     isa<CXXDefaultInitExpr>(Init));
6387       FullExpressionRAII InitScope(Info);
6388       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6389           (FD && FD->isBitField() &&
6390            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6391         // If we're checking for a potential constant expression, evaluate all
6392         // initializers even if some of them fail.
6393         if (!Info.noteFailure())
6394           return false;
6395         Success = false;
6396       }
6397     }
6398 
6399     // This is the point at which the dynamic type of the object becomes this
6400     // class type.
6401     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6402       EvalObj.finishedConstructingBases();
6403   }
6404 
6405   // Default-initialize any remaining fields.
6406   if (!RD->isUnion()) {
6407     for (; FieldIt != RD->field_end(); ++FieldIt) {
6408       if (!FieldIt->isUnnamedBitfield())
6409         Success &= getDefaultInitValue(
6410             FieldIt->getType(),
6411             Result.getStructField(FieldIt->getFieldIndex()));
6412     }
6413   }
6414 
6415   EvalObj.finishedConstructingFields();
6416 
6417   return Success &&
6418          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6419          LifetimeExtendedScope.destroy();
6420 }
6421 
6422 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6423                                   ArrayRef<const Expr*> Args,
6424                                   const CXXConstructorDecl *Definition,
6425                                   EvalInfo &Info, APValue &Result) {
6426   CallScopeRAII CallScope(Info);
6427   CallRef Call = Info.CurrentCall->createCall(Definition);
6428   if (!EvaluateArgs(Args, Call, Info, Definition))
6429     return false;
6430 
6431   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6432          CallScope.destroy();
6433 }
6434 
6435 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6436                                   const LValue &This, APValue &Value,
6437                                   QualType T) {
6438   // Objects can only be destroyed while they're within their lifetimes.
6439   // FIXME: We have no representation for whether an object of type nullptr_t
6440   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6441   // as indeterminate instead?
6442   if (Value.isAbsent() && !T->isNullPtrType()) {
6443     APValue Printable;
6444     This.moveInto(Printable);
6445     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6446       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6447     return false;
6448   }
6449 
6450   // Invent an expression for location purposes.
6451   // FIXME: We shouldn't need to do this.
6452   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6453 
6454   // For arrays, destroy elements right-to-left.
6455   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6456     uint64_t Size = CAT->getSize().getZExtValue();
6457     QualType ElemT = CAT->getElementType();
6458 
6459     LValue ElemLV = This;
6460     ElemLV.addArray(Info, &LocE, CAT);
6461     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6462       return false;
6463 
6464     // Ensure that we have actual array elements available to destroy; the
6465     // destructors might mutate the value, so we can't run them on the array
6466     // filler.
6467     if (Size && Size > Value.getArrayInitializedElts())
6468       expandArray(Value, Value.getArraySize() - 1);
6469 
6470     for (; Size != 0; --Size) {
6471       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6472       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6473           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6474         return false;
6475     }
6476 
6477     // End the lifetime of this array now.
6478     Value = APValue();
6479     return true;
6480   }
6481 
6482   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6483   if (!RD) {
6484     if (T.isDestructedType()) {
6485       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6486       return false;
6487     }
6488 
6489     Value = APValue();
6490     return true;
6491   }
6492 
6493   if (RD->getNumVBases()) {
6494     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6495     return false;
6496   }
6497 
6498   const CXXDestructorDecl *DD = RD->getDestructor();
6499   if (!DD && !RD->hasTrivialDestructor()) {
6500     Info.FFDiag(CallLoc);
6501     return false;
6502   }
6503 
6504   if (!DD || DD->isTrivial() ||
6505       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6506     // A trivial destructor just ends the lifetime of the object. Check for
6507     // this case before checking for a body, because we might not bother
6508     // building a body for a trivial destructor. Note that it doesn't matter
6509     // whether the destructor is constexpr in this case; all trivial
6510     // destructors are constexpr.
6511     //
6512     // If an anonymous union would be destroyed, some enclosing destructor must
6513     // have been explicitly defined, and the anonymous union destruction should
6514     // have no effect.
6515     Value = APValue();
6516     return true;
6517   }
6518 
6519   if (!Info.CheckCallLimit(CallLoc))
6520     return false;
6521 
6522   const FunctionDecl *Definition = nullptr;
6523   const Stmt *Body = DD->getBody(Definition);
6524 
6525   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6526     return false;
6527 
6528   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6529 
6530   // We're now in the period of destruction of this object.
6531   unsigned BasesLeft = RD->getNumBases();
6532   EvalInfo::EvaluatingDestructorRAII EvalObj(
6533       Info,
6534       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6535   if (!EvalObj.DidInsert) {
6536     // C++2a [class.dtor]p19:
6537     //   the behavior is undefined if the destructor is invoked for an object
6538     //   whose lifetime has ended
6539     // (Note that formally the lifetime ends when the period of destruction
6540     // begins, even though certain uses of the object remain valid until the
6541     // period of destruction ends.)
6542     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6543     return false;
6544   }
6545 
6546   // FIXME: Creating an APValue just to hold a nonexistent return value is
6547   // wasteful.
6548   APValue RetVal;
6549   StmtResult Ret = {RetVal, nullptr};
6550   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6551     return false;
6552 
6553   // A union destructor does not implicitly destroy its members.
6554   if (RD->isUnion())
6555     return true;
6556 
6557   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6558 
6559   // We don't have a good way to iterate fields in reverse, so collect all the
6560   // fields first and then walk them backwards.
6561   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6562   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6563     if (FD->isUnnamedBitfield())
6564       continue;
6565 
6566     LValue Subobject = This;
6567     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6568       return false;
6569 
6570     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6571     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6572                                FD->getType()))
6573       return false;
6574   }
6575 
6576   if (BasesLeft != 0)
6577     EvalObj.startedDestroyingBases();
6578 
6579   // Destroy base classes in reverse order.
6580   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6581     --BasesLeft;
6582 
6583     QualType BaseType = Base.getType();
6584     LValue Subobject = This;
6585     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6586                                 BaseType->getAsCXXRecordDecl(), &Layout))
6587       return false;
6588 
6589     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6590     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6591                                BaseType))
6592       return false;
6593   }
6594   assert(BasesLeft == 0 && "NumBases was wrong?");
6595 
6596   // The period of destruction ends now. The object is gone.
6597   Value = APValue();
6598   return true;
6599 }
6600 
6601 namespace {
6602 struct DestroyObjectHandler {
6603   EvalInfo &Info;
6604   const Expr *E;
6605   const LValue &This;
6606   const AccessKinds AccessKind;
6607 
6608   typedef bool result_type;
6609   bool failed() { return false; }
6610   bool found(APValue &Subobj, QualType SubobjType) {
6611     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6612                                  SubobjType);
6613   }
6614   bool found(APSInt &Value, QualType SubobjType) {
6615     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6616     return false;
6617   }
6618   bool found(APFloat &Value, QualType SubobjType) {
6619     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6620     return false;
6621   }
6622 };
6623 }
6624 
6625 /// Perform a destructor or pseudo-destructor call on the given object, which
6626 /// might in general not be a complete object.
6627 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6628                               const LValue &This, QualType ThisType) {
6629   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6630   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6631   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6632 }
6633 
6634 /// Destroy and end the lifetime of the given complete object.
6635 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6636                               APValue::LValueBase LVBase, APValue &Value,
6637                               QualType T) {
6638   // If we've had an unmodeled side-effect, we can't rely on mutable state
6639   // (such as the object we're about to destroy) being correct.
6640   if (Info.EvalStatus.HasSideEffects)
6641     return false;
6642 
6643   LValue LV;
6644   LV.set({LVBase});
6645   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6646 }
6647 
6648 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6649 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6650                                   LValue &Result) {
6651   if (Info.checkingPotentialConstantExpression() ||
6652       Info.SpeculativeEvaluationDepth)
6653     return false;
6654 
6655   // This is permitted only within a call to std::allocator<T>::allocate.
6656   auto Caller = Info.getStdAllocatorCaller("allocate");
6657   if (!Caller) {
6658     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6659                                      ? diag::note_constexpr_new_untyped
6660                                      : diag::note_constexpr_new);
6661     return false;
6662   }
6663 
6664   QualType ElemType = Caller.ElemType;
6665   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6666     Info.FFDiag(E->getExprLoc(),
6667                 diag::note_constexpr_new_not_complete_object_type)
6668         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6669     return false;
6670   }
6671 
6672   APSInt ByteSize;
6673   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6674     return false;
6675   bool IsNothrow = false;
6676   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6677     EvaluateIgnoredValue(Info, E->getArg(I));
6678     IsNothrow |= E->getType()->isNothrowT();
6679   }
6680 
6681   CharUnits ElemSize;
6682   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6683     return false;
6684   APInt Size, Remainder;
6685   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6686   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6687   if (Remainder != 0) {
6688     // This likely indicates a bug in the implementation of 'std::allocator'.
6689     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6690         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6691     return false;
6692   }
6693 
6694   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6695     if (IsNothrow) {
6696       Result.setNull(Info.Ctx, E->getType());
6697       return true;
6698     }
6699 
6700     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6701     return false;
6702   }
6703 
6704   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6705                                                      ArrayType::Normal, 0);
6706   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6707   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6708   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6709   return true;
6710 }
6711 
6712 static bool hasVirtualDestructor(QualType T) {
6713   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6714     if (CXXDestructorDecl *DD = RD->getDestructor())
6715       return DD->isVirtual();
6716   return false;
6717 }
6718 
6719 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6720   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6721     if (CXXDestructorDecl *DD = RD->getDestructor())
6722       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6723   return nullptr;
6724 }
6725 
6726 /// Check that the given object is a suitable pointer to a heap allocation that
6727 /// still exists and is of the right kind for the purpose of a deletion.
6728 ///
6729 /// On success, returns the heap allocation to deallocate. On failure, produces
6730 /// a diagnostic and returns None.
6731 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6732                                             const LValue &Pointer,
6733                                             DynAlloc::Kind DeallocKind) {
6734   auto PointerAsString = [&] {
6735     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6736   };
6737 
6738   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6739   if (!DA) {
6740     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6741         << PointerAsString();
6742     if (Pointer.Base)
6743       NoteLValueLocation(Info, Pointer.Base);
6744     return None;
6745   }
6746 
6747   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6748   if (!Alloc) {
6749     Info.FFDiag(E, diag::note_constexpr_double_delete);
6750     return None;
6751   }
6752 
6753   QualType AllocType = Pointer.Base.getDynamicAllocType();
6754   if (DeallocKind != (*Alloc)->getKind()) {
6755     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6756         << DeallocKind << (*Alloc)->getKind() << AllocType;
6757     NoteLValueLocation(Info, Pointer.Base);
6758     return None;
6759   }
6760 
6761   bool Subobject = false;
6762   if (DeallocKind == DynAlloc::New) {
6763     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6764                 Pointer.Designator.isOnePastTheEnd();
6765   } else {
6766     Subobject = Pointer.Designator.Entries.size() != 1 ||
6767                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6768   }
6769   if (Subobject) {
6770     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6771         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6772     return None;
6773   }
6774 
6775   return Alloc;
6776 }
6777 
6778 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6779 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6780   if (Info.checkingPotentialConstantExpression() ||
6781       Info.SpeculativeEvaluationDepth)
6782     return false;
6783 
6784   // This is permitted only within a call to std::allocator<T>::deallocate.
6785   if (!Info.getStdAllocatorCaller("deallocate")) {
6786     Info.FFDiag(E->getExprLoc());
6787     return true;
6788   }
6789 
6790   LValue Pointer;
6791   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6792     return false;
6793   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6794     EvaluateIgnoredValue(Info, E->getArg(I));
6795 
6796   if (Pointer.Designator.Invalid)
6797     return false;
6798 
6799   // Deleting a null pointer would have no effect, but it's not permitted by
6800   // std::allocator<T>::deallocate's contract.
6801   if (Pointer.isNullPointer()) {
6802     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6803     return true;
6804   }
6805 
6806   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6807     return false;
6808 
6809   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6810   return true;
6811 }
6812 
6813 //===----------------------------------------------------------------------===//
6814 // Generic Evaluation
6815 //===----------------------------------------------------------------------===//
6816 namespace {
6817 
6818 class BitCastBuffer {
6819   // FIXME: We're going to need bit-level granularity when we support
6820   // bit-fields.
6821   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6822   // we don't support a host or target where that is the case. Still, we should
6823   // use a more generic type in case we ever do.
6824   SmallVector<Optional<unsigned char>, 32> Bytes;
6825 
6826   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6827                 "Need at least 8 bit unsigned char");
6828 
6829   bool TargetIsLittleEndian;
6830 
6831 public:
6832   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6833       : Bytes(Width.getQuantity()),
6834         TargetIsLittleEndian(TargetIsLittleEndian) {}
6835 
6836   LLVM_NODISCARD
6837   bool readObject(CharUnits Offset, CharUnits Width,
6838                   SmallVectorImpl<unsigned char> &Output) const {
6839     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6840       // If a byte of an integer is uninitialized, then the whole integer is
6841       // uninitialized.
6842       if (!Bytes[I.getQuantity()])
6843         return false;
6844       Output.push_back(*Bytes[I.getQuantity()]);
6845     }
6846     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6847       std::reverse(Output.begin(), Output.end());
6848     return true;
6849   }
6850 
6851   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6852     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6853       std::reverse(Input.begin(), Input.end());
6854 
6855     size_t Index = 0;
6856     for (unsigned char Byte : Input) {
6857       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6858       Bytes[Offset.getQuantity() + Index] = Byte;
6859       ++Index;
6860     }
6861   }
6862 
6863   size_t size() { return Bytes.size(); }
6864 };
6865 
6866 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6867 /// target would represent the value at runtime.
6868 class APValueToBufferConverter {
6869   EvalInfo &Info;
6870   BitCastBuffer Buffer;
6871   const CastExpr *BCE;
6872 
6873   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6874                            const CastExpr *BCE)
6875       : Info(Info),
6876         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6877         BCE(BCE) {}
6878 
6879   bool visit(const APValue &Val, QualType Ty) {
6880     return visit(Val, Ty, CharUnits::fromQuantity(0));
6881   }
6882 
6883   // Write out Val with type Ty into Buffer starting at Offset.
6884   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6885     assert((size_t)Offset.getQuantity() <= Buffer.size());
6886 
6887     // As a special case, nullptr_t has an indeterminate value.
6888     if (Ty->isNullPtrType())
6889       return true;
6890 
6891     // Dig through Src to find the byte at SrcOffset.
6892     switch (Val.getKind()) {
6893     case APValue::Indeterminate:
6894     case APValue::None:
6895       return true;
6896 
6897     case APValue::Int:
6898       return visitInt(Val.getInt(), Ty, Offset);
6899     case APValue::Float:
6900       return visitFloat(Val.getFloat(), Ty, Offset);
6901     case APValue::Array:
6902       return visitArray(Val, Ty, Offset);
6903     case APValue::Struct:
6904       return visitRecord(Val, Ty, Offset);
6905 
6906     case APValue::ComplexInt:
6907     case APValue::ComplexFloat:
6908     case APValue::Vector:
6909     case APValue::FixedPoint:
6910       // FIXME: We should support these.
6911 
6912     case APValue::Union:
6913     case APValue::MemberPointer:
6914     case APValue::AddrLabelDiff: {
6915       Info.FFDiag(BCE->getBeginLoc(),
6916                   diag::note_constexpr_bit_cast_unsupported_type)
6917           << Ty;
6918       return false;
6919     }
6920 
6921     case APValue::LValue:
6922       llvm_unreachable("LValue subobject in bit_cast?");
6923     }
6924     llvm_unreachable("Unhandled APValue::ValueKind");
6925   }
6926 
6927   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6928     const RecordDecl *RD = Ty->getAsRecordDecl();
6929     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6930 
6931     // Visit the base classes.
6932     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6933       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6934         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6935         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6936 
6937         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6938                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6939           return false;
6940       }
6941     }
6942 
6943     // Visit the fields.
6944     unsigned FieldIdx = 0;
6945     for (FieldDecl *FD : RD->fields()) {
6946       if (FD->isBitField()) {
6947         Info.FFDiag(BCE->getBeginLoc(),
6948                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6949         return false;
6950       }
6951 
6952       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6953 
6954       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6955              "only bit-fields can have sub-char alignment");
6956       CharUnits FieldOffset =
6957           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6958       QualType FieldTy = FD->getType();
6959       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6960         return false;
6961       ++FieldIdx;
6962     }
6963 
6964     return true;
6965   }
6966 
6967   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6968     const auto *CAT =
6969         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6970     if (!CAT)
6971       return false;
6972 
6973     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6974     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6975     unsigned ArraySize = Val.getArraySize();
6976     // First, initialize the initialized elements.
6977     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6978       const APValue &SubObj = Val.getArrayInitializedElt(I);
6979       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6980         return false;
6981     }
6982 
6983     // Next, initialize the rest of the array using the filler.
6984     if (Val.hasArrayFiller()) {
6985       const APValue &Filler = Val.getArrayFiller();
6986       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6987         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6988           return false;
6989       }
6990     }
6991 
6992     return true;
6993   }
6994 
6995   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6996     APSInt AdjustedVal = Val;
6997     unsigned Width = AdjustedVal.getBitWidth();
6998     if (Ty->isBooleanType()) {
6999       Width = Info.Ctx.getTypeSize(Ty);
7000       AdjustedVal = AdjustedVal.extend(Width);
7001     }
7002 
7003     SmallVector<unsigned char, 8> Bytes(Width / 8);
7004     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7005     Buffer.writeObject(Offset, Bytes);
7006     return true;
7007   }
7008 
7009   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7010     APSInt AsInt(Val.bitcastToAPInt());
7011     return visitInt(AsInt, Ty, Offset);
7012   }
7013 
7014 public:
7015   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
7016                                          const CastExpr *BCE) {
7017     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7018     APValueToBufferConverter Converter(Info, DstSize, BCE);
7019     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7020       return None;
7021     return Converter.Buffer;
7022   }
7023 };
7024 
7025 /// Write an BitCastBuffer into an APValue.
7026 class BufferToAPValueConverter {
7027   EvalInfo &Info;
7028   const BitCastBuffer &Buffer;
7029   const CastExpr *BCE;
7030 
7031   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7032                            const CastExpr *BCE)
7033       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7034 
7035   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7036   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7037   // Ideally this will be unreachable.
7038   llvm::NoneType unsupportedType(QualType Ty) {
7039     Info.FFDiag(BCE->getBeginLoc(),
7040                 diag::note_constexpr_bit_cast_unsupported_type)
7041         << Ty;
7042     return None;
7043   }
7044 
7045   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
7046     Info.FFDiag(BCE->getBeginLoc(),
7047                 diag::note_constexpr_bit_cast_unrepresentable_value)
7048         << Ty << toString(Val, /*Radix=*/10);
7049     return None;
7050   }
7051 
7052   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7053                           const EnumType *EnumSugar = nullptr) {
7054     if (T->isNullPtrType()) {
7055       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7056       return APValue((Expr *)nullptr,
7057                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7058                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7059     }
7060 
7061     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7062 
7063     // Work around floating point types that contain unused padding bytes. This
7064     // is really just `long double` on x86, which is the only fundamental type
7065     // with padding bytes.
7066     if (T->isRealFloatingType()) {
7067       const llvm::fltSemantics &Semantics =
7068           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7069       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7070       assert(NumBits % 8 == 0);
7071       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7072       if (NumBytes != SizeOf)
7073         SizeOf = NumBytes;
7074     }
7075 
7076     SmallVector<uint8_t, 8> Bytes;
7077     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7078       // If this is std::byte or unsigned char, then its okay to store an
7079       // indeterminate value.
7080       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7081       bool IsUChar =
7082           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7083                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7084       if (!IsStdByte && !IsUChar) {
7085         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7086         Info.FFDiag(BCE->getExprLoc(),
7087                     diag::note_constexpr_bit_cast_indet_dest)
7088             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7089         return None;
7090       }
7091 
7092       return APValue::IndeterminateValue();
7093     }
7094 
7095     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7096     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7097 
7098     if (T->isIntegralOrEnumerationType()) {
7099       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7100 
7101       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7102       if (IntWidth != Val.getBitWidth()) {
7103         APSInt Truncated = Val.trunc(IntWidth);
7104         if (Truncated.extend(Val.getBitWidth()) != Val)
7105           return unrepresentableValue(QualType(T, 0), Val);
7106         Val = Truncated;
7107       }
7108 
7109       return APValue(Val);
7110     }
7111 
7112     if (T->isRealFloatingType()) {
7113       const llvm::fltSemantics &Semantics =
7114           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7115       return APValue(APFloat(Semantics, Val));
7116     }
7117 
7118     return unsupportedType(QualType(T, 0));
7119   }
7120 
7121   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7122     const RecordDecl *RD = RTy->getAsRecordDecl();
7123     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7124 
7125     unsigned NumBases = 0;
7126     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7127       NumBases = CXXRD->getNumBases();
7128 
7129     APValue ResultVal(APValue::UninitStruct(), NumBases,
7130                       std::distance(RD->field_begin(), RD->field_end()));
7131 
7132     // Visit the base classes.
7133     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7134       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7135         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7136         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7137         if (BaseDecl->isEmpty() ||
7138             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7139           continue;
7140 
7141         Optional<APValue> SubObj = visitType(
7142             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7143         if (!SubObj)
7144           return None;
7145         ResultVal.getStructBase(I) = *SubObj;
7146       }
7147     }
7148 
7149     // Visit the fields.
7150     unsigned FieldIdx = 0;
7151     for (FieldDecl *FD : RD->fields()) {
7152       // FIXME: We don't currently support bit-fields. A lot of the logic for
7153       // this is in CodeGen, so we need to factor it around.
7154       if (FD->isBitField()) {
7155         Info.FFDiag(BCE->getBeginLoc(),
7156                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7157         return None;
7158       }
7159 
7160       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7161       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7162 
7163       CharUnits FieldOffset =
7164           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7165           Offset;
7166       QualType FieldTy = FD->getType();
7167       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7168       if (!SubObj)
7169         return None;
7170       ResultVal.getStructField(FieldIdx) = *SubObj;
7171       ++FieldIdx;
7172     }
7173 
7174     return ResultVal;
7175   }
7176 
7177   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7178     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7179     assert(!RepresentationType.isNull() &&
7180            "enum forward decl should be caught by Sema");
7181     const auto *AsBuiltin =
7182         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7183     // Recurse into the underlying type. Treat std::byte transparently as
7184     // unsigned char.
7185     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7186   }
7187 
7188   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7189     size_t Size = Ty->getSize().getLimitedValue();
7190     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7191 
7192     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7193     for (size_t I = 0; I != Size; ++I) {
7194       Optional<APValue> ElementValue =
7195           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7196       if (!ElementValue)
7197         return None;
7198       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7199     }
7200 
7201     return ArrayValue;
7202   }
7203 
7204   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7205     return unsupportedType(QualType(Ty, 0));
7206   }
7207 
7208   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7209     QualType Can = Ty.getCanonicalType();
7210 
7211     switch (Can->getTypeClass()) {
7212 #define TYPE(Class, Base)                                                      \
7213   case Type::Class:                                                            \
7214     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7215 #define ABSTRACT_TYPE(Class, Base)
7216 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7217   case Type::Class:                                                            \
7218     llvm_unreachable("non-canonical type should be impossible!");
7219 #define DEPENDENT_TYPE(Class, Base)                                            \
7220   case Type::Class:                                                            \
7221     llvm_unreachable(                                                          \
7222         "dependent types aren't supported in the constant evaluator!");
7223 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7224   case Type::Class:                                                            \
7225     llvm_unreachable("either dependent or not canonical!");
7226 #include "clang/AST/TypeNodes.inc"
7227     }
7228     llvm_unreachable("Unhandled Type::TypeClass");
7229   }
7230 
7231 public:
7232   // Pull out a full value of type DstType.
7233   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7234                                    const CastExpr *BCE) {
7235     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7236     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7237   }
7238 };
7239 
7240 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7241                                                  QualType Ty, EvalInfo *Info,
7242                                                  const ASTContext &Ctx,
7243                                                  bool CheckingDest) {
7244   Ty = Ty.getCanonicalType();
7245 
7246   auto diag = [&](int Reason) {
7247     if (Info)
7248       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7249           << CheckingDest << (Reason == 4) << Reason;
7250     return false;
7251   };
7252   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7253     if (Info)
7254       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7255           << NoteTy << Construct << Ty;
7256     return false;
7257   };
7258 
7259   if (Ty->isUnionType())
7260     return diag(0);
7261   if (Ty->isPointerType())
7262     return diag(1);
7263   if (Ty->isMemberPointerType())
7264     return diag(2);
7265   if (Ty.isVolatileQualified())
7266     return diag(3);
7267 
7268   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7269     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7270       for (CXXBaseSpecifier &BS : CXXRD->bases())
7271         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7272                                                   CheckingDest))
7273           return note(1, BS.getType(), BS.getBeginLoc());
7274     }
7275     for (FieldDecl *FD : Record->fields()) {
7276       if (FD->getType()->isReferenceType())
7277         return diag(4);
7278       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7279                                                 CheckingDest))
7280         return note(0, FD->getType(), FD->getBeginLoc());
7281     }
7282   }
7283 
7284   if (Ty->isArrayType() &&
7285       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7286                                             Info, Ctx, CheckingDest))
7287     return false;
7288 
7289   return true;
7290 }
7291 
7292 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7293                                              const ASTContext &Ctx,
7294                                              const CastExpr *BCE) {
7295   bool DestOK = checkBitCastConstexprEligibilityType(
7296       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7297   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7298                                 BCE->getBeginLoc(),
7299                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7300   return SourceOK;
7301 }
7302 
7303 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7304                                         APValue &SourceValue,
7305                                         const CastExpr *BCE) {
7306   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7307          "no host or target supports non 8-bit chars");
7308   assert(SourceValue.isLValue() &&
7309          "LValueToRValueBitcast requires an lvalue operand!");
7310 
7311   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7312     return false;
7313 
7314   LValue SourceLValue;
7315   APValue SourceRValue;
7316   SourceLValue.setFrom(Info.Ctx, SourceValue);
7317   if (!handleLValueToRValueConversion(
7318           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7319           SourceRValue, /*WantObjectRepresentation=*/true))
7320     return false;
7321 
7322   // Read out SourceValue into a char buffer.
7323   Optional<BitCastBuffer> Buffer =
7324       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7325   if (!Buffer)
7326     return false;
7327 
7328   // Write out the buffer into a new APValue.
7329   Optional<APValue> MaybeDestValue =
7330       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7331   if (!MaybeDestValue)
7332     return false;
7333 
7334   DestValue = std::move(*MaybeDestValue);
7335   return true;
7336 }
7337 
7338 template <class Derived>
7339 class ExprEvaluatorBase
7340   : public ConstStmtVisitor<Derived, bool> {
7341 private:
7342   Derived &getDerived() { return static_cast<Derived&>(*this); }
7343   bool DerivedSuccess(const APValue &V, const Expr *E) {
7344     return getDerived().Success(V, E);
7345   }
7346   bool DerivedZeroInitialization(const Expr *E) {
7347     return getDerived().ZeroInitialization(E);
7348   }
7349 
7350   // Check whether a conditional operator with a non-constant condition is a
7351   // potential constant expression. If neither arm is a potential constant
7352   // expression, then the conditional operator is not either.
7353   template<typename ConditionalOperator>
7354   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7355     assert(Info.checkingPotentialConstantExpression());
7356 
7357     // Speculatively evaluate both arms.
7358     SmallVector<PartialDiagnosticAt, 8> Diag;
7359     {
7360       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7361       StmtVisitorTy::Visit(E->getFalseExpr());
7362       if (Diag.empty())
7363         return;
7364     }
7365 
7366     {
7367       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7368       Diag.clear();
7369       StmtVisitorTy::Visit(E->getTrueExpr());
7370       if (Diag.empty())
7371         return;
7372     }
7373 
7374     Error(E, diag::note_constexpr_conditional_never_const);
7375   }
7376 
7377 
7378   template<typename ConditionalOperator>
7379   bool HandleConditionalOperator(const ConditionalOperator *E) {
7380     bool BoolResult;
7381     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7382       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7383         CheckPotentialConstantConditional(E);
7384         return false;
7385       }
7386       if (Info.noteFailure()) {
7387         StmtVisitorTy::Visit(E->getTrueExpr());
7388         StmtVisitorTy::Visit(E->getFalseExpr());
7389       }
7390       return false;
7391     }
7392 
7393     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7394     return StmtVisitorTy::Visit(EvalExpr);
7395   }
7396 
7397 protected:
7398   EvalInfo &Info;
7399   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7400   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7401 
7402   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7403     return Info.CCEDiag(E, D);
7404   }
7405 
7406   bool ZeroInitialization(const Expr *E) { return Error(E); }
7407 
7408 public:
7409   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7410 
7411   EvalInfo &getEvalInfo() { return Info; }
7412 
7413   /// Report an evaluation error. This should only be called when an error is
7414   /// first discovered. When propagating an error, just return false.
7415   bool Error(const Expr *E, diag::kind D) {
7416     Info.FFDiag(E, D);
7417     return false;
7418   }
7419   bool Error(const Expr *E) {
7420     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7421   }
7422 
7423   bool VisitStmt(const Stmt *) {
7424     llvm_unreachable("Expression evaluator should not be called on stmts");
7425   }
7426   bool VisitExpr(const Expr *E) {
7427     return Error(E);
7428   }
7429 
7430   bool VisitConstantExpr(const ConstantExpr *E) {
7431     if (E->hasAPValueResult())
7432       return DerivedSuccess(E->getAPValueResult(), E);
7433 
7434     return StmtVisitorTy::Visit(E->getSubExpr());
7435   }
7436 
7437   bool VisitParenExpr(const ParenExpr *E)
7438     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7439   bool VisitUnaryExtension(const UnaryOperator *E)
7440     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7441   bool VisitUnaryPlus(const UnaryOperator *E)
7442     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7443   bool VisitChooseExpr(const ChooseExpr *E)
7444     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7445   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7446     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7447   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7448     { return StmtVisitorTy::Visit(E->getReplacement()); }
7449   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7450     TempVersionRAII RAII(*Info.CurrentCall);
7451     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7452     return StmtVisitorTy::Visit(E->getExpr());
7453   }
7454   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7455     TempVersionRAII RAII(*Info.CurrentCall);
7456     // The initializer may not have been parsed yet, or might be erroneous.
7457     if (!E->getExpr())
7458       return Error(E);
7459     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7460     return StmtVisitorTy::Visit(E->getExpr());
7461   }
7462 
7463   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7464     FullExpressionRAII Scope(Info);
7465     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7466   }
7467 
7468   // Temporaries are registered when created, so we don't care about
7469   // CXXBindTemporaryExpr.
7470   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7471     return StmtVisitorTy::Visit(E->getSubExpr());
7472   }
7473 
7474   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7475     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7476     return static_cast<Derived*>(this)->VisitCastExpr(E);
7477   }
7478   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7479     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7480       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7481     return static_cast<Derived*>(this)->VisitCastExpr(E);
7482   }
7483   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7484     return static_cast<Derived*>(this)->VisitCastExpr(E);
7485   }
7486 
7487   bool VisitBinaryOperator(const BinaryOperator *E) {
7488     switch (E->getOpcode()) {
7489     default:
7490       return Error(E);
7491 
7492     case BO_Comma:
7493       VisitIgnoredValue(E->getLHS());
7494       return StmtVisitorTy::Visit(E->getRHS());
7495 
7496     case BO_PtrMemD:
7497     case BO_PtrMemI: {
7498       LValue Obj;
7499       if (!HandleMemberPointerAccess(Info, E, Obj))
7500         return false;
7501       APValue Result;
7502       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7503         return false;
7504       return DerivedSuccess(Result, E);
7505     }
7506     }
7507   }
7508 
7509   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7510     return StmtVisitorTy::Visit(E->getSemanticForm());
7511   }
7512 
7513   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7514     // Evaluate and cache the common expression. We treat it as a temporary,
7515     // even though it's not quite the same thing.
7516     LValue CommonLV;
7517     if (!Evaluate(Info.CurrentCall->createTemporary(
7518                       E->getOpaqueValue(),
7519                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7520                       ScopeKind::FullExpression, CommonLV),
7521                   Info, E->getCommon()))
7522       return false;
7523 
7524     return HandleConditionalOperator(E);
7525   }
7526 
7527   bool VisitConditionalOperator(const ConditionalOperator *E) {
7528     bool IsBcpCall = false;
7529     // If the condition (ignoring parens) is a __builtin_constant_p call,
7530     // the result is a constant expression if it can be folded without
7531     // side-effects. This is an important GNU extension. See GCC PR38377
7532     // for discussion.
7533     if (const CallExpr *CallCE =
7534           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7535       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7536         IsBcpCall = true;
7537 
7538     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7539     // constant expression; we can't check whether it's potentially foldable.
7540     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7541     // it would return 'false' in this mode.
7542     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7543       return false;
7544 
7545     FoldConstant Fold(Info, IsBcpCall);
7546     if (!HandleConditionalOperator(E)) {
7547       Fold.keepDiagnostics();
7548       return false;
7549     }
7550 
7551     return true;
7552   }
7553 
7554   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7555     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7556       return DerivedSuccess(*Value, E);
7557 
7558     const Expr *Source = E->getSourceExpr();
7559     if (!Source)
7560       return Error(E);
7561     if (Source == E) {
7562       assert(0 && "OpaqueValueExpr recursively refers to itself");
7563       return Error(E);
7564     }
7565     return StmtVisitorTy::Visit(Source);
7566   }
7567 
7568   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7569     for (const Expr *SemE : E->semantics()) {
7570       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7571         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7572         // result expression: there could be two different LValues that would
7573         // refer to the same object in that case, and we can't model that.
7574         if (SemE == E->getResultExpr())
7575           return Error(E);
7576 
7577         // Unique OVEs get evaluated if and when we encounter them when
7578         // emitting the rest of the semantic form, rather than eagerly.
7579         if (OVE->isUnique())
7580           continue;
7581 
7582         LValue LV;
7583         if (!Evaluate(Info.CurrentCall->createTemporary(
7584                           OVE, getStorageType(Info.Ctx, OVE),
7585                           ScopeKind::FullExpression, LV),
7586                       Info, OVE->getSourceExpr()))
7587           return false;
7588       } else if (SemE == E->getResultExpr()) {
7589         if (!StmtVisitorTy::Visit(SemE))
7590           return false;
7591       } else {
7592         if (!EvaluateIgnoredValue(Info, SemE))
7593           return false;
7594       }
7595     }
7596     return true;
7597   }
7598 
7599   bool VisitCallExpr(const CallExpr *E) {
7600     APValue Result;
7601     if (!handleCallExpr(E, Result, nullptr))
7602       return false;
7603     return DerivedSuccess(Result, E);
7604   }
7605 
7606   bool handleCallExpr(const CallExpr *E, APValue &Result,
7607                      const LValue *ResultSlot) {
7608     CallScopeRAII CallScope(Info);
7609 
7610     const Expr *Callee = E->getCallee()->IgnoreParens();
7611     QualType CalleeType = Callee->getType();
7612 
7613     const FunctionDecl *FD = nullptr;
7614     LValue *This = nullptr, ThisVal;
7615     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7616     bool HasQualifier = false;
7617 
7618     CallRef Call;
7619 
7620     // Extract function decl and 'this' pointer from the callee.
7621     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7622       const CXXMethodDecl *Member = nullptr;
7623       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7624         // Explicit bound member calls, such as x.f() or p->g();
7625         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7626           return false;
7627         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7628         if (!Member)
7629           return Error(Callee);
7630         This = &ThisVal;
7631         HasQualifier = ME->hasQualifier();
7632       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7633         // Indirect bound member calls ('.*' or '->*').
7634         const ValueDecl *D =
7635             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7636         if (!D)
7637           return false;
7638         Member = dyn_cast<CXXMethodDecl>(D);
7639         if (!Member)
7640           return Error(Callee);
7641         This = &ThisVal;
7642       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7643         if (!Info.getLangOpts().CPlusPlus20)
7644           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7645         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7646                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7647       } else
7648         return Error(Callee);
7649       FD = Member;
7650     } else if (CalleeType->isFunctionPointerType()) {
7651       LValue CalleeLV;
7652       if (!EvaluatePointer(Callee, CalleeLV, Info))
7653         return false;
7654 
7655       if (!CalleeLV.getLValueOffset().isZero())
7656         return Error(Callee);
7657       FD = dyn_cast_or_null<FunctionDecl>(
7658           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7659       if (!FD)
7660         return Error(Callee);
7661       // Don't call function pointers which have been cast to some other type.
7662       // Per DR (no number yet), the caller and callee can differ in noexcept.
7663       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7664         CalleeType->getPointeeType(), FD->getType())) {
7665         return Error(E);
7666       }
7667 
7668       // For an (overloaded) assignment expression, evaluate the RHS before the
7669       // LHS.
7670       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7671       if (OCE && OCE->isAssignmentOp()) {
7672         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7673         Call = Info.CurrentCall->createCall(FD);
7674         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7675                           Info, FD, /*RightToLeft=*/true))
7676           return false;
7677       }
7678 
7679       // Overloaded operator calls to member functions are represented as normal
7680       // calls with '*this' as the first argument.
7681       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7682       if (MD && !MD->isStatic()) {
7683         // FIXME: When selecting an implicit conversion for an overloaded
7684         // operator delete, we sometimes try to evaluate calls to conversion
7685         // operators without a 'this' parameter!
7686         if (Args.empty())
7687           return Error(E);
7688 
7689         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7690           return false;
7691         This = &ThisVal;
7692 
7693         // If this is syntactically a simple assignment using a trivial
7694         // assignment operator, start the lifetimes of union members as needed,
7695         // per C++20 [class.union]5.
7696         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7697             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7698             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7699           return false;
7700 
7701         Args = Args.slice(1);
7702       } else if (MD && MD->isLambdaStaticInvoker()) {
7703         // Map the static invoker for the lambda back to the call operator.
7704         // Conveniently, we don't have to slice out the 'this' argument (as is
7705         // being done for the non-static case), since a static member function
7706         // doesn't have an implicit argument passed in.
7707         const CXXRecordDecl *ClosureClass = MD->getParent();
7708         assert(
7709             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7710             "Number of captures must be zero for conversion to function-ptr");
7711 
7712         const CXXMethodDecl *LambdaCallOp =
7713             ClosureClass->getLambdaCallOperator();
7714 
7715         // Set 'FD', the function that will be called below, to the call
7716         // operator.  If the closure object represents a generic lambda, find
7717         // the corresponding specialization of the call operator.
7718 
7719         if (ClosureClass->isGenericLambda()) {
7720           assert(MD->isFunctionTemplateSpecialization() &&
7721                  "A generic lambda's static-invoker function must be a "
7722                  "template specialization");
7723           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7724           FunctionTemplateDecl *CallOpTemplate =
7725               LambdaCallOp->getDescribedFunctionTemplate();
7726           void *InsertPos = nullptr;
7727           FunctionDecl *CorrespondingCallOpSpecialization =
7728               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7729           assert(CorrespondingCallOpSpecialization &&
7730                  "We must always have a function call operator specialization "
7731                  "that corresponds to our static invoker specialization");
7732           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7733         } else
7734           FD = LambdaCallOp;
7735       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7736         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7737             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7738           LValue Ptr;
7739           if (!HandleOperatorNewCall(Info, E, Ptr))
7740             return false;
7741           Ptr.moveInto(Result);
7742           return CallScope.destroy();
7743         } else {
7744           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7745         }
7746       }
7747     } else
7748       return Error(E);
7749 
7750     // Evaluate the arguments now if we've not already done so.
7751     if (!Call) {
7752       Call = Info.CurrentCall->createCall(FD);
7753       if (!EvaluateArgs(Args, Call, Info, FD))
7754         return false;
7755     }
7756 
7757     SmallVector<QualType, 4> CovariantAdjustmentPath;
7758     if (This) {
7759       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7760       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7761         // Perform virtual dispatch, if necessary.
7762         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7763                                    CovariantAdjustmentPath);
7764         if (!FD)
7765           return false;
7766       } else {
7767         // Check that the 'this' pointer points to an object of the right type.
7768         // FIXME: If this is an assignment operator call, we may need to change
7769         // the active union member before we check this.
7770         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7771           return false;
7772       }
7773     }
7774 
7775     // Destructor calls are different enough that they have their own codepath.
7776     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7777       assert(This && "no 'this' pointer for destructor call");
7778       return HandleDestruction(Info, E, *This,
7779                                Info.Ctx.getRecordType(DD->getParent())) &&
7780              CallScope.destroy();
7781     }
7782 
7783     const FunctionDecl *Definition = nullptr;
7784     Stmt *Body = FD->getBody(Definition);
7785 
7786     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7787         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7788                             Body, Info, Result, ResultSlot))
7789       return false;
7790 
7791     if (!CovariantAdjustmentPath.empty() &&
7792         !HandleCovariantReturnAdjustment(Info, E, Result,
7793                                          CovariantAdjustmentPath))
7794       return false;
7795 
7796     return CallScope.destroy();
7797   }
7798 
7799   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7800     return StmtVisitorTy::Visit(E->getInitializer());
7801   }
7802   bool VisitInitListExpr(const InitListExpr *E) {
7803     if (E->getNumInits() == 0)
7804       return DerivedZeroInitialization(E);
7805     if (E->getNumInits() == 1)
7806       return StmtVisitorTy::Visit(E->getInit(0));
7807     return Error(E);
7808   }
7809   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7810     return DerivedZeroInitialization(E);
7811   }
7812   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7813     return DerivedZeroInitialization(E);
7814   }
7815   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7816     return DerivedZeroInitialization(E);
7817   }
7818 
7819   /// A member expression where the object is a prvalue is itself a prvalue.
7820   bool VisitMemberExpr(const MemberExpr *E) {
7821     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7822            "missing temporary materialization conversion");
7823     assert(!E->isArrow() && "missing call to bound member function?");
7824 
7825     APValue Val;
7826     if (!Evaluate(Val, Info, E->getBase()))
7827       return false;
7828 
7829     QualType BaseTy = E->getBase()->getType();
7830 
7831     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7832     if (!FD) return Error(E);
7833     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7834     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7835            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7836 
7837     // Note: there is no lvalue base here. But this case should only ever
7838     // happen in C or in C++98, where we cannot be evaluating a constexpr
7839     // constructor, which is the only case the base matters.
7840     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7841     SubobjectDesignator Designator(BaseTy);
7842     Designator.addDeclUnchecked(FD);
7843 
7844     APValue Result;
7845     return extractSubobject(Info, E, Obj, Designator, Result) &&
7846            DerivedSuccess(Result, E);
7847   }
7848 
7849   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7850     APValue Val;
7851     if (!Evaluate(Val, Info, E->getBase()))
7852       return false;
7853 
7854     if (Val.isVector()) {
7855       SmallVector<uint32_t, 4> Indices;
7856       E->getEncodedElementAccess(Indices);
7857       if (Indices.size() == 1) {
7858         // Return scalar.
7859         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7860       } else {
7861         // Construct new APValue vector.
7862         SmallVector<APValue, 4> Elts;
7863         for (unsigned I = 0; I < Indices.size(); ++I) {
7864           Elts.push_back(Val.getVectorElt(Indices[I]));
7865         }
7866         APValue VecResult(Elts.data(), Indices.size());
7867         return DerivedSuccess(VecResult, E);
7868       }
7869     }
7870 
7871     return false;
7872   }
7873 
7874   bool VisitCastExpr(const CastExpr *E) {
7875     switch (E->getCastKind()) {
7876     default:
7877       break;
7878 
7879     case CK_AtomicToNonAtomic: {
7880       APValue AtomicVal;
7881       // This does not need to be done in place even for class/array types:
7882       // atomic-to-non-atomic conversion implies copying the object
7883       // representation.
7884       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7885         return false;
7886       return DerivedSuccess(AtomicVal, E);
7887     }
7888 
7889     case CK_NoOp:
7890     case CK_UserDefinedConversion:
7891       return StmtVisitorTy::Visit(E->getSubExpr());
7892 
7893     case CK_LValueToRValue: {
7894       LValue LVal;
7895       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7896         return false;
7897       APValue RVal;
7898       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7899       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7900                                           LVal, RVal))
7901         return false;
7902       return DerivedSuccess(RVal, E);
7903     }
7904     case CK_LValueToRValueBitCast: {
7905       APValue DestValue, SourceValue;
7906       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7907         return false;
7908       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7909         return false;
7910       return DerivedSuccess(DestValue, E);
7911     }
7912 
7913     case CK_AddressSpaceConversion: {
7914       APValue Value;
7915       if (!Evaluate(Value, Info, E->getSubExpr()))
7916         return false;
7917       return DerivedSuccess(Value, E);
7918     }
7919     }
7920 
7921     return Error(E);
7922   }
7923 
7924   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7925     return VisitUnaryPostIncDec(UO);
7926   }
7927   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7928     return VisitUnaryPostIncDec(UO);
7929   }
7930   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7931     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7932       return Error(UO);
7933 
7934     LValue LVal;
7935     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7936       return false;
7937     APValue RVal;
7938     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7939                       UO->isIncrementOp(), &RVal))
7940       return false;
7941     return DerivedSuccess(RVal, UO);
7942   }
7943 
7944   bool VisitStmtExpr(const StmtExpr *E) {
7945     // We will have checked the full-expressions inside the statement expression
7946     // when they were completed, and don't need to check them again now.
7947     llvm::SaveAndRestore<bool> NotCheckingForUB(
7948         Info.CheckingForUndefinedBehavior, false);
7949 
7950     const CompoundStmt *CS = E->getSubStmt();
7951     if (CS->body_empty())
7952       return true;
7953 
7954     BlockScopeRAII Scope(Info);
7955     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7956                                            BE = CS->body_end();
7957          /**/; ++BI) {
7958       if (BI + 1 == BE) {
7959         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7960         if (!FinalExpr) {
7961           Info.FFDiag((*BI)->getBeginLoc(),
7962                       diag::note_constexpr_stmt_expr_unsupported);
7963           return false;
7964         }
7965         return this->Visit(FinalExpr) && Scope.destroy();
7966       }
7967 
7968       APValue ReturnValue;
7969       StmtResult Result = { ReturnValue, nullptr };
7970       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7971       if (ESR != ESR_Succeeded) {
7972         // FIXME: If the statement-expression terminated due to 'return',
7973         // 'break', or 'continue', it would be nice to propagate that to
7974         // the outer statement evaluation rather than bailing out.
7975         if (ESR != ESR_Failed)
7976           Info.FFDiag((*BI)->getBeginLoc(),
7977                       diag::note_constexpr_stmt_expr_unsupported);
7978         return false;
7979       }
7980     }
7981 
7982     llvm_unreachable("Return from function from the loop above.");
7983   }
7984 
7985   /// Visit a value which is evaluated, but whose value is ignored.
7986   void VisitIgnoredValue(const Expr *E) {
7987     EvaluateIgnoredValue(Info, E);
7988   }
7989 
7990   /// Potentially visit a MemberExpr's base expression.
7991   void VisitIgnoredBaseExpression(const Expr *E) {
7992     // While MSVC doesn't evaluate the base expression, it does diagnose the
7993     // presence of side-effecting behavior.
7994     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7995       return;
7996     VisitIgnoredValue(E);
7997   }
7998 };
7999 
8000 } // namespace
8001 
8002 //===----------------------------------------------------------------------===//
8003 // Common base class for lvalue and temporary evaluation.
8004 //===----------------------------------------------------------------------===//
8005 namespace {
8006 template<class Derived>
8007 class LValueExprEvaluatorBase
8008   : public ExprEvaluatorBase<Derived> {
8009 protected:
8010   LValue &Result;
8011   bool InvalidBaseOK;
8012   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8013   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8014 
8015   bool Success(APValue::LValueBase B) {
8016     Result.set(B);
8017     return true;
8018   }
8019 
8020   bool evaluatePointer(const Expr *E, LValue &Result) {
8021     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8022   }
8023 
8024 public:
8025   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8026       : ExprEvaluatorBaseTy(Info), Result(Result),
8027         InvalidBaseOK(InvalidBaseOK) {}
8028 
8029   bool Success(const APValue &V, const Expr *E) {
8030     Result.setFrom(this->Info.Ctx, V);
8031     return true;
8032   }
8033 
8034   bool VisitMemberExpr(const MemberExpr *E) {
8035     // Handle non-static data members.
8036     QualType BaseTy;
8037     bool EvalOK;
8038     if (E->isArrow()) {
8039       EvalOK = evaluatePointer(E->getBase(), Result);
8040       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8041     } else if (E->getBase()->isPRValue()) {
8042       assert(E->getBase()->getType()->isRecordType());
8043       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8044       BaseTy = E->getBase()->getType();
8045     } else {
8046       EvalOK = this->Visit(E->getBase());
8047       BaseTy = E->getBase()->getType();
8048     }
8049     if (!EvalOK) {
8050       if (!InvalidBaseOK)
8051         return false;
8052       Result.setInvalid(E);
8053       return true;
8054     }
8055 
8056     const ValueDecl *MD = E->getMemberDecl();
8057     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8058       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8059              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8060       (void)BaseTy;
8061       if (!HandleLValueMember(this->Info, E, Result, FD))
8062         return false;
8063     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8064       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8065         return false;
8066     } else
8067       return this->Error(E);
8068 
8069     if (MD->getType()->isReferenceType()) {
8070       APValue RefValue;
8071       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8072                                           RefValue))
8073         return false;
8074       return Success(RefValue, E);
8075     }
8076     return true;
8077   }
8078 
8079   bool VisitBinaryOperator(const BinaryOperator *E) {
8080     switch (E->getOpcode()) {
8081     default:
8082       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8083 
8084     case BO_PtrMemD:
8085     case BO_PtrMemI:
8086       return HandleMemberPointerAccess(this->Info, E, Result);
8087     }
8088   }
8089 
8090   bool VisitCastExpr(const CastExpr *E) {
8091     switch (E->getCastKind()) {
8092     default:
8093       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8094 
8095     case CK_DerivedToBase:
8096     case CK_UncheckedDerivedToBase:
8097       if (!this->Visit(E->getSubExpr()))
8098         return false;
8099 
8100       // Now figure out the necessary offset to add to the base LV to get from
8101       // the derived class to the base class.
8102       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8103                                   Result);
8104     }
8105   }
8106 };
8107 }
8108 
8109 //===----------------------------------------------------------------------===//
8110 // LValue Evaluation
8111 //
8112 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8113 // function designators (in C), decl references to void objects (in C), and
8114 // temporaries (if building with -Wno-address-of-temporary).
8115 //
8116 // LValue evaluation produces values comprising a base expression of one of the
8117 // following types:
8118 // - Declarations
8119 //  * VarDecl
8120 //  * FunctionDecl
8121 // - Literals
8122 //  * CompoundLiteralExpr in C (and in global scope in C++)
8123 //  * StringLiteral
8124 //  * PredefinedExpr
8125 //  * ObjCStringLiteralExpr
8126 //  * ObjCEncodeExpr
8127 //  * AddrLabelExpr
8128 //  * BlockExpr
8129 //  * CallExpr for a MakeStringConstant builtin
8130 // - typeid(T) expressions, as TypeInfoLValues
8131 // - Locals and temporaries
8132 //  * MaterializeTemporaryExpr
8133 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8134 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8135 //    from the AST (FIXME).
8136 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8137 //    CallIndex, for a lifetime-extended temporary.
8138 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8139 //    immediate invocation.
8140 // plus an offset in bytes.
8141 //===----------------------------------------------------------------------===//
8142 namespace {
8143 class LValueExprEvaluator
8144   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8145 public:
8146   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8147     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8148 
8149   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8150   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8151 
8152   bool VisitCallExpr(const CallExpr *E);
8153   bool VisitDeclRefExpr(const DeclRefExpr *E);
8154   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8155   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8156   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8157   bool VisitMemberExpr(const MemberExpr *E);
8158   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8159   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8160   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8161   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8162   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8163   bool VisitUnaryDeref(const UnaryOperator *E);
8164   bool VisitUnaryReal(const UnaryOperator *E);
8165   bool VisitUnaryImag(const UnaryOperator *E);
8166   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8167     return VisitUnaryPreIncDec(UO);
8168   }
8169   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8170     return VisitUnaryPreIncDec(UO);
8171   }
8172   bool VisitBinAssign(const BinaryOperator *BO);
8173   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8174 
8175   bool VisitCastExpr(const CastExpr *E) {
8176     switch (E->getCastKind()) {
8177     default:
8178       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8179 
8180     case CK_LValueBitCast:
8181       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8182       if (!Visit(E->getSubExpr()))
8183         return false;
8184       Result.Designator.setInvalid();
8185       return true;
8186 
8187     case CK_BaseToDerived:
8188       if (!Visit(E->getSubExpr()))
8189         return false;
8190       return HandleBaseToDerivedCast(Info, E, Result);
8191 
8192     case CK_Dynamic:
8193       if (!Visit(E->getSubExpr()))
8194         return false;
8195       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8196     }
8197   }
8198 };
8199 } // end anonymous namespace
8200 
8201 /// Evaluate an expression as an lvalue. This can be legitimately called on
8202 /// expressions which are not glvalues, in three cases:
8203 ///  * function designators in C, and
8204 ///  * "extern void" objects
8205 ///  * @selector() expressions in Objective-C
8206 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8207                            bool InvalidBaseOK) {
8208   assert(!E->isValueDependent());
8209   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8210          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8211   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8212 }
8213 
8214 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8215   const NamedDecl *D = E->getDecl();
8216   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8217           UnnamedGlobalConstantDecl>(D))
8218     return Success(cast<ValueDecl>(D));
8219   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8220     return VisitVarDecl(E, VD);
8221   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8222     return Visit(BD->getBinding());
8223   return Error(E);
8224 }
8225 
8226 
8227 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8228 
8229   // If we are within a lambda's call operator, check whether the 'VD' referred
8230   // to within 'E' actually represents a lambda-capture that maps to a
8231   // data-member/field within the closure object, and if so, evaluate to the
8232   // field or what the field refers to.
8233   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8234       isa<DeclRefExpr>(E) &&
8235       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8236     // We don't always have a complete capture-map when checking or inferring if
8237     // the function call operator meets the requirements of a constexpr function
8238     // - but we don't need to evaluate the captures to determine constexprness
8239     // (dcl.constexpr C++17).
8240     if (Info.checkingPotentialConstantExpression())
8241       return false;
8242 
8243     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8244       // Start with 'Result' referring to the complete closure object...
8245       Result = *Info.CurrentCall->This;
8246       // ... then update it to refer to the field of the closure object
8247       // that represents the capture.
8248       if (!HandleLValueMember(Info, E, Result, FD))
8249         return false;
8250       // And if the field is of reference type, update 'Result' to refer to what
8251       // the field refers to.
8252       if (FD->getType()->isReferenceType()) {
8253         APValue RVal;
8254         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8255                                             RVal))
8256           return false;
8257         Result.setFrom(Info.Ctx, RVal);
8258       }
8259       return true;
8260     }
8261   }
8262 
8263   CallStackFrame *Frame = nullptr;
8264   unsigned Version = 0;
8265   if (VD->hasLocalStorage()) {
8266     // Only if a local variable was declared in the function currently being
8267     // evaluated, do we expect to be able to find its value in the current
8268     // frame. (Otherwise it was likely declared in an enclosing context and
8269     // could either have a valid evaluatable value (for e.g. a constexpr
8270     // variable) or be ill-formed (and trigger an appropriate evaluation
8271     // diagnostic)).
8272     CallStackFrame *CurrFrame = Info.CurrentCall;
8273     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8274       // Function parameters are stored in some caller's frame. (Usually the
8275       // immediate caller, but for an inherited constructor they may be more
8276       // distant.)
8277       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8278         if (CurrFrame->Arguments) {
8279           VD = CurrFrame->Arguments.getOrigParam(PVD);
8280           Frame =
8281               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8282           Version = CurrFrame->Arguments.Version;
8283         }
8284       } else {
8285         Frame = CurrFrame;
8286         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8287       }
8288     }
8289   }
8290 
8291   if (!VD->getType()->isReferenceType()) {
8292     if (Frame) {
8293       Result.set({VD, Frame->Index, Version});
8294       return true;
8295     }
8296     return Success(VD);
8297   }
8298 
8299   if (!Info.getLangOpts().CPlusPlus11) {
8300     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8301         << VD << VD->getType();
8302     Info.Note(VD->getLocation(), diag::note_declared_at);
8303   }
8304 
8305   APValue *V;
8306   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8307     return false;
8308   if (!V->hasValue()) {
8309     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8310     // adjust the diagnostic to say that.
8311     if (!Info.checkingPotentialConstantExpression())
8312       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8313     return false;
8314   }
8315   return Success(*V, E);
8316 }
8317 
8318 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8319   switch (E->getBuiltinCallee()) {
8320   case Builtin::BIas_const:
8321   case Builtin::BIforward:
8322   case Builtin::BImove:
8323   case Builtin::BImove_if_noexcept:
8324     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8325       return Visit(E->getArg(0));
8326     break;
8327   }
8328 
8329   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8330 }
8331 
8332 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8333     const MaterializeTemporaryExpr *E) {
8334   // Walk through the expression to find the materialized temporary itself.
8335   SmallVector<const Expr *, 2> CommaLHSs;
8336   SmallVector<SubobjectAdjustment, 2> Adjustments;
8337   const Expr *Inner =
8338       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8339 
8340   // If we passed any comma operators, evaluate their LHSs.
8341   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8342     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8343       return false;
8344 
8345   // A materialized temporary with static storage duration can appear within the
8346   // result of a constant expression evaluation, so we need to preserve its
8347   // value for use outside this evaluation.
8348   APValue *Value;
8349   if (E->getStorageDuration() == SD_Static) {
8350     // FIXME: What about SD_Thread?
8351     Value = E->getOrCreateValue(true);
8352     *Value = APValue();
8353     Result.set(E);
8354   } else {
8355     Value = &Info.CurrentCall->createTemporary(
8356         E, E->getType(),
8357         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8358                                                      : ScopeKind::Block,
8359         Result);
8360   }
8361 
8362   QualType Type = Inner->getType();
8363 
8364   // Materialize the temporary itself.
8365   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8366     *Value = APValue();
8367     return false;
8368   }
8369 
8370   // Adjust our lvalue to refer to the desired subobject.
8371   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8372     --I;
8373     switch (Adjustments[I].Kind) {
8374     case SubobjectAdjustment::DerivedToBaseAdjustment:
8375       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8376                                 Type, Result))
8377         return false;
8378       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8379       break;
8380 
8381     case SubobjectAdjustment::FieldAdjustment:
8382       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8383         return false;
8384       Type = Adjustments[I].Field->getType();
8385       break;
8386 
8387     case SubobjectAdjustment::MemberPointerAdjustment:
8388       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8389                                      Adjustments[I].Ptr.RHS))
8390         return false;
8391       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8392       break;
8393     }
8394   }
8395 
8396   return true;
8397 }
8398 
8399 bool
8400 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8401   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8402          "lvalue compound literal in c++?");
8403   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8404   // only see this when folding in C, so there's no standard to follow here.
8405   return Success(E);
8406 }
8407 
8408 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8409   TypeInfoLValue TypeInfo;
8410 
8411   if (!E->isPotentiallyEvaluated()) {
8412     if (E->isTypeOperand())
8413       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8414     else
8415       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8416   } else {
8417     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8418       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8419         << E->getExprOperand()->getType()
8420         << E->getExprOperand()->getSourceRange();
8421     }
8422 
8423     if (!Visit(E->getExprOperand()))
8424       return false;
8425 
8426     Optional<DynamicType> DynType =
8427         ComputeDynamicType(Info, E, Result, AK_TypeId);
8428     if (!DynType)
8429       return false;
8430 
8431     TypeInfo =
8432         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8433   }
8434 
8435   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8436 }
8437 
8438 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8439   return Success(E->getGuidDecl());
8440 }
8441 
8442 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8443   // Handle static data members.
8444   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8445     VisitIgnoredBaseExpression(E->getBase());
8446     return VisitVarDecl(E, VD);
8447   }
8448 
8449   // Handle static member functions.
8450   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8451     if (MD->isStatic()) {
8452       VisitIgnoredBaseExpression(E->getBase());
8453       return Success(MD);
8454     }
8455   }
8456 
8457   // Handle non-static data members.
8458   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8459 }
8460 
8461 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8462   // FIXME: Deal with vectors as array subscript bases.
8463   if (E->getBase()->getType()->isVectorType() ||
8464       E->getBase()->getType()->isVLSTBuiltinType())
8465     return Error(E);
8466 
8467   APSInt Index;
8468   bool Success = true;
8469 
8470   // C++17's rules require us to evaluate the LHS first, regardless of which
8471   // side is the base.
8472   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8473     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8474                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8475       if (!Info.noteFailure())
8476         return false;
8477       Success = false;
8478     }
8479   }
8480 
8481   return Success &&
8482          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8483 }
8484 
8485 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8486   return evaluatePointer(E->getSubExpr(), Result);
8487 }
8488 
8489 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8490   if (!Visit(E->getSubExpr()))
8491     return false;
8492   // __real is a no-op on scalar lvalues.
8493   if (E->getSubExpr()->getType()->isAnyComplexType())
8494     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8495   return true;
8496 }
8497 
8498 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8499   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8500          "lvalue __imag__ on scalar?");
8501   if (!Visit(E->getSubExpr()))
8502     return false;
8503   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8504   return true;
8505 }
8506 
8507 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8508   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8509     return Error(UO);
8510 
8511   if (!this->Visit(UO->getSubExpr()))
8512     return false;
8513 
8514   return handleIncDec(
8515       this->Info, UO, Result, UO->getSubExpr()->getType(),
8516       UO->isIncrementOp(), nullptr);
8517 }
8518 
8519 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8520     const CompoundAssignOperator *CAO) {
8521   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8522     return Error(CAO);
8523 
8524   bool Success = true;
8525 
8526   // C++17 onwards require that we evaluate the RHS first.
8527   APValue RHS;
8528   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8529     if (!Info.noteFailure())
8530       return false;
8531     Success = false;
8532   }
8533 
8534   // The overall lvalue result is the result of evaluating the LHS.
8535   if (!this->Visit(CAO->getLHS()) || !Success)
8536     return false;
8537 
8538   return handleCompoundAssignment(
8539       this->Info, CAO,
8540       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8541       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8542 }
8543 
8544 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8545   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8546     return Error(E);
8547 
8548   bool Success = true;
8549 
8550   // C++17 onwards require that we evaluate the RHS first.
8551   APValue NewVal;
8552   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8553     if (!Info.noteFailure())
8554       return false;
8555     Success = false;
8556   }
8557 
8558   if (!this->Visit(E->getLHS()) || !Success)
8559     return false;
8560 
8561   if (Info.getLangOpts().CPlusPlus20 &&
8562       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8563     return false;
8564 
8565   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8566                           NewVal);
8567 }
8568 
8569 //===----------------------------------------------------------------------===//
8570 // Pointer Evaluation
8571 //===----------------------------------------------------------------------===//
8572 
8573 /// Attempts to compute the number of bytes available at the pointer
8574 /// returned by a function with the alloc_size attribute. Returns true if we
8575 /// were successful. Places an unsigned number into `Result`.
8576 ///
8577 /// This expects the given CallExpr to be a call to a function with an
8578 /// alloc_size attribute.
8579 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8580                                             const CallExpr *Call,
8581                                             llvm::APInt &Result) {
8582   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8583 
8584   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8585   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8586   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8587   if (Call->getNumArgs() <= SizeArgNo)
8588     return false;
8589 
8590   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8591     Expr::EvalResult ExprResult;
8592     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8593       return false;
8594     Into = ExprResult.Val.getInt();
8595     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8596       return false;
8597     Into = Into.zext(BitsInSizeT);
8598     return true;
8599   };
8600 
8601   APSInt SizeOfElem;
8602   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8603     return false;
8604 
8605   if (!AllocSize->getNumElemsParam().isValid()) {
8606     Result = std::move(SizeOfElem);
8607     return true;
8608   }
8609 
8610   APSInt NumberOfElems;
8611   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8612   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8613     return false;
8614 
8615   bool Overflow;
8616   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8617   if (Overflow)
8618     return false;
8619 
8620   Result = std::move(BytesAvailable);
8621   return true;
8622 }
8623 
8624 /// Convenience function. LVal's base must be a call to an alloc_size
8625 /// function.
8626 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8627                                             const LValue &LVal,
8628                                             llvm::APInt &Result) {
8629   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8630          "Can't get the size of a non alloc_size function");
8631   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8632   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8633   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8634 }
8635 
8636 /// Attempts to evaluate the given LValueBase as the result of a call to
8637 /// a function with the alloc_size attribute. If it was possible to do so, this
8638 /// function will return true, make Result's Base point to said function call,
8639 /// and mark Result's Base as invalid.
8640 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8641                                       LValue &Result) {
8642   if (Base.isNull())
8643     return false;
8644 
8645   // Because we do no form of static analysis, we only support const variables.
8646   //
8647   // Additionally, we can't support parameters, nor can we support static
8648   // variables (in the latter case, use-before-assign isn't UB; in the former,
8649   // we have no clue what they'll be assigned to).
8650   const auto *VD =
8651       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8652   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8653     return false;
8654 
8655   const Expr *Init = VD->getAnyInitializer();
8656   if (!Init || Init->getType().isNull())
8657     return false;
8658 
8659   const Expr *E = Init->IgnoreParens();
8660   if (!tryUnwrapAllocSizeCall(E))
8661     return false;
8662 
8663   // Store E instead of E unwrapped so that the type of the LValue's base is
8664   // what the user wanted.
8665   Result.setInvalid(E);
8666 
8667   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8668   Result.addUnsizedArray(Info, E, Pointee);
8669   return true;
8670 }
8671 
8672 namespace {
8673 class PointerExprEvaluator
8674   : public ExprEvaluatorBase<PointerExprEvaluator> {
8675   LValue &Result;
8676   bool InvalidBaseOK;
8677 
8678   bool Success(const Expr *E) {
8679     Result.set(E);
8680     return true;
8681   }
8682 
8683   bool evaluateLValue(const Expr *E, LValue &Result) {
8684     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8685   }
8686 
8687   bool evaluatePointer(const Expr *E, LValue &Result) {
8688     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8689   }
8690 
8691   bool visitNonBuiltinCallExpr(const CallExpr *E);
8692 public:
8693 
8694   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8695       : ExprEvaluatorBaseTy(info), Result(Result),
8696         InvalidBaseOK(InvalidBaseOK) {}
8697 
8698   bool Success(const APValue &V, const Expr *E) {
8699     Result.setFrom(Info.Ctx, V);
8700     return true;
8701   }
8702   bool ZeroInitialization(const Expr *E) {
8703     Result.setNull(Info.Ctx, E->getType());
8704     return true;
8705   }
8706 
8707   bool VisitBinaryOperator(const BinaryOperator *E);
8708   bool VisitCastExpr(const CastExpr* E);
8709   bool VisitUnaryAddrOf(const UnaryOperator *E);
8710   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8711       { return Success(E); }
8712   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8713     if (E->isExpressibleAsConstantInitializer())
8714       return Success(E);
8715     if (Info.noteFailure())
8716       EvaluateIgnoredValue(Info, E->getSubExpr());
8717     return Error(E);
8718   }
8719   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8720       { return Success(E); }
8721   bool VisitCallExpr(const CallExpr *E);
8722   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8723   bool VisitBlockExpr(const BlockExpr *E) {
8724     if (!E->getBlockDecl()->hasCaptures())
8725       return Success(E);
8726     return Error(E);
8727   }
8728   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8729     // Can't look at 'this' when checking a potential constant expression.
8730     if (Info.checkingPotentialConstantExpression())
8731       return false;
8732     if (!Info.CurrentCall->This) {
8733       if (Info.getLangOpts().CPlusPlus11)
8734         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8735       else
8736         Info.FFDiag(E);
8737       return false;
8738     }
8739     Result = *Info.CurrentCall->This;
8740     // If we are inside a lambda's call operator, the 'this' expression refers
8741     // to the enclosing '*this' object (either by value or reference) which is
8742     // either copied into the closure object's field that represents the '*this'
8743     // or refers to '*this'.
8744     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8745       // Ensure we actually have captured 'this'. (an error will have
8746       // been previously reported if not).
8747       if (!Info.CurrentCall->LambdaThisCaptureField)
8748         return false;
8749 
8750       // Update 'Result' to refer to the data member/field of the closure object
8751       // that represents the '*this' capture.
8752       if (!HandleLValueMember(Info, E, Result,
8753                              Info.CurrentCall->LambdaThisCaptureField))
8754         return false;
8755       // If we captured '*this' by reference, replace the field with its referent.
8756       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8757               ->isPointerType()) {
8758         APValue RVal;
8759         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8760                                             RVal))
8761           return false;
8762 
8763         Result.setFrom(Info.Ctx, RVal);
8764       }
8765     }
8766     return true;
8767   }
8768 
8769   bool VisitCXXNewExpr(const CXXNewExpr *E);
8770 
8771   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8772     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8773     APValue LValResult = E->EvaluateInContext(
8774         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8775     Result.setFrom(Info.Ctx, LValResult);
8776     return true;
8777   }
8778 
8779   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8780     std::string ResultStr = E->ComputeName(Info.Ctx);
8781 
8782     QualType CharTy = Info.Ctx.CharTy.withConst();
8783     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8784                ResultStr.size() + 1);
8785     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8786                                                      ArrayType::Normal, 0);
8787 
8788     StringLiteral *SL =
8789         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8790                               /*Pascal*/ false, ArrayTy, E->getLocation());
8791 
8792     evaluateLValue(SL, Result);
8793     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8794     return true;
8795   }
8796 
8797   // FIXME: Missing: @protocol, @selector
8798 };
8799 } // end anonymous namespace
8800 
8801 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8802                             bool InvalidBaseOK) {
8803   assert(!E->isValueDependent());
8804   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8805   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8806 }
8807 
8808 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8809   if (E->getOpcode() != BO_Add &&
8810       E->getOpcode() != BO_Sub)
8811     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8812 
8813   const Expr *PExp = E->getLHS();
8814   const Expr *IExp = E->getRHS();
8815   if (IExp->getType()->isPointerType())
8816     std::swap(PExp, IExp);
8817 
8818   bool EvalPtrOK = evaluatePointer(PExp, Result);
8819   if (!EvalPtrOK && !Info.noteFailure())
8820     return false;
8821 
8822   llvm::APSInt Offset;
8823   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8824     return false;
8825 
8826   if (E->getOpcode() == BO_Sub)
8827     negateAsSigned(Offset);
8828 
8829   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8830   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8831 }
8832 
8833 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8834   return evaluateLValue(E->getSubExpr(), Result);
8835 }
8836 
8837 // Is the provided decl 'std::source_location::current'?
8838 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8839   if (!FD)
8840     return false;
8841   const IdentifierInfo *FnII = FD->getIdentifier();
8842   if (!FnII || !FnII->isStr("current"))
8843     return false;
8844 
8845   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8846   if (!RD)
8847     return false;
8848 
8849   const IdentifierInfo *ClassII = RD->getIdentifier();
8850   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8851 }
8852 
8853 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8854   const Expr *SubExpr = E->getSubExpr();
8855 
8856   switch (E->getCastKind()) {
8857   default:
8858     break;
8859   case CK_BitCast:
8860   case CK_CPointerToObjCPointerCast:
8861   case CK_BlockPointerToObjCPointerCast:
8862   case CK_AnyPointerToBlockPointerCast:
8863   case CK_AddressSpaceConversion:
8864     if (!Visit(SubExpr))
8865       return false;
8866     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8867     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8868     // also static_casts, but we disallow them as a resolution to DR1312.
8869     if (!E->getType()->isVoidPointerType()) {
8870       // In some circumstances, we permit casting from void* to cv1 T*, when the
8871       // actual pointee object is actually a cv2 T.
8872       bool VoidPtrCastMaybeOK =
8873           !Result.InvalidBase && !Result.Designator.Invalid &&
8874           !Result.IsNullPtr &&
8875           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8876                                           E->getType()->getPointeeType());
8877       // 1. We'll allow it in std::allocator::allocate, and anything which that
8878       //    calls.
8879       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8880       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8881       //    We'll allow it in the body of std::source_location::current.  GCC's
8882       //    implementation had a parameter of type `void*`, and casts from
8883       //    that back to `const __impl*` in its body.
8884       if (VoidPtrCastMaybeOK &&
8885           (Info.getStdAllocatorCaller("allocate") ||
8886            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8887         // Permitted.
8888       } else {
8889         Result.Designator.setInvalid();
8890         if (SubExpr->getType()->isVoidPointerType())
8891           CCEDiag(E, diag::note_constexpr_invalid_cast)
8892             << 3 << SubExpr->getType();
8893         else
8894           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8895       }
8896     }
8897     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8898       ZeroInitialization(E);
8899     return true;
8900 
8901   case CK_DerivedToBase:
8902   case CK_UncheckedDerivedToBase:
8903     if (!evaluatePointer(E->getSubExpr(), Result))
8904       return false;
8905     if (!Result.Base && Result.Offset.isZero())
8906       return true;
8907 
8908     // Now figure out the necessary offset to add to the base LV to get from
8909     // the derived class to the base class.
8910     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8911                                   castAs<PointerType>()->getPointeeType(),
8912                                 Result);
8913 
8914   case CK_BaseToDerived:
8915     if (!Visit(E->getSubExpr()))
8916       return false;
8917     if (!Result.Base && Result.Offset.isZero())
8918       return true;
8919     return HandleBaseToDerivedCast(Info, E, Result);
8920 
8921   case CK_Dynamic:
8922     if (!Visit(E->getSubExpr()))
8923       return false;
8924     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8925 
8926   case CK_NullToPointer:
8927     VisitIgnoredValue(E->getSubExpr());
8928     return ZeroInitialization(E);
8929 
8930   case CK_IntegralToPointer: {
8931     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8932 
8933     APValue Value;
8934     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8935       break;
8936 
8937     if (Value.isInt()) {
8938       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8939       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8940       Result.Base = (Expr*)nullptr;
8941       Result.InvalidBase = false;
8942       Result.Offset = CharUnits::fromQuantity(N);
8943       Result.Designator.setInvalid();
8944       Result.IsNullPtr = false;
8945       return true;
8946     } else {
8947       // Cast is of an lvalue, no need to change value.
8948       Result.setFrom(Info.Ctx, Value);
8949       return true;
8950     }
8951   }
8952 
8953   case CK_ArrayToPointerDecay: {
8954     if (SubExpr->isGLValue()) {
8955       if (!evaluateLValue(SubExpr, Result))
8956         return false;
8957     } else {
8958       APValue &Value = Info.CurrentCall->createTemporary(
8959           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8960       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8961         return false;
8962     }
8963     // The result is a pointer to the first element of the array.
8964     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8965     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8966       Result.addArray(Info, E, CAT);
8967     else
8968       Result.addUnsizedArray(Info, E, AT->getElementType());
8969     return true;
8970   }
8971 
8972   case CK_FunctionToPointerDecay:
8973     return evaluateLValue(SubExpr, Result);
8974 
8975   case CK_LValueToRValue: {
8976     LValue LVal;
8977     if (!evaluateLValue(E->getSubExpr(), LVal))
8978       return false;
8979 
8980     APValue RVal;
8981     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8982     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8983                                         LVal, RVal))
8984       return InvalidBaseOK &&
8985              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8986     return Success(RVal, E);
8987   }
8988   }
8989 
8990   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8991 }
8992 
8993 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8994                                 UnaryExprOrTypeTrait ExprKind) {
8995   // C++ [expr.alignof]p3:
8996   //     When alignof is applied to a reference type, the result is the
8997   //     alignment of the referenced type.
8998   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8999     T = Ref->getPointeeType();
9000 
9001   if (T.getQualifiers().hasUnaligned())
9002     return CharUnits::One();
9003 
9004   const bool AlignOfReturnsPreferred =
9005       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9006 
9007   // __alignof is defined to return the preferred alignment.
9008   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9009   // as well.
9010   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9011     return Info.Ctx.toCharUnitsFromBits(
9012       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9013   // alignof and _Alignof are defined to return the ABI alignment.
9014   else if (ExprKind == UETT_AlignOf)
9015     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9016   else
9017     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9018 }
9019 
9020 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9021                                 UnaryExprOrTypeTrait ExprKind) {
9022   E = E->IgnoreParens();
9023 
9024   // The kinds of expressions that we have special-case logic here for
9025   // should be kept up to date with the special checks for those
9026   // expressions in Sema.
9027 
9028   // alignof decl is always accepted, even if it doesn't make sense: we default
9029   // to 1 in those cases.
9030   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9031     return Info.Ctx.getDeclAlign(DRE->getDecl(),
9032                                  /*RefAsPointee*/true);
9033 
9034   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9035     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9036                                  /*RefAsPointee*/true);
9037 
9038   return GetAlignOfType(Info, E->getType(), ExprKind);
9039 }
9040 
9041 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9042   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9043     return Info.Ctx.getDeclAlign(VD);
9044   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9045     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9046   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9047 }
9048 
9049 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9050 /// __builtin_is_aligned and __builtin_assume_aligned.
9051 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9052                                  EvalInfo &Info, APSInt &Alignment) {
9053   if (!EvaluateInteger(E, Alignment, Info))
9054     return false;
9055   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9056     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9057     return false;
9058   }
9059   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9060   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9061   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9062     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9063         << MaxValue << ForType << Alignment;
9064     return false;
9065   }
9066   // Ensure both alignment and source value have the same bit width so that we
9067   // don't assert when computing the resulting value.
9068   APSInt ExtAlignment =
9069       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9070   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9071          "Alignment should not be changed by ext/trunc");
9072   Alignment = ExtAlignment;
9073   assert(Alignment.getBitWidth() == SrcWidth);
9074   return true;
9075 }
9076 
9077 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9078 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9079   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9080     return true;
9081 
9082   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9083     return false;
9084 
9085   Result.setInvalid(E);
9086   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9087   Result.addUnsizedArray(Info, E, PointeeTy);
9088   return true;
9089 }
9090 
9091 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9092   if (IsConstantCall(E))
9093     return Success(E);
9094 
9095   if (unsigned BuiltinOp = E->getBuiltinCallee())
9096     return VisitBuiltinCallExpr(E, BuiltinOp);
9097 
9098   return visitNonBuiltinCallExpr(E);
9099 }
9100 
9101 // Determine if T is a character type for which we guarantee that
9102 // sizeof(T) == 1.
9103 static bool isOneByteCharacterType(QualType T) {
9104   return T->isCharType() || T->isChar8Type();
9105 }
9106 
9107 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9108                                                 unsigned BuiltinOp) {
9109   switch (BuiltinOp) {
9110   case Builtin::BIaddressof:
9111   case Builtin::BI__addressof:
9112   case Builtin::BI__builtin_addressof:
9113     return evaluateLValue(E->getArg(0), Result);
9114   case Builtin::BI__builtin_assume_aligned: {
9115     // We need to be very careful here because: if the pointer does not have the
9116     // asserted alignment, then the behavior is undefined, and undefined
9117     // behavior is non-constant.
9118     if (!evaluatePointer(E->getArg(0), Result))
9119       return false;
9120 
9121     LValue OffsetResult(Result);
9122     APSInt Alignment;
9123     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9124                               Alignment))
9125       return false;
9126     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9127 
9128     if (E->getNumArgs() > 2) {
9129       APSInt Offset;
9130       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9131         return false;
9132 
9133       int64_t AdditionalOffset = -Offset.getZExtValue();
9134       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9135     }
9136 
9137     // If there is a base object, then it must have the correct alignment.
9138     if (OffsetResult.Base) {
9139       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9140 
9141       if (BaseAlignment < Align) {
9142         Result.Designator.setInvalid();
9143         // FIXME: Add support to Diagnostic for long / long long.
9144         CCEDiag(E->getArg(0),
9145                 diag::note_constexpr_baa_insufficient_alignment) << 0
9146           << (unsigned)BaseAlignment.getQuantity()
9147           << (unsigned)Align.getQuantity();
9148         return false;
9149       }
9150     }
9151 
9152     // The offset must also have the correct alignment.
9153     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9154       Result.Designator.setInvalid();
9155 
9156       (OffsetResult.Base
9157            ? CCEDiag(E->getArg(0),
9158                      diag::note_constexpr_baa_insufficient_alignment) << 1
9159            : CCEDiag(E->getArg(0),
9160                      diag::note_constexpr_baa_value_insufficient_alignment))
9161         << (int)OffsetResult.Offset.getQuantity()
9162         << (unsigned)Align.getQuantity();
9163       return false;
9164     }
9165 
9166     return true;
9167   }
9168   case Builtin::BI__builtin_align_up:
9169   case Builtin::BI__builtin_align_down: {
9170     if (!evaluatePointer(E->getArg(0), Result))
9171       return false;
9172     APSInt Alignment;
9173     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9174                               Alignment))
9175       return false;
9176     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9177     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9178     // For align_up/align_down, we can return the same value if the alignment
9179     // is known to be greater or equal to the requested value.
9180     if (PtrAlign.getQuantity() >= Alignment)
9181       return true;
9182 
9183     // The alignment could be greater than the minimum at run-time, so we cannot
9184     // infer much about the resulting pointer value. One case is possible:
9185     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9186     // can infer the correct index if the requested alignment is smaller than
9187     // the base alignment so we can perform the computation on the offset.
9188     if (BaseAlignment.getQuantity() >= Alignment) {
9189       assert(Alignment.getBitWidth() <= 64 &&
9190              "Cannot handle > 64-bit address-space");
9191       uint64_t Alignment64 = Alignment.getZExtValue();
9192       CharUnits NewOffset = CharUnits::fromQuantity(
9193           BuiltinOp == Builtin::BI__builtin_align_down
9194               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9195               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9196       Result.adjustOffset(NewOffset - Result.Offset);
9197       // TODO: diagnose out-of-bounds values/only allow for arrays?
9198       return true;
9199     }
9200     // Otherwise, we cannot constant-evaluate the result.
9201     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9202         << Alignment;
9203     return false;
9204   }
9205   case Builtin::BI__builtin_operator_new:
9206     return HandleOperatorNewCall(Info, E, Result);
9207   case Builtin::BI__builtin_launder:
9208     return evaluatePointer(E->getArg(0), Result);
9209   case Builtin::BIstrchr:
9210   case Builtin::BIwcschr:
9211   case Builtin::BImemchr:
9212   case Builtin::BIwmemchr:
9213     if (Info.getLangOpts().CPlusPlus11)
9214       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9215         << /*isConstexpr*/0 << /*isConstructor*/0
9216         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9217     else
9218       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9219     LLVM_FALLTHROUGH;
9220   case Builtin::BI__builtin_strchr:
9221   case Builtin::BI__builtin_wcschr:
9222   case Builtin::BI__builtin_memchr:
9223   case Builtin::BI__builtin_char_memchr:
9224   case Builtin::BI__builtin_wmemchr: {
9225     if (!Visit(E->getArg(0)))
9226       return false;
9227     APSInt Desired;
9228     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9229       return false;
9230     uint64_t MaxLength = uint64_t(-1);
9231     if (BuiltinOp != Builtin::BIstrchr &&
9232         BuiltinOp != Builtin::BIwcschr &&
9233         BuiltinOp != Builtin::BI__builtin_strchr &&
9234         BuiltinOp != Builtin::BI__builtin_wcschr) {
9235       APSInt N;
9236       if (!EvaluateInteger(E->getArg(2), N, Info))
9237         return false;
9238       MaxLength = N.getExtValue();
9239     }
9240     // We cannot find the value if there are no candidates to match against.
9241     if (MaxLength == 0u)
9242       return ZeroInitialization(E);
9243     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9244         Result.Designator.Invalid)
9245       return false;
9246     QualType CharTy = Result.Designator.getType(Info.Ctx);
9247     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9248                      BuiltinOp == Builtin::BI__builtin_memchr;
9249     assert(IsRawByte ||
9250            Info.Ctx.hasSameUnqualifiedType(
9251                CharTy, E->getArg(0)->getType()->getPointeeType()));
9252     // Pointers to const void may point to objects of incomplete type.
9253     if (IsRawByte && CharTy->isIncompleteType()) {
9254       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9255       return false;
9256     }
9257     // Give up on byte-oriented matching against multibyte elements.
9258     // FIXME: We can compare the bytes in the correct order.
9259     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9260       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9261           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9262           << CharTy;
9263       return false;
9264     }
9265     // Figure out what value we're actually looking for (after converting to
9266     // the corresponding unsigned type if necessary).
9267     uint64_t DesiredVal;
9268     bool StopAtNull = false;
9269     switch (BuiltinOp) {
9270     case Builtin::BIstrchr:
9271     case Builtin::BI__builtin_strchr:
9272       // strchr compares directly to the passed integer, and therefore
9273       // always fails if given an int that is not a char.
9274       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9275                                                   E->getArg(1)->getType(),
9276                                                   Desired),
9277                                Desired))
9278         return ZeroInitialization(E);
9279       StopAtNull = true;
9280       LLVM_FALLTHROUGH;
9281     case Builtin::BImemchr:
9282     case Builtin::BI__builtin_memchr:
9283     case Builtin::BI__builtin_char_memchr:
9284       // memchr compares by converting both sides to unsigned char. That's also
9285       // correct for strchr if we get this far (to cope with plain char being
9286       // unsigned in the strchr case).
9287       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9288       break;
9289 
9290     case Builtin::BIwcschr:
9291     case Builtin::BI__builtin_wcschr:
9292       StopAtNull = true;
9293       LLVM_FALLTHROUGH;
9294     case Builtin::BIwmemchr:
9295     case Builtin::BI__builtin_wmemchr:
9296       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9297       DesiredVal = Desired.getZExtValue();
9298       break;
9299     }
9300 
9301     for (; MaxLength; --MaxLength) {
9302       APValue Char;
9303       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9304           !Char.isInt())
9305         return false;
9306       if (Char.getInt().getZExtValue() == DesiredVal)
9307         return true;
9308       if (StopAtNull && !Char.getInt())
9309         break;
9310       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9311         return false;
9312     }
9313     // Not found: return nullptr.
9314     return ZeroInitialization(E);
9315   }
9316 
9317   case Builtin::BImemcpy:
9318   case Builtin::BImemmove:
9319   case Builtin::BIwmemcpy:
9320   case Builtin::BIwmemmove:
9321     if (Info.getLangOpts().CPlusPlus11)
9322       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9323         << /*isConstexpr*/0 << /*isConstructor*/0
9324         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9325     else
9326       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9327     LLVM_FALLTHROUGH;
9328   case Builtin::BI__builtin_memcpy:
9329   case Builtin::BI__builtin_memmove:
9330   case Builtin::BI__builtin_wmemcpy:
9331   case Builtin::BI__builtin_wmemmove: {
9332     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9333                  BuiltinOp == Builtin::BIwmemmove ||
9334                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9335                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9336     bool Move = BuiltinOp == Builtin::BImemmove ||
9337                 BuiltinOp == Builtin::BIwmemmove ||
9338                 BuiltinOp == Builtin::BI__builtin_memmove ||
9339                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9340 
9341     // The result of mem* is the first argument.
9342     if (!Visit(E->getArg(0)))
9343       return false;
9344     LValue Dest = Result;
9345 
9346     LValue Src;
9347     if (!EvaluatePointer(E->getArg(1), Src, Info))
9348       return false;
9349 
9350     APSInt N;
9351     if (!EvaluateInteger(E->getArg(2), N, Info))
9352       return false;
9353     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9354 
9355     // If the size is zero, we treat this as always being a valid no-op.
9356     // (Even if one of the src and dest pointers is null.)
9357     if (!N)
9358       return true;
9359 
9360     // Otherwise, if either of the operands is null, we can't proceed. Don't
9361     // try to determine the type of the copied objects, because there aren't
9362     // any.
9363     if (!Src.Base || !Dest.Base) {
9364       APValue Val;
9365       (!Src.Base ? Src : Dest).moveInto(Val);
9366       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9367           << Move << WChar << !!Src.Base
9368           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9369       return false;
9370     }
9371     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9372       return false;
9373 
9374     // We require that Src and Dest are both pointers to arrays of
9375     // trivially-copyable type. (For the wide version, the designator will be
9376     // invalid if the designated object is not a wchar_t.)
9377     QualType T = Dest.Designator.getType(Info.Ctx);
9378     QualType SrcT = Src.Designator.getType(Info.Ctx);
9379     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9380       // FIXME: Consider using our bit_cast implementation to support this.
9381       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9382       return false;
9383     }
9384     if (T->isIncompleteType()) {
9385       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9386       return false;
9387     }
9388     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9389       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9390       return false;
9391     }
9392 
9393     // Figure out how many T's we're copying.
9394     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9395     if (!WChar) {
9396       uint64_t Remainder;
9397       llvm::APInt OrigN = N;
9398       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9399       if (Remainder) {
9400         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9401             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9402             << (unsigned)TSize;
9403         return false;
9404       }
9405     }
9406 
9407     // Check that the copying will remain within the arrays, just so that we
9408     // can give a more meaningful diagnostic. This implicitly also checks that
9409     // N fits into 64 bits.
9410     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9411     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9412     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9413       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9414           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9415           << toString(N, 10, /*Signed*/false);
9416       return false;
9417     }
9418     uint64_t NElems = N.getZExtValue();
9419     uint64_t NBytes = NElems * TSize;
9420 
9421     // Check for overlap.
9422     int Direction = 1;
9423     if (HasSameBase(Src, Dest)) {
9424       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9425       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9426       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9427         // Dest is inside the source region.
9428         if (!Move) {
9429           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9430           return false;
9431         }
9432         // For memmove and friends, copy backwards.
9433         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9434             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9435           return false;
9436         Direction = -1;
9437       } else if (!Move && SrcOffset >= DestOffset &&
9438                  SrcOffset - DestOffset < NBytes) {
9439         // Src is inside the destination region for memcpy: invalid.
9440         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9441         return false;
9442       }
9443     }
9444 
9445     while (true) {
9446       APValue Val;
9447       // FIXME: Set WantObjectRepresentation to true if we're copying a
9448       // char-like type?
9449       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9450           !handleAssignment(Info, E, Dest, T, Val))
9451         return false;
9452       // Do not iterate past the last element; if we're copying backwards, that
9453       // might take us off the start of the array.
9454       if (--NElems == 0)
9455         return true;
9456       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9457           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9458         return false;
9459     }
9460   }
9461 
9462   default:
9463     break;
9464   }
9465 
9466   return visitNonBuiltinCallExpr(E);
9467 }
9468 
9469 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9470                                      APValue &Result, const InitListExpr *ILE,
9471                                      QualType AllocType);
9472 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9473                                           APValue &Result,
9474                                           const CXXConstructExpr *CCE,
9475                                           QualType AllocType);
9476 
9477 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9478   if (!Info.getLangOpts().CPlusPlus20)
9479     Info.CCEDiag(E, diag::note_constexpr_new);
9480 
9481   // We cannot speculatively evaluate a delete expression.
9482   if (Info.SpeculativeEvaluationDepth)
9483     return false;
9484 
9485   FunctionDecl *OperatorNew = E->getOperatorNew();
9486 
9487   bool IsNothrow = false;
9488   bool IsPlacement = false;
9489   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9490       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9491     // FIXME Support array placement new.
9492     assert(E->getNumPlacementArgs() == 1);
9493     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9494       return false;
9495     if (Result.Designator.Invalid)
9496       return false;
9497     IsPlacement = true;
9498   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9499     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9500         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9501     return false;
9502   } else if (E->getNumPlacementArgs()) {
9503     // The only new-placement list we support is of the form (std::nothrow).
9504     //
9505     // FIXME: There is no restriction on this, but it's not clear that any
9506     // other form makes any sense. We get here for cases such as:
9507     //
9508     //   new (std::align_val_t{N}) X(int)
9509     //
9510     // (which should presumably be valid only if N is a multiple of
9511     // alignof(int), and in any case can't be deallocated unless N is
9512     // alignof(X) and X has new-extended alignment).
9513     if (E->getNumPlacementArgs() != 1 ||
9514         !E->getPlacementArg(0)->getType()->isNothrowT())
9515       return Error(E, diag::note_constexpr_new_placement);
9516 
9517     LValue Nothrow;
9518     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9519       return false;
9520     IsNothrow = true;
9521   }
9522 
9523   const Expr *Init = E->getInitializer();
9524   const InitListExpr *ResizedArrayILE = nullptr;
9525   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9526   bool ValueInit = false;
9527 
9528   QualType AllocType = E->getAllocatedType();
9529   if (Optional<const Expr *> ArraySize = E->getArraySize()) {
9530     const Expr *Stripped = *ArraySize;
9531     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9532          Stripped = ICE->getSubExpr())
9533       if (ICE->getCastKind() != CK_NoOp &&
9534           ICE->getCastKind() != CK_IntegralCast)
9535         break;
9536 
9537     llvm::APSInt ArrayBound;
9538     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9539       return false;
9540 
9541     // C++ [expr.new]p9:
9542     //   The expression is erroneous if:
9543     //   -- [...] its value before converting to size_t [or] applying the
9544     //      second standard conversion sequence is less than zero
9545     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9546       if (IsNothrow)
9547         return ZeroInitialization(E);
9548 
9549       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9550           << ArrayBound << (*ArraySize)->getSourceRange();
9551       return false;
9552     }
9553 
9554     //   -- its value is such that the size of the allocated object would
9555     //      exceed the implementation-defined limit
9556     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9557                                                 ArrayBound) >
9558         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9559       if (IsNothrow)
9560         return ZeroInitialization(E);
9561 
9562       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9563         << ArrayBound << (*ArraySize)->getSourceRange();
9564       return false;
9565     }
9566 
9567     //   -- the new-initializer is a braced-init-list and the number of
9568     //      array elements for which initializers are provided [...]
9569     //      exceeds the number of elements to initialize
9570     if (!Init) {
9571       // No initialization is performed.
9572     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9573                isa<ImplicitValueInitExpr>(Init)) {
9574       ValueInit = true;
9575     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9576       ResizedArrayCCE = CCE;
9577     } else {
9578       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9579       assert(CAT && "unexpected type for array initializer");
9580 
9581       unsigned Bits =
9582           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9583       llvm::APInt InitBound = CAT->getSize().zext(Bits);
9584       llvm::APInt AllocBound = ArrayBound.zext(Bits);
9585       if (InitBound.ugt(AllocBound)) {
9586         if (IsNothrow)
9587           return ZeroInitialization(E);
9588 
9589         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9590             << toString(AllocBound, 10, /*Signed=*/false)
9591             << toString(InitBound, 10, /*Signed=*/false)
9592             << (*ArraySize)->getSourceRange();
9593         return false;
9594       }
9595 
9596       // If the sizes differ, we must have an initializer list, and we need
9597       // special handling for this case when we initialize.
9598       if (InitBound != AllocBound)
9599         ResizedArrayILE = cast<InitListExpr>(Init);
9600     }
9601 
9602     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9603                                               ArrayType::Normal, 0);
9604   } else {
9605     assert(!AllocType->isArrayType() &&
9606            "array allocation with non-array new");
9607   }
9608 
9609   APValue *Val;
9610   if (IsPlacement) {
9611     AccessKinds AK = AK_Construct;
9612     struct FindObjectHandler {
9613       EvalInfo &Info;
9614       const Expr *E;
9615       QualType AllocType;
9616       const AccessKinds AccessKind;
9617       APValue *Value;
9618 
9619       typedef bool result_type;
9620       bool failed() { return false; }
9621       bool found(APValue &Subobj, QualType SubobjType) {
9622         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9623         // old name of the object to be used to name the new object.
9624         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9625           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9626             SubobjType << AllocType;
9627           return false;
9628         }
9629         Value = &Subobj;
9630         return true;
9631       }
9632       bool found(APSInt &Value, QualType SubobjType) {
9633         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9634         return false;
9635       }
9636       bool found(APFloat &Value, QualType SubobjType) {
9637         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9638         return false;
9639       }
9640     } Handler = {Info, E, AllocType, AK, nullptr};
9641 
9642     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9643     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9644       return false;
9645 
9646     Val = Handler.Value;
9647 
9648     // [basic.life]p1:
9649     //   The lifetime of an object o of type T ends when [...] the storage
9650     //   which the object occupies is [...] reused by an object that is not
9651     //   nested within o (6.6.2).
9652     *Val = APValue();
9653   } else {
9654     // Perform the allocation and obtain a pointer to the resulting object.
9655     Val = Info.createHeapAlloc(E, AllocType, Result);
9656     if (!Val)
9657       return false;
9658   }
9659 
9660   if (ValueInit) {
9661     ImplicitValueInitExpr VIE(AllocType);
9662     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9663       return false;
9664   } else if (ResizedArrayILE) {
9665     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9666                                   AllocType))
9667       return false;
9668   } else if (ResizedArrayCCE) {
9669     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9670                                        AllocType))
9671       return false;
9672   } else if (Init) {
9673     if (!EvaluateInPlace(*Val, Info, Result, Init))
9674       return false;
9675   } else if (!getDefaultInitValue(AllocType, *Val)) {
9676     return false;
9677   }
9678 
9679   // Array new returns a pointer to the first element, not a pointer to the
9680   // array.
9681   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9682     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9683 
9684   return true;
9685 }
9686 //===----------------------------------------------------------------------===//
9687 // Member Pointer Evaluation
9688 //===----------------------------------------------------------------------===//
9689 
9690 namespace {
9691 class MemberPointerExprEvaluator
9692   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9693   MemberPtr &Result;
9694 
9695   bool Success(const ValueDecl *D) {
9696     Result = MemberPtr(D);
9697     return true;
9698   }
9699 public:
9700 
9701   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9702     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9703 
9704   bool Success(const APValue &V, const Expr *E) {
9705     Result.setFrom(V);
9706     return true;
9707   }
9708   bool ZeroInitialization(const Expr *E) {
9709     return Success((const ValueDecl*)nullptr);
9710   }
9711 
9712   bool VisitCastExpr(const CastExpr *E);
9713   bool VisitUnaryAddrOf(const UnaryOperator *E);
9714 };
9715 } // end anonymous namespace
9716 
9717 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9718                                   EvalInfo &Info) {
9719   assert(!E->isValueDependent());
9720   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9721   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9722 }
9723 
9724 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9725   switch (E->getCastKind()) {
9726   default:
9727     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9728 
9729   case CK_NullToMemberPointer:
9730     VisitIgnoredValue(E->getSubExpr());
9731     return ZeroInitialization(E);
9732 
9733   case CK_BaseToDerivedMemberPointer: {
9734     if (!Visit(E->getSubExpr()))
9735       return false;
9736     if (E->path_empty())
9737       return true;
9738     // Base-to-derived member pointer casts store the path in derived-to-base
9739     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9740     // the wrong end of the derived->base arc, so stagger the path by one class.
9741     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9742     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9743          PathI != PathE; ++PathI) {
9744       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9745       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9746       if (!Result.castToDerived(Derived))
9747         return Error(E);
9748     }
9749     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9750     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9751       return Error(E);
9752     return true;
9753   }
9754 
9755   case CK_DerivedToBaseMemberPointer:
9756     if (!Visit(E->getSubExpr()))
9757       return false;
9758     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9759          PathE = E->path_end(); PathI != PathE; ++PathI) {
9760       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9761       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9762       if (!Result.castToBase(Base))
9763         return Error(E);
9764     }
9765     return true;
9766   }
9767 }
9768 
9769 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9770   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9771   // member can be formed.
9772   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9773 }
9774 
9775 //===----------------------------------------------------------------------===//
9776 // Record Evaluation
9777 //===----------------------------------------------------------------------===//
9778 
9779 namespace {
9780   class RecordExprEvaluator
9781   : public ExprEvaluatorBase<RecordExprEvaluator> {
9782     const LValue &This;
9783     APValue &Result;
9784   public:
9785 
9786     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9787       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9788 
9789     bool Success(const APValue &V, const Expr *E) {
9790       Result = V;
9791       return true;
9792     }
9793     bool ZeroInitialization(const Expr *E) {
9794       return ZeroInitialization(E, E->getType());
9795     }
9796     bool ZeroInitialization(const Expr *E, QualType T);
9797 
9798     bool VisitCallExpr(const CallExpr *E) {
9799       return handleCallExpr(E, Result, &This);
9800     }
9801     bool VisitCastExpr(const CastExpr *E);
9802     bool VisitInitListExpr(const InitListExpr *E);
9803     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9804       return VisitCXXConstructExpr(E, E->getType());
9805     }
9806     bool VisitLambdaExpr(const LambdaExpr *E);
9807     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9808     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9809     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9810     bool VisitBinCmp(const BinaryOperator *E);
9811   };
9812 }
9813 
9814 /// Perform zero-initialization on an object of non-union class type.
9815 /// C++11 [dcl.init]p5:
9816 ///  To zero-initialize an object or reference of type T means:
9817 ///    [...]
9818 ///    -- if T is a (possibly cv-qualified) non-union class type,
9819 ///       each non-static data member and each base-class subobject is
9820 ///       zero-initialized
9821 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9822                                           const RecordDecl *RD,
9823                                           const LValue &This, APValue &Result) {
9824   assert(!RD->isUnion() && "Expected non-union class type");
9825   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9826   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9827                    std::distance(RD->field_begin(), RD->field_end()));
9828 
9829   if (RD->isInvalidDecl()) return false;
9830   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9831 
9832   if (CD) {
9833     unsigned Index = 0;
9834     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9835            End = CD->bases_end(); I != End; ++I, ++Index) {
9836       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9837       LValue Subobject = This;
9838       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9839         return false;
9840       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9841                                          Result.getStructBase(Index)))
9842         return false;
9843     }
9844   }
9845 
9846   for (const auto *I : RD->fields()) {
9847     // -- if T is a reference type, no initialization is performed.
9848     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9849       continue;
9850 
9851     LValue Subobject = This;
9852     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9853       return false;
9854 
9855     ImplicitValueInitExpr VIE(I->getType());
9856     if (!EvaluateInPlace(
9857           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9858       return false;
9859   }
9860 
9861   return true;
9862 }
9863 
9864 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9865   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9866   if (RD->isInvalidDecl()) return false;
9867   if (RD->isUnion()) {
9868     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9869     // object's first non-static named data member is zero-initialized
9870     RecordDecl::field_iterator I = RD->field_begin();
9871     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9872       ++I;
9873     if (I == RD->field_end()) {
9874       Result = APValue((const FieldDecl*)nullptr);
9875       return true;
9876     }
9877 
9878     LValue Subobject = This;
9879     if (!HandleLValueMember(Info, E, Subobject, *I))
9880       return false;
9881     Result = APValue(*I);
9882     ImplicitValueInitExpr VIE(I->getType());
9883     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9884   }
9885 
9886   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9887     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9888     return false;
9889   }
9890 
9891   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9892 }
9893 
9894 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9895   switch (E->getCastKind()) {
9896   default:
9897     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9898 
9899   case CK_ConstructorConversion:
9900     return Visit(E->getSubExpr());
9901 
9902   case CK_DerivedToBase:
9903   case CK_UncheckedDerivedToBase: {
9904     APValue DerivedObject;
9905     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9906       return false;
9907     if (!DerivedObject.isStruct())
9908       return Error(E->getSubExpr());
9909 
9910     // Derived-to-base rvalue conversion: just slice off the derived part.
9911     APValue *Value = &DerivedObject;
9912     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9913     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9914          PathE = E->path_end(); PathI != PathE; ++PathI) {
9915       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9916       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9917       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9918       RD = Base;
9919     }
9920     Result = *Value;
9921     return true;
9922   }
9923   }
9924 }
9925 
9926 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9927   if (E->isTransparent())
9928     return Visit(E->getInit(0));
9929 
9930   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9931   if (RD->isInvalidDecl()) return false;
9932   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9933   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9934 
9935   EvalInfo::EvaluatingConstructorRAII EvalObj(
9936       Info,
9937       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9938       CXXRD && CXXRD->getNumBases());
9939 
9940   if (RD->isUnion()) {
9941     const FieldDecl *Field = E->getInitializedFieldInUnion();
9942     Result = APValue(Field);
9943     if (!Field)
9944       return true;
9945 
9946     // If the initializer list for a union does not contain any elements, the
9947     // first element of the union is value-initialized.
9948     // FIXME: The element should be initialized from an initializer list.
9949     //        Is this difference ever observable for initializer lists which
9950     //        we don't build?
9951     ImplicitValueInitExpr VIE(Field->getType());
9952     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9953 
9954     LValue Subobject = This;
9955     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9956       return false;
9957 
9958     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9959     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9960                                   isa<CXXDefaultInitExpr>(InitExpr));
9961 
9962     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9963       if (Field->isBitField())
9964         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9965                                      Field);
9966       return true;
9967     }
9968 
9969     return false;
9970   }
9971 
9972   if (!Result.hasValue())
9973     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9974                      std::distance(RD->field_begin(), RD->field_end()));
9975   unsigned ElementNo = 0;
9976   bool Success = true;
9977 
9978   // Initialize base classes.
9979   if (CXXRD && CXXRD->getNumBases()) {
9980     for (const auto &Base : CXXRD->bases()) {
9981       assert(ElementNo < E->getNumInits() && "missing init for base class");
9982       const Expr *Init = E->getInit(ElementNo);
9983 
9984       LValue Subobject = This;
9985       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9986         return false;
9987 
9988       APValue &FieldVal = Result.getStructBase(ElementNo);
9989       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9990         if (!Info.noteFailure())
9991           return false;
9992         Success = false;
9993       }
9994       ++ElementNo;
9995     }
9996 
9997     EvalObj.finishedConstructingBases();
9998   }
9999 
10000   // Initialize members.
10001   for (const auto *Field : RD->fields()) {
10002     // Anonymous bit-fields are not considered members of the class for
10003     // purposes of aggregate initialization.
10004     if (Field->isUnnamedBitfield())
10005       continue;
10006 
10007     LValue Subobject = This;
10008 
10009     bool HaveInit = ElementNo < E->getNumInits();
10010 
10011     // FIXME: Diagnostics here should point to the end of the initializer
10012     // list, not the start.
10013     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
10014                             Subobject, Field, &Layout))
10015       return false;
10016 
10017     // Perform an implicit value-initialization for members beyond the end of
10018     // the initializer list.
10019     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10020     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
10021 
10022     if (Field->getType()->isIncompleteArrayType()) {
10023       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10024         if (!CAT->getSize().isZero()) {
10025           // Bail out for now. This might sort of "work", but the rest of the
10026           // code isn't really prepared to handle it.
10027           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10028           return false;
10029         }
10030       }
10031     }
10032 
10033     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10034     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10035                                   isa<CXXDefaultInitExpr>(Init));
10036 
10037     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10038     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10039         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10040                                                        FieldVal, Field))) {
10041       if (!Info.noteFailure())
10042         return false;
10043       Success = false;
10044     }
10045   }
10046 
10047   EvalObj.finishedConstructingFields();
10048 
10049   return Success;
10050 }
10051 
10052 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10053                                                 QualType T) {
10054   // Note that E's type is not necessarily the type of our class here; we might
10055   // be initializing an array element instead.
10056   const CXXConstructorDecl *FD = E->getConstructor();
10057   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10058 
10059   bool ZeroInit = E->requiresZeroInitialization();
10060   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10061     // If we've already performed zero-initialization, we're already done.
10062     if (Result.hasValue())
10063       return true;
10064 
10065     if (ZeroInit)
10066       return ZeroInitialization(E, T);
10067 
10068     return getDefaultInitValue(T, Result);
10069   }
10070 
10071   const FunctionDecl *Definition = nullptr;
10072   auto Body = FD->getBody(Definition);
10073 
10074   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10075     return false;
10076 
10077   // Avoid materializing a temporary for an elidable copy/move constructor.
10078   if (E->isElidable() && !ZeroInit) {
10079     // FIXME: This only handles the simplest case, where the source object
10080     //        is passed directly as the first argument to the constructor.
10081     //        This should also handle stepping though implicit casts and
10082     //        and conversion sequences which involve two steps, with a
10083     //        conversion operator followed by a converting constructor.
10084     const Expr *SrcObj = E->getArg(0);
10085     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10086     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10087     if (const MaterializeTemporaryExpr *ME =
10088             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10089       return Visit(ME->getSubExpr());
10090   }
10091 
10092   if (ZeroInit && !ZeroInitialization(E, T))
10093     return false;
10094 
10095   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
10096   return HandleConstructorCall(E, This, Args,
10097                                cast<CXXConstructorDecl>(Definition), Info,
10098                                Result);
10099 }
10100 
10101 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10102     const CXXInheritedCtorInitExpr *E) {
10103   if (!Info.CurrentCall) {
10104     assert(Info.checkingPotentialConstantExpression());
10105     return false;
10106   }
10107 
10108   const CXXConstructorDecl *FD = E->getConstructor();
10109   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10110     return false;
10111 
10112   const FunctionDecl *Definition = nullptr;
10113   auto Body = FD->getBody(Definition);
10114 
10115   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10116     return false;
10117 
10118   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10119                                cast<CXXConstructorDecl>(Definition), Info,
10120                                Result);
10121 }
10122 
10123 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10124     const CXXStdInitializerListExpr *E) {
10125   const ConstantArrayType *ArrayType =
10126       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10127 
10128   LValue Array;
10129   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10130     return false;
10131 
10132   // Get a pointer to the first element of the array.
10133   Array.addArray(Info, E, ArrayType);
10134 
10135   auto InvalidType = [&] {
10136     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10137       << E->getType();
10138     return false;
10139   };
10140 
10141   // FIXME: Perform the checks on the field types in SemaInit.
10142   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10143   RecordDecl::field_iterator Field = Record->field_begin();
10144   if (Field == Record->field_end())
10145     return InvalidType();
10146 
10147   // Start pointer.
10148   if (!Field->getType()->isPointerType() ||
10149       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10150                             ArrayType->getElementType()))
10151     return InvalidType();
10152 
10153   // FIXME: What if the initializer_list type has base classes, etc?
10154   Result = APValue(APValue::UninitStruct(), 0, 2);
10155   Array.moveInto(Result.getStructField(0));
10156 
10157   if (++Field == Record->field_end())
10158     return InvalidType();
10159 
10160   if (Field->getType()->isPointerType() &&
10161       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10162                            ArrayType->getElementType())) {
10163     // End pointer.
10164     if (!HandleLValueArrayAdjustment(Info, E, Array,
10165                                      ArrayType->getElementType(),
10166                                      ArrayType->getSize().getZExtValue()))
10167       return false;
10168     Array.moveInto(Result.getStructField(1));
10169   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10170     // Length.
10171     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10172   else
10173     return InvalidType();
10174 
10175   if (++Field != Record->field_end())
10176     return InvalidType();
10177 
10178   return true;
10179 }
10180 
10181 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10182   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10183   if (ClosureClass->isInvalidDecl())
10184     return false;
10185 
10186   const size_t NumFields =
10187       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10188 
10189   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10190                                             E->capture_init_end()) &&
10191          "The number of lambda capture initializers should equal the number of "
10192          "fields within the closure type");
10193 
10194   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10195   // Iterate through all the lambda's closure object's fields and initialize
10196   // them.
10197   auto *CaptureInitIt = E->capture_init_begin();
10198   bool Success = true;
10199   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10200   for (const auto *Field : ClosureClass->fields()) {
10201     assert(CaptureInitIt != E->capture_init_end());
10202     // Get the initializer for this field
10203     Expr *const CurFieldInit = *CaptureInitIt++;
10204 
10205     // If there is no initializer, either this is a VLA or an error has
10206     // occurred.
10207     if (!CurFieldInit)
10208       return Error(E);
10209 
10210     LValue Subobject = This;
10211 
10212     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10213       return false;
10214 
10215     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10216     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10217       if (!Info.keepEvaluatingAfterFailure())
10218         return false;
10219       Success = false;
10220     }
10221   }
10222   return Success;
10223 }
10224 
10225 static bool EvaluateRecord(const Expr *E, const LValue &This,
10226                            APValue &Result, EvalInfo &Info) {
10227   assert(!E->isValueDependent());
10228   assert(E->isPRValue() && E->getType()->isRecordType() &&
10229          "can't evaluate expression as a record rvalue");
10230   return RecordExprEvaluator(Info, This, Result).Visit(E);
10231 }
10232 
10233 //===----------------------------------------------------------------------===//
10234 // Temporary Evaluation
10235 //
10236 // Temporaries are represented in the AST as rvalues, but generally behave like
10237 // lvalues. The full-object of which the temporary is a subobject is implicitly
10238 // materialized so that a reference can bind to it.
10239 //===----------------------------------------------------------------------===//
10240 namespace {
10241 class TemporaryExprEvaluator
10242   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10243 public:
10244   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10245     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10246 
10247   /// Visit an expression which constructs the value of this temporary.
10248   bool VisitConstructExpr(const Expr *E) {
10249     APValue &Value = Info.CurrentCall->createTemporary(
10250         E, E->getType(), ScopeKind::FullExpression, Result);
10251     return EvaluateInPlace(Value, Info, Result, E);
10252   }
10253 
10254   bool VisitCastExpr(const CastExpr *E) {
10255     switch (E->getCastKind()) {
10256     default:
10257       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10258 
10259     case CK_ConstructorConversion:
10260       return VisitConstructExpr(E->getSubExpr());
10261     }
10262   }
10263   bool VisitInitListExpr(const InitListExpr *E) {
10264     return VisitConstructExpr(E);
10265   }
10266   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10267     return VisitConstructExpr(E);
10268   }
10269   bool VisitCallExpr(const CallExpr *E) {
10270     return VisitConstructExpr(E);
10271   }
10272   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10273     return VisitConstructExpr(E);
10274   }
10275   bool VisitLambdaExpr(const LambdaExpr *E) {
10276     return VisitConstructExpr(E);
10277   }
10278 };
10279 } // end anonymous namespace
10280 
10281 /// Evaluate an expression of record type as a temporary.
10282 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10283   assert(!E->isValueDependent());
10284   assert(E->isPRValue() && E->getType()->isRecordType());
10285   return TemporaryExprEvaluator(Info, Result).Visit(E);
10286 }
10287 
10288 //===----------------------------------------------------------------------===//
10289 // Vector Evaluation
10290 //===----------------------------------------------------------------------===//
10291 
10292 namespace {
10293   class VectorExprEvaluator
10294   : public ExprEvaluatorBase<VectorExprEvaluator> {
10295     APValue &Result;
10296   public:
10297 
10298     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10299       : ExprEvaluatorBaseTy(info), Result(Result) {}
10300 
10301     bool Success(ArrayRef<APValue> V, const Expr *E) {
10302       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10303       // FIXME: remove this APValue copy.
10304       Result = APValue(V.data(), V.size());
10305       return true;
10306     }
10307     bool Success(const APValue &V, const Expr *E) {
10308       assert(V.isVector());
10309       Result = V;
10310       return true;
10311     }
10312     bool ZeroInitialization(const Expr *E);
10313 
10314     bool VisitUnaryReal(const UnaryOperator *E)
10315       { return Visit(E->getSubExpr()); }
10316     bool VisitCastExpr(const CastExpr* E);
10317     bool VisitInitListExpr(const InitListExpr *E);
10318     bool VisitUnaryImag(const UnaryOperator *E);
10319     bool VisitBinaryOperator(const BinaryOperator *E);
10320     bool VisitUnaryOperator(const UnaryOperator *E);
10321     // FIXME: Missing: conditional operator (for GNU
10322     //                 conditional select), shufflevector, ExtVectorElementExpr
10323   };
10324 } // end anonymous namespace
10325 
10326 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10327   assert(E->isPRValue() && E->getType()->isVectorType() &&
10328          "not a vector prvalue");
10329   return VectorExprEvaluator(Info, Result).Visit(E);
10330 }
10331 
10332 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10333   const VectorType *VTy = E->getType()->castAs<VectorType>();
10334   unsigned NElts = VTy->getNumElements();
10335 
10336   const Expr *SE = E->getSubExpr();
10337   QualType SETy = SE->getType();
10338 
10339   switch (E->getCastKind()) {
10340   case CK_VectorSplat: {
10341     APValue Val = APValue();
10342     if (SETy->isIntegerType()) {
10343       APSInt IntResult;
10344       if (!EvaluateInteger(SE, IntResult, Info))
10345         return false;
10346       Val = APValue(std::move(IntResult));
10347     } else if (SETy->isRealFloatingType()) {
10348       APFloat FloatResult(0.0);
10349       if (!EvaluateFloat(SE, FloatResult, Info))
10350         return false;
10351       Val = APValue(std::move(FloatResult));
10352     } else {
10353       return Error(E);
10354     }
10355 
10356     // Splat and create vector APValue.
10357     SmallVector<APValue, 4> Elts(NElts, Val);
10358     return Success(Elts, E);
10359   }
10360   case CK_BitCast: {
10361     // Evaluate the operand into an APInt we can extract from.
10362     llvm::APInt SValInt;
10363     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10364       return false;
10365     // Extract the elements
10366     QualType EltTy = VTy->getElementType();
10367     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10368     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10369     SmallVector<APValue, 4> Elts;
10370     if (EltTy->isRealFloatingType()) {
10371       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10372       unsigned FloatEltSize = EltSize;
10373       if (&Sem == &APFloat::x87DoubleExtended())
10374         FloatEltSize = 80;
10375       for (unsigned i = 0; i < NElts; i++) {
10376         llvm::APInt Elt;
10377         if (BigEndian)
10378           Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10379         else
10380           Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10381         Elts.push_back(APValue(APFloat(Sem, Elt)));
10382       }
10383     } else if (EltTy->isIntegerType()) {
10384       for (unsigned i = 0; i < NElts; i++) {
10385         llvm::APInt Elt;
10386         if (BigEndian)
10387           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10388         else
10389           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10390         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10391       }
10392     } else {
10393       return Error(E);
10394     }
10395     return Success(Elts, E);
10396   }
10397   default:
10398     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10399   }
10400 }
10401 
10402 bool
10403 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10404   const VectorType *VT = E->getType()->castAs<VectorType>();
10405   unsigned NumInits = E->getNumInits();
10406   unsigned NumElements = VT->getNumElements();
10407 
10408   QualType EltTy = VT->getElementType();
10409   SmallVector<APValue, 4> Elements;
10410 
10411   // The number of initializers can be less than the number of
10412   // vector elements. For OpenCL, this can be due to nested vector
10413   // initialization. For GCC compatibility, missing trailing elements
10414   // should be initialized with zeroes.
10415   unsigned CountInits = 0, CountElts = 0;
10416   while (CountElts < NumElements) {
10417     // Handle nested vector initialization.
10418     if (CountInits < NumInits
10419         && E->getInit(CountInits)->getType()->isVectorType()) {
10420       APValue v;
10421       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10422         return Error(E);
10423       unsigned vlen = v.getVectorLength();
10424       for (unsigned j = 0; j < vlen; j++)
10425         Elements.push_back(v.getVectorElt(j));
10426       CountElts += vlen;
10427     } else if (EltTy->isIntegerType()) {
10428       llvm::APSInt sInt(32);
10429       if (CountInits < NumInits) {
10430         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10431           return false;
10432       } else // trailing integer zero.
10433         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10434       Elements.push_back(APValue(sInt));
10435       CountElts++;
10436     } else {
10437       llvm::APFloat f(0.0);
10438       if (CountInits < NumInits) {
10439         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10440           return false;
10441       } else // trailing float zero.
10442         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10443       Elements.push_back(APValue(f));
10444       CountElts++;
10445     }
10446     CountInits++;
10447   }
10448   return Success(Elements, E);
10449 }
10450 
10451 bool
10452 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10453   const auto *VT = E->getType()->castAs<VectorType>();
10454   QualType EltTy = VT->getElementType();
10455   APValue ZeroElement;
10456   if (EltTy->isIntegerType())
10457     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10458   else
10459     ZeroElement =
10460         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10461 
10462   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10463   return Success(Elements, E);
10464 }
10465 
10466 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10467   VisitIgnoredValue(E->getSubExpr());
10468   return ZeroInitialization(E);
10469 }
10470 
10471 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10472   BinaryOperatorKind Op = E->getOpcode();
10473   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10474          "Operation not supported on vector types");
10475 
10476   if (Op == BO_Comma)
10477     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10478 
10479   Expr *LHS = E->getLHS();
10480   Expr *RHS = E->getRHS();
10481 
10482   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10483          "Must both be vector types");
10484   // Checking JUST the types are the same would be fine, except shifts don't
10485   // need to have their types be the same (since you always shift by an int).
10486   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10487              E->getType()->castAs<VectorType>()->getNumElements() &&
10488          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10489              E->getType()->castAs<VectorType>()->getNumElements() &&
10490          "All operands must be the same size.");
10491 
10492   APValue LHSValue;
10493   APValue RHSValue;
10494   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10495   if (!LHSOK && !Info.noteFailure())
10496     return false;
10497   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10498     return false;
10499 
10500   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10501     return false;
10502 
10503   return Success(LHSValue, E);
10504 }
10505 
10506 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10507                                                          QualType ResultTy,
10508                                                          UnaryOperatorKind Op,
10509                                                          APValue Elt) {
10510   switch (Op) {
10511   case UO_Plus:
10512     // Nothing to do here.
10513     return Elt;
10514   case UO_Minus:
10515     if (Elt.getKind() == APValue::Int) {
10516       Elt.getInt().negate();
10517     } else {
10518       assert(Elt.getKind() == APValue::Float &&
10519              "Vector can only be int or float type");
10520       Elt.getFloat().changeSign();
10521     }
10522     return Elt;
10523   case UO_Not:
10524     // This is only valid for integral types anyway, so we don't have to handle
10525     // float here.
10526     assert(Elt.getKind() == APValue::Int &&
10527            "Vector operator ~ can only be int");
10528     Elt.getInt().flipAllBits();
10529     return Elt;
10530   case UO_LNot: {
10531     if (Elt.getKind() == APValue::Int) {
10532       Elt.getInt() = !Elt.getInt();
10533       // operator ! on vectors returns -1 for 'truth', so negate it.
10534       Elt.getInt().negate();
10535       return Elt;
10536     }
10537     assert(Elt.getKind() == APValue::Float &&
10538            "Vector can only be int or float type");
10539     // Float types result in an int of the same size, but -1 for true, or 0 for
10540     // false.
10541     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10542                      ResultTy->isUnsignedIntegerType()};
10543     if (Elt.getFloat().isZero())
10544       EltResult.setAllBits();
10545     else
10546       EltResult.clearAllBits();
10547 
10548     return APValue{EltResult};
10549   }
10550   default:
10551     // FIXME: Implement the rest of the unary operators.
10552     return llvm::None;
10553   }
10554 }
10555 
10556 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10557   Expr *SubExpr = E->getSubExpr();
10558   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10559   // This result element type differs in the case of negating a floating point
10560   // vector, since the result type is the a vector of the equivilant sized
10561   // integer.
10562   const QualType ResultEltTy = VD->getElementType();
10563   UnaryOperatorKind Op = E->getOpcode();
10564 
10565   APValue SubExprValue;
10566   if (!Evaluate(SubExprValue, Info, SubExpr))
10567     return false;
10568 
10569   // FIXME: This vector evaluator someday needs to be changed to be LValue
10570   // aware/keep LValue information around, rather than dealing with just vector
10571   // types directly. Until then, we cannot handle cases where the operand to
10572   // these unary operators is an LValue. The only case I've been able to see
10573   // cause this is operator++ assigning to a member expression (only valid in
10574   // altivec compilations) in C mode, so this shouldn't limit us too much.
10575   if (SubExprValue.isLValue())
10576     return false;
10577 
10578   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10579          "Vector length doesn't match type?");
10580 
10581   SmallVector<APValue, 4> ResultElements;
10582   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10583     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10584         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10585     if (!Elt)
10586       return false;
10587     ResultElements.push_back(*Elt);
10588   }
10589   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10590 }
10591 
10592 //===----------------------------------------------------------------------===//
10593 // Array Evaluation
10594 //===----------------------------------------------------------------------===//
10595 
10596 namespace {
10597   class ArrayExprEvaluator
10598   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10599     const LValue &This;
10600     APValue &Result;
10601   public:
10602 
10603     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10604       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10605 
10606     bool Success(const APValue &V, const Expr *E) {
10607       assert(V.isArray() && "expected array");
10608       Result = V;
10609       return true;
10610     }
10611 
10612     bool ZeroInitialization(const Expr *E) {
10613       const ConstantArrayType *CAT =
10614           Info.Ctx.getAsConstantArrayType(E->getType());
10615       if (!CAT) {
10616         if (E->getType()->isIncompleteArrayType()) {
10617           // We can be asked to zero-initialize a flexible array member; this
10618           // is represented as an ImplicitValueInitExpr of incomplete array
10619           // type. In this case, the array has zero elements.
10620           Result = APValue(APValue::UninitArray(), 0, 0);
10621           return true;
10622         }
10623         // FIXME: We could handle VLAs here.
10624         return Error(E);
10625       }
10626 
10627       Result = APValue(APValue::UninitArray(), 0,
10628                        CAT->getSize().getZExtValue());
10629       if (!Result.hasArrayFiller())
10630         return true;
10631 
10632       // Zero-initialize all elements.
10633       LValue Subobject = This;
10634       Subobject.addArray(Info, E, CAT);
10635       ImplicitValueInitExpr VIE(CAT->getElementType());
10636       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10637     }
10638 
10639     bool VisitCallExpr(const CallExpr *E) {
10640       return handleCallExpr(E, Result, &This);
10641     }
10642     bool VisitInitListExpr(const InitListExpr *E,
10643                            QualType AllocType = QualType());
10644     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10645     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10646     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10647                                const LValue &Subobject,
10648                                APValue *Value, QualType Type);
10649     bool VisitStringLiteral(const StringLiteral *E,
10650                             QualType AllocType = QualType()) {
10651       expandStringLiteral(Info, E, Result, AllocType);
10652       return true;
10653     }
10654   };
10655 } // end anonymous namespace
10656 
10657 static bool EvaluateArray(const Expr *E, const LValue &This,
10658                           APValue &Result, EvalInfo &Info) {
10659   assert(!E->isValueDependent());
10660   assert(E->isPRValue() && E->getType()->isArrayType() &&
10661          "not an array prvalue");
10662   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10663 }
10664 
10665 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10666                                      APValue &Result, const InitListExpr *ILE,
10667                                      QualType AllocType) {
10668   assert(!ILE->isValueDependent());
10669   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10670          "not an array prvalue");
10671   return ArrayExprEvaluator(Info, This, Result)
10672       .VisitInitListExpr(ILE, AllocType);
10673 }
10674 
10675 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10676                                           APValue &Result,
10677                                           const CXXConstructExpr *CCE,
10678                                           QualType AllocType) {
10679   assert(!CCE->isValueDependent());
10680   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10681          "not an array prvalue");
10682   return ArrayExprEvaluator(Info, This, Result)
10683       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10684 }
10685 
10686 // Return true iff the given array filler may depend on the element index.
10687 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10688   // For now, just allow non-class value-initialization and initialization
10689   // lists comprised of them.
10690   if (isa<ImplicitValueInitExpr>(FillerExpr))
10691     return false;
10692   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10693     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10694       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10695         return true;
10696     }
10697     return false;
10698   }
10699   return true;
10700 }
10701 
10702 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10703                                            QualType AllocType) {
10704   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10705       AllocType.isNull() ? E->getType() : AllocType);
10706   if (!CAT)
10707     return Error(E);
10708 
10709   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10710   // an appropriately-typed string literal enclosed in braces.
10711   if (E->isStringLiteralInit()) {
10712     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10713     // FIXME: Support ObjCEncodeExpr here once we support it in
10714     // ArrayExprEvaluator generally.
10715     if (!SL)
10716       return Error(E);
10717     return VisitStringLiteral(SL, AllocType);
10718   }
10719   // Any other transparent list init will need proper handling of the
10720   // AllocType; we can't just recurse to the inner initializer.
10721   assert(!E->isTransparent() &&
10722          "transparent array list initialization is not string literal init?");
10723 
10724   bool Success = true;
10725 
10726   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10727          "zero-initialized array shouldn't have any initialized elts");
10728   APValue Filler;
10729   if (Result.isArray() && Result.hasArrayFiller())
10730     Filler = Result.getArrayFiller();
10731 
10732   unsigned NumEltsToInit = E->getNumInits();
10733   unsigned NumElts = CAT->getSize().getZExtValue();
10734   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10735 
10736   // If the initializer might depend on the array index, run it for each
10737   // array element.
10738   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10739     NumEltsToInit = NumElts;
10740 
10741   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10742                           << NumEltsToInit << ".\n");
10743 
10744   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10745 
10746   // If the array was previously zero-initialized, preserve the
10747   // zero-initialized values.
10748   if (Filler.hasValue()) {
10749     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10750       Result.getArrayInitializedElt(I) = Filler;
10751     if (Result.hasArrayFiller())
10752       Result.getArrayFiller() = Filler;
10753   }
10754 
10755   LValue Subobject = This;
10756   Subobject.addArray(Info, E, CAT);
10757   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10758     const Expr *Init =
10759         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10760     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10761                          Info, Subobject, Init) ||
10762         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10763                                      CAT->getElementType(), 1)) {
10764       if (!Info.noteFailure())
10765         return false;
10766       Success = false;
10767     }
10768   }
10769 
10770   if (!Result.hasArrayFiller())
10771     return Success;
10772 
10773   // If we get here, we have a trivial filler, which we can just evaluate
10774   // once and splat over the rest of the array elements.
10775   assert(FillerExpr && "no array filler for incomplete init list");
10776   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10777                          FillerExpr) && Success;
10778 }
10779 
10780 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10781   LValue CommonLV;
10782   if (E->getCommonExpr() &&
10783       !Evaluate(Info.CurrentCall->createTemporary(
10784                     E->getCommonExpr(),
10785                     getStorageType(Info.Ctx, E->getCommonExpr()),
10786                     ScopeKind::FullExpression, CommonLV),
10787                 Info, E->getCommonExpr()->getSourceExpr()))
10788     return false;
10789 
10790   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10791 
10792   uint64_t Elements = CAT->getSize().getZExtValue();
10793   Result = APValue(APValue::UninitArray(), Elements, Elements);
10794 
10795   LValue Subobject = This;
10796   Subobject.addArray(Info, E, CAT);
10797 
10798   bool Success = true;
10799   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10800     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10801                          Info, Subobject, E->getSubExpr()) ||
10802         !HandleLValueArrayAdjustment(Info, E, Subobject,
10803                                      CAT->getElementType(), 1)) {
10804       if (!Info.noteFailure())
10805         return false;
10806       Success = false;
10807     }
10808   }
10809 
10810   return Success;
10811 }
10812 
10813 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10814   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10815 }
10816 
10817 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10818                                                const LValue &Subobject,
10819                                                APValue *Value,
10820                                                QualType Type) {
10821   bool HadZeroInit = Value->hasValue();
10822 
10823   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10824     unsigned FinalSize = CAT->getSize().getZExtValue();
10825 
10826     // Preserve the array filler if we had prior zero-initialization.
10827     APValue Filler =
10828       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10829                                              : APValue();
10830 
10831     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10832     if (FinalSize == 0)
10833       return true;
10834 
10835     LValue ArrayElt = Subobject;
10836     ArrayElt.addArray(Info, E, CAT);
10837     // We do the whole initialization in two passes, first for just one element,
10838     // then for the whole array. It's possible we may find out we can't do const
10839     // init in the first pass, in which case we avoid allocating a potentially
10840     // large array. We don't do more passes because expanding array requires
10841     // copying the data, which is wasteful.
10842     for (const unsigned N : {1u, FinalSize}) {
10843       unsigned OldElts = Value->getArrayInitializedElts();
10844       if (OldElts == N)
10845         break;
10846 
10847       // Expand the array to appropriate size.
10848       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10849       for (unsigned I = 0; I < OldElts; ++I)
10850         NewValue.getArrayInitializedElt(I).swap(
10851             Value->getArrayInitializedElt(I));
10852       Value->swap(NewValue);
10853 
10854       if (HadZeroInit)
10855         for (unsigned I = OldElts; I < N; ++I)
10856           Value->getArrayInitializedElt(I) = Filler;
10857 
10858       // Initialize the elements.
10859       for (unsigned I = OldElts; I < N; ++I) {
10860         if (!VisitCXXConstructExpr(E, ArrayElt,
10861                                    &Value->getArrayInitializedElt(I),
10862                                    CAT->getElementType()) ||
10863             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10864                                          CAT->getElementType(), 1))
10865           return false;
10866         // When checking for const initilization any diagnostic is considered
10867         // an error.
10868         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10869             !Info.keepEvaluatingAfterFailure())
10870           return false;
10871       }
10872     }
10873 
10874     return true;
10875   }
10876 
10877   if (!Type->isRecordType())
10878     return Error(E);
10879 
10880   return RecordExprEvaluator(Info, Subobject, *Value)
10881              .VisitCXXConstructExpr(E, Type);
10882 }
10883 
10884 //===----------------------------------------------------------------------===//
10885 // Integer Evaluation
10886 //
10887 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10888 // types and back in constant folding. Integer values are thus represented
10889 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10890 //===----------------------------------------------------------------------===//
10891 
10892 namespace {
10893 class IntExprEvaluator
10894         : public ExprEvaluatorBase<IntExprEvaluator> {
10895   APValue &Result;
10896 public:
10897   IntExprEvaluator(EvalInfo &info, APValue &result)
10898       : ExprEvaluatorBaseTy(info), Result(result) {}
10899 
10900   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10901     assert(E->getType()->isIntegralOrEnumerationType() &&
10902            "Invalid evaluation result.");
10903     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10904            "Invalid evaluation result.");
10905     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10906            "Invalid evaluation result.");
10907     Result = APValue(SI);
10908     return true;
10909   }
10910   bool Success(const llvm::APSInt &SI, const Expr *E) {
10911     return Success(SI, E, Result);
10912   }
10913 
10914   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10915     assert(E->getType()->isIntegralOrEnumerationType() &&
10916            "Invalid evaluation result.");
10917     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10918            "Invalid evaluation result.");
10919     Result = APValue(APSInt(I));
10920     Result.getInt().setIsUnsigned(
10921                             E->getType()->isUnsignedIntegerOrEnumerationType());
10922     return true;
10923   }
10924   bool Success(const llvm::APInt &I, const Expr *E) {
10925     return Success(I, E, Result);
10926   }
10927 
10928   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10929     assert(E->getType()->isIntegralOrEnumerationType() &&
10930            "Invalid evaluation result.");
10931     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10932     return true;
10933   }
10934   bool Success(uint64_t Value, const Expr *E) {
10935     return Success(Value, E, Result);
10936   }
10937 
10938   bool Success(CharUnits Size, const Expr *E) {
10939     return Success(Size.getQuantity(), E);
10940   }
10941 
10942   bool Success(const APValue &V, const Expr *E) {
10943     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10944       Result = V;
10945       return true;
10946     }
10947     return Success(V.getInt(), E);
10948   }
10949 
10950   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10951 
10952   //===--------------------------------------------------------------------===//
10953   //                            Visitor Methods
10954   //===--------------------------------------------------------------------===//
10955 
10956   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10957     return Success(E->getValue(), E);
10958   }
10959   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10960     return Success(E->getValue(), E);
10961   }
10962 
10963   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10964   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10965     if (CheckReferencedDecl(E, E->getDecl()))
10966       return true;
10967 
10968     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10969   }
10970   bool VisitMemberExpr(const MemberExpr *E) {
10971     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10972       VisitIgnoredBaseExpression(E->getBase());
10973       return true;
10974     }
10975 
10976     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10977   }
10978 
10979   bool VisitCallExpr(const CallExpr *E);
10980   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10981   bool VisitBinaryOperator(const BinaryOperator *E);
10982   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10983   bool VisitUnaryOperator(const UnaryOperator *E);
10984 
10985   bool VisitCastExpr(const CastExpr* E);
10986   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10987 
10988   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10989     return Success(E->getValue(), E);
10990   }
10991 
10992   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10993     return Success(E->getValue(), E);
10994   }
10995 
10996   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10997     if (Info.ArrayInitIndex == uint64_t(-1)) {
10998       // We were asked to evaluate this subexpression independent of the
10999       // enclosing ArrayInitLoopExpr. We can't do that.
11000       Info.FFDiag(E);
11001       return false;
11002     }
11003     return Success(Info.ArrayInitIndex, E);
11004   }
11005 
11006   // Note, GNU defines __null as an integer, not a pointer.
11007   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11008     return ZeroInitialization(E);
11009   }
11010 
11011   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11012     return Success(E->getValue(), E);
11013   }
11014 
11015   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11016     return Success(E->getValue(), E);
11017   }
11018 
11019   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11020     return Success(E->getValue(), E);
11021   }
11022 
11023   bool VisitUnaryReal(const UnaryOperator *E);
11024   bool VisitUnaryImag(const UnaryOperator *E);
11025 
11026   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11027   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11028   bool VisitSourceLocExpr(const SourceLocExpr *E);
11029   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11030   bool VisitRequiresExpr(const RequiresExpr *E);
11031   // FIXME: Missing: array subscript of vector, member of vector
11032 };
11033 
11034 class FixedPointExprEvaluator
11035     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11036   APValue &Result;
11037 
11038  public:
11039   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11040       : ExprEvaluatorBaseTy(info), Result(result) {}
11041 
11042   bool Success(const llvm::APInt &I, const Expr *E) {
11043     return Success(
11044         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11045   }
11046 
11047   bool Success(uint64_t Value, const Expr *E) {
11048     return Success(
11049         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11050   }
11051 
11052   bool Success(const APValue &V, const Expr *E) {
11053     return Success(V.getFixedPoint(), E);
11054   }
11055 
11056   bool Success(const APFixedPoint &V, const Expr *E) {
11057     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11058     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11059            "Invalid evaluation result.");
11060     Result = APValue(V);
11061     return true;
11062   }
11063 
11064   //===--------------------------------------------------------------------===//
11065   //                            Visitor Methods
11066   //===--------------------------------------------------------------------===//
11067 
11068   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11069     return Success(E->getValue(), E);
11070   }
11071 
11072   bool VisitCastExpr(const CastExpr *E);
11073   bool VisitUnaryOperator(const UnaryOperator *E);
11074   bool VisitBinaryOperator(const BinaryOperator *E);
11075 };
11076 } // end anonymous namespace
11077 
11078 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11079 /// produce either the integer value or a pointer.
11080 ///
11081 /// GCC has a heinous extension which folds casts between pointer types and
11082 /// pointer-sized integral types. We support this by allowing the evaluation of
11083 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11084 /// Some simple arithmetic on such values is supported (they are treated much
11085 /// like char*).
11086 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11087                                     EvalInfo &Info) {
11088   assert(!E->isValueDependent());
11089   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11090   return IntExprEvaluator(Info, Result).Visit(E);
11091 }
11092 
11093 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11094   assert(!E->isValueDependent());
11095   APValue Val;
11096   if (!EvaluateIntegerOrLValue(E, Val, Info))
11097     return false;
11098   if (!Val.isInt()) {
11099     // FIXME: It would be better to produce the diagnostic for casting
11100     //        a pointer to an integer.
11101     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11102     return false;
11103   }
11104   Result = Val.getInt();
11105   return true;
11106 }
11107 
11108 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11109   APValue Evaluated = E->EvaluateInContext(
11110       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11111   return Success(Evaluated, E);
11112 }
11113 
11114 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11115                                EvalInfo &Info) {
11116   assert(!E->isValueDependent());
11117   if (E->getType()->isFixedPointType()) {
11118     APValue Val;
11119     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11120       return false;
11121     if (!Val.isFixedPoint())
11122       return false;
11123 
11124     Result = Val.getFixedPoint();
11125     return true;
11126   }
11127   return false;
11128 }
11129 
11130 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11131                                         EvalInfo &Info) {
11132   assert(!E->isValueDependent());
11133   if (E->getType()->isIntegerType()) {
11134     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11135     APSInt Val;
11136     if (!EvaluateInteger(E, Val, Info))
11137       return false;
11138     Result = APFixedPoint(Val, FXSema);
11139     return true;
11140   } else if (E->getType()->isFixedPointType()) {
11141     return EvaluateFixedPoint(E, Result, Info);
11142   }
11143   return false;
11144 }
11145 
11146 /// Check whether the given declaration can be directly converted to an integral
11147 /// rvalue. If not, no diagnostic is produced; there are other things we can
11148 /// try.
11149 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11150   // Enums are integer constant exprs.
11151   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11152     // Check for signedness/width mismatches between E type and ECD value.
11153     bool SameSign = (ECD->getInitVal().isSigned()
11154                      == E->getType()->isSignedIntegerOrEnumerationType());
11155     bool SameWidth = (ECD->getInitVal().getBitWidth()
11156                       == Info.Ctx.getIntWidth(E->getType()));
11157     if (SameSign && SameWidth)
11158       return Success(ECD->getInitVal(), E);
11159     else {
11160       // Get rid of mismatch (otherwise Success assertions will fail)
11161       // by computing a new value matching the type of E.
11162       llvm::APSInt Val = ECD->getInitVal();
11163       if (!SameSign)
11164         Val.setIsSigned(!ECD->getInitVal().isSigned());
11165       if (!SameWidth)
11166         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11167       return Success(Val, E);
11168     }
11169   }
11170   return false;
11171 }
11172 
11173 /// Values returned by __builtin_classify_type, chosen to match the values
11174 /// produced by GCC's builtin.
11175 enum class GCCTypeClass {
11176   None = -1,
11177   Void = 0,
11178   Integer = 1,
11179   // GCC reserves 2 for character types, but instead classifies them as
11180   // integers.
11181   Enum = 3,
11182   Bool = 4,
11183   Pointer = 5,
11184   // GCC reserves 6 for references, but appears to never use it (because
11185   // expressions never have reference type, presumably).
11186   PointerToDataMember = 7,
11187   RealFloat = 8,
11188   Complex = 9,
11189   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11190   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11191   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11192   // uses 12 for that purpose, same as for a class or struct. Maybe it
11193   // internally implements a pointer to member as a struct?  Who knows.
11194   PointerToMemberFunction = 12, // Not a bug, see above.
11195   ClassOrStruct = 12,
11196   Union = 13,
11197   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11198   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11199   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11200   // literals.
11201 };
11202 
11203 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11204 /// as GCC.
11205 static GCCTypeClass
11206 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11207   assert(!T->isDependentType() && "unexpected dependent type");
11208 
11209   QualType CanTy = T.getCanonicalType();
11210   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11211 
11212   switch (CanTy->getTypeClass()) {
11213 #define TYPE(ID, BASE)
11214 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11215 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11216 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11217 #include "clang/AST/TypeNodes.inc"
11218   case Type::Auto:
11219   case Type::DeducedTemplateSpecialization:
11220       llvm_unreachable("unexpected non-canonical or dependent type");
11221 
11222   case Type::Builtin:
11223     switch (BT->getKind()) {
11224 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11225 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11226     case BuiltinType::ID: return GCCTypeClass::Integer;
11227 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11228     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11229 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11230     case BuiltinType::ID: break;
11231 #include "clang/AST/BuiltinTypes.def"
11232     case BuiltinType::Void:
11233       return GCCTypeClass::Void;
11234 
11235     case BuiltinType::Bool:
11236       return GCCTypeClass::Bool;
11237 
11238     case BuiltinType::Char_U:
11239     case BuiltinType::UChar:
11240     case BuiltinType::WChar_U:
11241     case BuiltinType::Char8:
11242     case BuiltinType::Char16:
11243     case BuiltinType::Char32:
11244     case BuiltinType::UShort:
11245     case BuiltinType::UInt:
11246     case BuiltinType::ULong:
11247     case BuiltinType::ULongLong:
11248     case BuiltinType::UInt128:
11249       return GCCTypeClass::Integer;
11250 
11251     case BuiltinType::UShortAccum:
11252     case BuiltinType::UAccum:
11253     case BuiltinType::ULongAccum:
11254     case BuiltinType::UShortFract:
11255     case BuiltinType::UFract:
11256     case BuiltinType::ULongFract:
11257     case BuiltinType::SatUShortAccum:
11258     case BuiltinType::SatUAccum:
11259     case BuiltinType::SatULongAccum:
11260     case BuiltinType::SatUShortFract:
11261     case BuiltinType::SatUFract:
11262     case BuiltinType::SatULongFract:
11263       return GCCTypeClass::None;
11264 
11265     case BuiltinType::NullPtr:
11266 
11267     case BuiltinType::ObjCId:
11268     case BuiltinType::ObjCClass:
11269     case BuiltinType::ObjCSel:
11270 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11271     case BuiltinType::Id:
11272 #include "clang/Basic/OpenCLImageTypes.def"
11273 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11274     case BuiltinType::Id:
11275 #include "clang/Basic/OpenCLExtensionTypes.def"
11276     case BuiltinType::OCLSampler:
11277     case BuiltinType::OCLEvent:
11278     case BuiltinType::OCLClkEvent:
11279     case BuiltinType::OCLQueue:
11280     case BuiltinType::OCLReserveID:
11281 #define SVE_TYPE(Name, Id, SingletonId) \
11282     case BuiltinType::Id:
11283 #include "clang/Basic/AArch64SVEACLETypes.def"
11284 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11285     case BuiltinType::Id:
11286 #include "clang/Basic/PPCTypes.def"
11287 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11288 #include "clang/Basic/RISCVVTypes.def"
11289       return GCCTypeClass::None;
11290 
11291     case BuiltinType::Dependent:
11292       llvm_unreachable("unexpected dependent type");
11293     };
11294     llvm_unreachable("unexpected placeholder type");
11295 
11296   case Type::Enum:
11297     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11298 
11299   case Type::Pointer:
11300   case Type::ConstantArray:
11301   case Type::VariableArray:
11302   case Type::IncompleteArray:
11303   case Type::FunctionNoProto:
11304   case Type::FunctionProto:
11305     return GCCTypeClass::Pointer;
11306 
11307   case Type::MemberPointer:
11308     return CanTy->isMemberDataPointerType()
11309                ? GCCTypeClass::PointerToDataMember
11310                : GCCTypeClass::PointerToMemberFunction;
11311 
11312   case Type::Complex:
11313     return GCCTypeClass::Complex;
11314 
11315   case Type::Record:
11316     return CanTy->isUnionType() ? GCCTypeClass::Union
11317                                 : GCCTypeClass::ClassOrStruct;
11318 
11319   case Type::Atomic:
11320     // GCC classifies _Atomic T the same as T.
11321     return EvaluateBuiltinClassifyType(
11322         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11323 
11324   case Type::BlockPointer:
11325   case Type::Vector:
11326   case Type::ExtVector:
11327   case Type::ConstantMatrix:
11328   case Type::ObjCObject:
11329   case Type::ObjCInterface:
11330   case Type::ObjCObjectPointer:
11331   case Type::Pipe:
11332   case Type::BitInt:
11333     // GCC classifies vectors as None. We follow its lead and classify all
11334     // other types that don't fit into the regular classification the same way.
11335     return GCCTypeClass::None;
11336 
11337   case Type::LValueReference:
11338   case Type::RValueReference:
11339     llvm_unreachable("invalid type for expression");
11340   }
11341 
11342   llvm_unreachable("unexpected type class");
11343 }
11344 
11345 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11346 /// as GCC.
11347 static GCCTypeClass
11348 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11349   // If no argument was supplied, default to None. This isn't
11350   // ideal, however it is what gcc does.
11351   if (E->getNumArgs() == 0)
11352     return GCCTypeClass::None;
11353 
11354   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11355   // being an ICE, but still folds it to a constant using the type of the first
11356   // argument.
11357   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11358 }
11359 
11360 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11361 /// __builtin_constant_p when applied to the given pointer.
11362 ///
11363 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11364 /// or it points to the first character of a string literal.
11365 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11366   APValue::LValueBase Base = LV.getLValueBase();
11367   if (Base.isNull()) {
11368     // A null base is acceptable.
11369     return true;
11370   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11371     if (!isa<StringLiteral>(E))
11372       return false;
11373     return LV.getLValueOffset().isZero();
11374   } else if (Base.is<TypeInfoLValue>()) {
11375     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11376     // evaluate to true.
11377     return true;
11378   } else {
11379     // Any other base is not constant enough for GCC.
11380     return false;
11381   }
11382 }
11383 
11384 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11385 /// GCC as we can manage.
11386 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11387   // This evaluation is not permitted to have side-effects, so evaluate it in
11388   // a speculative evaluation context.
11389   SpeculativeEvaluationRAII SpeculativeEval(Info);
11390 
11391   // Constant-folding is always enabled for the operand of __builtin_constant_p
11392   // (even when the enclosing evaluation context otherwise requires a strict
11393   // language-specific constant expression).
11394   FoldConstant Fold(Info, true);
11395 
11396   QualType ArgType = Arg->getType();
11397 
11398   // __builtin_constant_p always has one operand. The rules which gcc follows
11399   // are not precisely documented, but are as follows:
11400   //
11401   //  - If the operand is of integral, floating, complex or enumeration type,
11402   //    and can be folded to a known value of that type, it returns 1.
11403   //  - If the operand can be folded to a pointer to the first character
11404   //    of a string literal (or such a pointer cast to an integral type)
11405   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11406   //
11407   // Otherwise, it returns 0.
11408   //
11409   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11410   // its support for this did not work prior to GCC 9 and is not yet well
11411   // understood.
11412   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11413       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11414       ArgType->isNullPtrType()) {
11415     APValue V;
11416     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11417       Fold.keepDiagnostics();
11418       return false;
11419     }
11420 
11421     // For a pointer (possibly cast to integer), there are special rules.
11422     if (V.getKind() == APValue::LValue)
11423       return EvaluateBuiltinConstantPForLValue(V);
11424 
11425     // Otherwise, any constant value is good enough.
11426     return V.hasValue();
11427   }
11428 
11429   // Anything else isn't considered to be sufficiently constant.
11430   return false;
11431 }
11432 
11433 /// Retrieves the "underlying object type" of the given expression,
11434 /// as used by __builtin_object_size.
11435 static QualType getObjectType(APValue::LValueBase B) {
11436   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11437     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11438       return VD->getType();
11439   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11440     if (isa<CompoundLiteralExpr>(E))
11441       return E->getType();
11442   } else if (B.is<TypeInfoLValue>()) {
11443     return B.getTypeInfoType();
11444   } else if (B.is<DynamicAllocLValue>()) {
11445     return B.getDynamicAllocType();
11446   }
11447 
11448   return QualType();
11449 }
11450 
11451 /// A more selective version of E->IgnoreParenCasts for
11452 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11453 /// to change the type of E.
11454 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11455 ///
11456 /// Always returns an RValue with a pointer representation.
11457 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11458   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11459 
11460   auto *NoParens = E->IgnoreParens();
11461   auto *Cast = dyn_cast<CastExpr>(NoParens);
11462   if (Cast == nullptr)
11463     return NoParens;
11464 
11465   // We only conservatively allow a few kinds of casts, because this code is
11466   // inherently a simple solution that seeks to support the common case.
11467   auto CastKind = Cast->getCastKind();
11468   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11469       CastKind != CK_AddressSpaceConversion)
11470     return NoParens;
11471 
11472   auto *SubExpr = Cast->getSubExpr();
11473   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11474     return NoParens;
11475   return ignorePointerCastsAndParens(SubExpr);
11476 }
11477 
11478 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11479 /// record layout. e.g.
11480 ///   struct { struct { int a, b; } fst, snd; } obj;
11481 ///   obj.fst   // no
11482 ///   obj.snd   // yes
11483 ///   obj.fst.a // no
11484 ///   obj.fst.b // no
11485 ///   obj.snd.a // no
11486 ///   obj.snd.b // yes
11487 ///
11488 /// Please note: this function is specialized for how __builtin_object_size
11489 /// views "objects".
11490 ///
11491 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11492 /// correct result, it will always return true.
11493 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11494   assert(!LVal.Designator.Invalid);
11495 
11496   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11497     const RecordDecl *Parent = FD->getParent();
11498     Invalid = Parent->isInvalidDecl();
11499     if (Invalid || Parent->isUnion())
11500       return true;
11501     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11502     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11503   };
11504 
11505   auto &Base = LVal.getLValueBase();
11506   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11507     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11508       bool Invalid;
11509       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11510         return Invalid;
11511     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11512       for (auto *FD : IFD->chain()) {
11513         bool Invalid;
11514         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11515           return Invalid;
11516       }
11517     }
11518   }
11519 
11520   unsigned I = 0;
11521   QualType BaseType = getType(Base);
11522   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11523     // If we don't know the array bound, conservatively assume we're looking at
11524     // the final array element.
11525     ++I;
11526     if (BaseType->isIncompleteArrayType())
11527       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11528     else
11529       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11530   }
11531 
11532   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11533     const auto &Entry = LVal.Designator.Entries[I];
11534     if (BaseType->isArrayType()) {
11535       // Because __builtin_object_size treats arrays as objects, we can ignore
11536       // the index iff this is the last array in the Designator.
11537       if (I + 1 == E)
11538         return true;
11539       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11540       uint64_t Index = Entry.getAsArrayIndex();
11541       if (Index + 1 != CAT->getSize())
11542         return false;
11543       BaseType = CAT->getElementType();
11544     } else if (BaseType->isAnyComplexType()) {
11545       const auto *CT = BaseType->castAs<ComplexType>();
11546       uint64_t Index = Entry.getAsArrayIndex();
11547       if (Index != 1)
11548         return false;
11549       BaseType = CT->getElementType();
11550     } else if (auto *FD = getAsField(Entry)) {
11551       bool Invalid;
11552       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11553         return Invalid;
11554       BaseType = FD->getType();
11555     } else {
11556       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11557       return false;
11558     }
11559   }
11560   return true;
11561 }
11562 
11563 /// Tests to see if the LValue has a user-specified designator (that isn't
11564 /// necessarily valid). Note that this always returns 'true' if the LValue has
11565 /// an unsized array as its first designator entry, because there's currently no
11566 /// way to tell if the user typed *foo or foo[0].
11567 static bool refersToCompleteObject(const LValue &LVal) {
11568   if (LVal.Designator.Invalid)
11569     return false;
11570 
11571   if (!LVal.Designator.Entries.empty())
11572     return LVal.Designator.isMostDerivedAnUnsizedArray();
11573 
11574   if (!LVal.InvalidBase)
11575     return true;
11576 
11577   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11578   // the LValueBase.
11579   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11580   return !E || !isa<MemberExpr>(E);
11581 }
11582 
11583 /// Attempts to detect a user writing into a piece of memory that's impossible
11584 /// to figure out the size of by just using types.
11585 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11586   const SubobjectDesignator &Designator = LVal.Designator;
11587   // Notes:
11588   // - Users can only write off of the end when we have an invalid base. Invalid
11589   //   bases imply we don't know where the memory came from.
11590   // - We used to be a bit more aggressive here; we'd only be conservative if
11591   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11592   //   broke some common standard library extensions (PR30346), but was
11593   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11594   //   with some sort of list. OTOH, it seems that GCC is always
11595   //   conservative with the last element in structs (if it's an array), so our
11596   //   current behavior is more compatible than an explicit list approach would
11597   //   be.
11598   return LVal.InvalidBase &&
11599          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11600          Designator.MostDerivedIsArrayElement &&
11601          isDesignatorAtObjectEnd(Ctx, LVal);
11602 }
11603 
11604 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11605 /// Fails if the conversion would cause loss of precision.
11606 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11607                                             CharUnits &Result) {
11608   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11609   if (Int.ugt(CharUnitsMax))
11610     return false;
11611   Result = CharUnits::fromQuantity(Int.getZExtValue());
11612   return true;
11613 }
11614 
11615 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11616 /// determine how many bytes exist from the beginning of the object to either
11617 /// the end of the current subobject, or the end of the object itself, depending
11618 /// on what the LValue looks like + the value of Type.
11619 ///
11620 /// If this returns false, the value of Result is undefined.
11621 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11622                                unsigned Type, const LValue &LVal,
11623                                CharUnits &EndOffset) {
11624   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11625 
11626   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11627     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11628       return false;
11629     return HandleSizeof(Info, ExprLoc, Ty, Result);
11630   };
11631 
11632   // We want to evaluate the size of the entire object. This is a valid fallback
11633   // for when Type=1 and the designator is invalid, because we're asked for an
11634   // upper-bound.
11635   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11636     // Type=3 wants a lower bound, so we can't fall back to this.
11637     if (Type == 3 && !DetermineForCompleteObject)
11638       return false;
11639 
11640     llvm::APInt APEndOffset;
11641     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11642         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11643       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11644 
11645     if (LVal.InvalidBase)
11646       return false;
11647 
11648     QualType BaseTy = getObjectType(LVal.getLValueBase());
11649     return CheckedHandleSizeof(BaseTy, EndOffset);
11650   }
11651 
11652   // We want to evaluate the size of a subobject.
11653   const SubobjectDesignator &Designator = LVal.Designator;
11654 
11655   // The following is a moderately common idiom in C:
11656   //
11657   // struct Foo { int a; char c[1]; };
11658   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11659   // strcpy(&F->c[0], Bar);
11660   //
11661   // In order to not break too much legacy code, we need to support it.
11662   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11663     // If we can resolve this to an alloc_size call, we can hand that back,
11664     // because we know for certain how many bytes there are to write to.
11665     llvm::APInt APEndOffset;
11666     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11667         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11668       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11669 
11670     // If we cannot determine the size of the initial allocation, then we can't
11671     // given an accurate upper-bound. However, we are still able to give
11672     // conservative lower-bounds for Type=3.
11673     if (Type == 1)
11674       return false;
11675   }
11676 
11677   CharUnits BytesPerElem;
11678   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11679     return false;
11680 
11681   // According to the GCC documentation, we want the size of the subobject
11682   // denoted by the pointer. But that's not quite right -- what we actually
11683   // want is the size of the immediately-enclosing array, if there is one.
11684   int64_t ElemsRemaining;
11685   if (Designator.MostDerivedIsArrayElement &&
11686       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11687     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11688     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11689     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11690   } else {
11691     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11692   }
11693 
11694   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11695   return true;
11696 }
11697 
11698 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11699 /// returns true and stores the result in @p Size.
11700 ///
11701 /// If @p WasError is non-null, this will report whether the failure to evaluate
11702 /// is to be treated as an Error in IntExprEvaluator.
11703 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11704                                          EvalInfo &Info, uint64_t &Size) {
11705   // Determine the denoted object.
11706   LValue LVal;
11707   {
11708     // The operand of __builtin_object_size is never evaluated for side-effects.
11709     // If there are any, but we can determine the pointed-to object anyway, then
11710     // ignore the side-effects.
11711     SpeculativeEvaluationRAII SpeculativeEval(Info);
11712     IgnoreSideEffectsRAII Fold(Info);
11713 
11714     if (E->isGLValue()) {
11715       // It's possible for us to be given GLValues if we're called via
11716       // Expr::tryEvaluateObjectSize.
11717       APValue RVal;
11718       if (!EvaluateAsRValue(Info, E, RVal))
11719         return false;
11720       LVal.setFrom(Info.Ctx, RVal);
11721     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11722                                 /*InvalidBaseOK=*/true))
11723       return false;
11724   }
11725 
11726   // If we point to before the start of the object, there are no accessible
11727   // bytes.
11728   if (LVal.getLValueOffset().isNegative()) {
11729     Size = 0;
11730     return true;
11731   }
11732 
11733   CharUnits EndOffset;
11734   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11735     return false;
11736 
11737   // If we've fallen outside of the end offset, just pretend there's nothing to
11738   // write to/read from.
11739   if (EndOffset <= LVal.getLValueOffset())
11740     Size = 0;
11741   else
11742     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11743   return true;
11744 }
11745 
11746 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11747   if (unsigned BuiltinOp = E->getBuiltinCallee())
11748     return VisitBuiltinCallExpr(E, BuiltinOp);
11749 
11750   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11751 }
11752 
11753 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11754                                      APValue &Val, APSInt &Alignment) {
11755   QualType SrcTy = E->getArg(0)->getType();
11756   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11757     return false;
11758   // Even though we are evaluating integer expressions we could get a pointer
11759   // argument for the __builtin_is_aligned() case.
11760   if (SrcTy->isPointerType()) {
11761     LValue Ptr;
11762     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11763       return false;
11764     Ptr.moveInto(Val);
11765   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11766     Info.FFDiag(E->getArg(0));
11767     return false;
11768   } else {
11769     APSInt SrcInt;
11770     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11771       return false;
11772     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11773            "Bit widths must be the same");
11774     Val = APValue(SrcInt);
11775   }
11776   assert(Val.hasValue());
11777   return true;
11778 }
11779 
11780 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11781                                             unsigned BuiltinOp) {
11782   switch (BuiltinOp) {
11783   default:
11784     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11785 
11786   case Builtin::BI__builtin_dynamic_object_size:
11787   case Builtin::BI__builtin_object_size: {
11788     // The type was checked when we built the expression.
11789     unsigned Type =
11790         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11791     assert(Type <= 3 && "unexpected type");
11792 
11793     uint64_t Size;
11794     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11795       return Success(Size, E);
11796 
11797     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11798       return Success((Type & 2) ? 0 : -1, E);
11799 
11800     // Expression had no side effects, but we couldn't statically determine the
11801     // size of the referenced object.
11802     switch (Info.EvalMode) {
11803     case EvalInfo::EM_ConstantExpression:
11804     case EvalInfo::EM_ConstantFold:
11805     case EvalInfo::EM_IgnoreSideEffects:
11806       // Leave it to IR generation.
11807       return Error(E);
11808     case EvalInfo::EM_ConstantExpressionUnevaluated:
11809       // Reduce it to a constant now.
11810       return Success((Type & 2) ? 0 : -1, E);
11811     }
11812 
11813     llvm_unreachable("unexpected EvalMode");
11814   }
11815 
11816   case Builtin::BI__builtin_os_log_format_buffer_size: {
11817     analyze_os_log::OSLogBufferLayout Layout;
11818     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11819     return Success(Layout.size().getQuantity(), E);
11820   }
11821 
11822   case Builtin::BI__builtin_is_aligned: {
11823     APValue Src;
11824     APSInt Alignment;
11825     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11826       return false;
11827     if (Src.isLValue()) {
11828       // If we evaluated a pointer, check the minimum known alignment.
11829       LValue Ptr;
11830       Ptr.setFrom(Info.Ctx, Src);
11831       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11832       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11833       // We can return true if the known alignment at the computed offset is
11834       // greater than the requested alignment.
11835       assert(PtrAlign.isPowerOfTwo());
11836       assert(Alignment.isPowerOf2());
11837       if (PtrAlign.getQuantity() >= Alignment)
11838         return Success(1, E);
11839       // If the alignment is not known to be sufficient, some cases could still
11840       // be aligned at run time. However, if the requested alignment is less or
11841       // equal to the base alignment and the offset is not aligned, we know that
11842       // the run-time value can never be aligned.
11843       if (BaseAlignment.getQuantity() >= Alignment &&
11844           PtrAlign.getQuantity() < Alignment)
11845         return Success(0, E);
11846       // Otherwise we can't infer whether the value is sufficiently aligned.
11847       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11848       //  in cases where we can't fully evaluate the pointer.
11849       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11850           << Alignment;
11851       return false;
11852     }
11853     assert(Src.isInt());
11854     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11855   }
11856   case Builtin::BI__builtin_align_up: {
11857     APValue Src;
11858     APSInt Alignment;
11859     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11860       return false;
11861     if (!Src.isInt())
11862       return Error(E);
11863     APSInt AlignedVal =
11864         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11865                Src.getInt().isUnsigned());
11866     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11867     return Success(AlignedVal, E);
11868   }
11869   case Builtin::BI__builtin_align_down: {
11870     APValue Src;
11871     APSInt Alignment;
11872     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11873       return false;
11874     if (!Src.isInt())
11875       return Error(E);
11876     APSInt AlignedVal =
11877         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11878     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11879     return Success(AlignedVal, E);
11880   }
11881 
11882   case Builtin::BI__builtin_bitreverse8:
11883   case Builtin::BI__builtin_bitreverse16:
11884   case Builtin::BI__builtin_bitreverse32:
11885   case Builtin::BI__builtin_bitreverse64: {
11886     APSInt Val;
11887     if (!EvaluateInteger(E->getArg(0), Val, Info))
11888       return false;
11889 
11890     return Success(Val.reverseBits(), E);
11891   }
11892 
11893   case Builtin::BI__builtin_bswap16:
11894   case Builtin::BI__builtin_bswap32:
11895   case Builtin::BI__builtin_bswap64: {
11896     APSInt Val;
11897     if (!EvaluateInteger(E->getArg(0), Val, Info))
11898       return false;
11899 
11900     return Success(Val.byteSwap(), E);
11901   }
11902 
11903   case Builtin::BI__builtin_classify_type:
11904     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11905 
11906   case Builtin::BI__builtin_clrsb:
11907   case Builtin::BI__builtin_clrsbl:
11908   case Builtin::BI__builtin_clrsbll: {
11909     APSInt Val;
11910     if (!EvaluateInteger(E->getArg(0), Val, Info))
11911       return false;
11912 
11913     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11914   }
11915 
11916   case Builtin::BI__builtin_clz:
11917   case Builtin::BI__builtin_clzl:
11918   case Builtin::BI__builtin_clzll:
11919   case Builtin::BI__builtin_clzs: {
11920     APSInt Val;
11921     if (!EvaluateInteger(E->getArg(0), Val, Info))
11922       return false;
11923     if (!Val)
11924       return Error(E);
11925 
11926     return Success(Val.countLeadingZeros(), E);
11927   }
11928 
11929   case Builtin::BI__builtin_constant_p: {
11930     const Expr *Arg = E->getArg(0);
11931     if (EvaluateBuiltinConstantP(Info, Arg))
11932       return Success(true, E);
11933     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11934       // Outside a constant context, eagerly evaluate to false in the presence
11935       // of side-effects in order to avoid -Wunsequenced false-positives in
11936       // a branch on __builtin_constant_p(expr).
11937       return Success(false, E);
11938     }
11939     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11940     return false;
11941   }
11942 
11943   case Builtin::BI__builtin_is_constant_evaluated: {
11944     const auto *Callee = Info.CurrentCall->getCallee();
11945     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11946         (Info.CallStackDepth == 1 ||
11947          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11948           Callee->getIdentifier() &&
11949           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11950       // FIXME: Find a better way to avoid duplicated diagnostics.
11951       if (Info.EvalStatus.Diag)
11952         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11953                                                : Info.CurrentCall->CallLoc,
11954                     diag::warn_is_constant_evaluated_always_true_constexpr)
11955             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11956                                          : "std::is_constant_evaluated");
11957     }
11958 
11959     return Success(Info.InConstantContext, E);
11960   }
11961 
11962   case Builtin::BI__builtin_ctz:
11963   case Builtin::BI__builtin_ctzl:
11964   case Builtin::BI__builtin_ctzll:
11965   case Builtin::BI__builtin_ctzs: {
11966     APSInt Val;
11967     if (!EvaluateInteger(E->getArg(0), Val, Info))
11968       return false;
11969     if (!Val)
11970       return Error(E);
11971 
11972     return Success(Val.countTrailingZeros(), E);
11973   }
11974 
11975   case Builtin::BI__builtin_eh_return_data_regno: {
11976     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11977     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11978     return Success(Operand, E);
11979   }
11980 
11981   case Builtin::BI__builtin_expect:
11982   case Builtin::BI__builtin_expect_with_probability:
11983     return Visit(E->getArg(0));
11984 
11985   case Builtin::BI__builtin_ffs:
11986   case Builtin::BI__builtin_ffsl:
11987   case Builtin::BI__builtin_ffsll: {
11988     APSInt Val;
11989     if (!EvaluateInteger(E->getArg(0), Val, Info))
11990       return false;
11991 
11992     unsigned N = Val.countTrailingZeros();
11993     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11994   }
11995 
11996   case Builtin::BI__builtin_fpclassify: {
11997     APFloat Val(0.0);
11998     if (!EvaluateFloat(E->getArg(5), Val, Info))
11999       return false;
12000     unsigned Arg;
12001     switch (Val.getCategory()) {
12002     case APFloat::fcNaN: Arg = 0; break;
12003     case APFloat::fcInfinity: Arg = 1; break;
12004     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12005     case APFloat::fcZero: Arg = 4; break;
12006     }
12007     return Visit(E->getArg(Arg));
12008   }
12009 
12010   case Builtin::BI__builtin_isinf_sign: {
12011     APFloat Val(0.0);
12012     return EvaluateFloat(E->getArg(0), Val, Info) &&
12013            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12014   }
12015 
12016   case Builtin::BI__builtin_isinf: {
12017     APFloat Val(0.0);
12018     return EvaluateFloat(E->getArg(0), Val, Info) &&
12019            Success(Val.isInfinity() ? 1 : 0, E);
12020   }
12021 
12022   case Builtin::BI__builtin_isfinite: {
12023     APFloat Val(0.0);
12024     return EvaluateFloat(E->getArg(0), Val, Info) &&
12025            Success(Val.isFinite() ? 1 : 0, E);
12026   }
12027 
12028   case Builtin::BI__builtin_isnan: {
12029     APFloat Val(0.0);
12030     return EvaluateFloat(E->getArg(0), Val, Info) &&
12031            Success(Val.isNaN() ? 1 : 0, E);
12032   }
12033 
12034   case Builtin::BI__builtin_isnormal: {
12035     APFloat Val(0.0);
12036     return EvaluateFloat(E->getArg(0), Val, Info) &&
12037            Success(Val.isNormal() ? 1 : 0, E);
12038   }
12039 
12040   case Builtin::BI__builtin_parity:
12041   case Builtin::BI__builtin_parityl:
12042   case Builtin::BI__builtin_parityll: {
12043     APSInt Val;
12044     if (!EvaluateInteger(E->getArg(0), Val, Info))
12045       return false;
12046 
12047     return Success(Val.countPopulation() % 2, E);
12048   }
12049 
12050   case Builtin::BI__builtin_popcount:
12051   case Builtin::BI__builtin_popcountl:
12052   case Builtin::BI__builtin_popcountll: {
12053     APSInt Val;
12054     if (!EvaluateInteger(E->getArg(0), Val, Info))
12055       return false;
12056 
12057     return Success(Val.countPopulation(), E);
12058   }
12059 
12060   case Builtin::BI__builtin_rotateleft8:
12061   case Builtin::BI__builtin_rotateleft16:
12062   case Builtin::BI__builtin_rotateleft32:
12063   case Builtin::BI__builtin_rotateleft64:
12064   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12065   case Builtin::BI_rotl16:
12066   case Builtin::BI_rotl:
12067   case Builtin::BI_lrotl:
12068   case Builtin::BI_rotl64: {
12069     APSInt Val, Amt;
12070     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12071         !EvaluateInteger(E->getArg(1), Amt, Info))
12072       return false;
12073 
12074     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12075   }
12076 
12077   case Builtin::BI__builtin_rotateright8:
12078   case Builtin::BI__builtin_rotateright16:
12079   case Builtin::BI__builtin_rotateright32:
12080   case Builtin::BI__builtin_rotateright64:
12081   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12082   case Builtin::BI_rotr16:
12083   case Builtin::BI_rotr:
12084   case Builtin::BI_lrotr:
12085   case Builtin::BI_rotr64: {
12086     APSInt Val, Amt;
12087     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12088         !EvaluateInteger(E->getArg(1), Amt, Info))
12089       return false;
12090 
12091     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12092   }
12093 
12094   case Builtin::BIstrlen:
12095   case Builtin::BIwcslen:
12096     // A call to strlen is not a constant expression.
12097     if (Info.getLangOpts().CPlusPlus11)
12098       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12099         << /*isConstexpr*/0 << /*isConstructor*/0
12100         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12101     else
12102       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12103     LLVM_FALLTHROUGH;
12104   case Builtin::BI__builtin_strlen:
12105   case Builtin::BI__builtin_wcslen: {
12106     // As an extension, we support __builtin_strlen() as a constant expression,
12107     // and support folding strlen() to a constant.
12108     uint64_t StrLen;
12109     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12110       return Success(StrLen, E);
12111     return false;
12112   }
12113 
12114   case Builtin::BIstrcmp:
12115   case Builtin::BIwcscmp:
12116   case Builtin::BIstrncmp:
12117   case Builtin::BIwcsncmp:
12118   case Builtin::BImemcmp:
12119   case Builtin::BIbcmp:
12120   case Builtin::BIwmemcmp:
12121     // A call to strlen is not a constant expression.
12122     if (Info.getLangOpts().CPlusPlus11)
12123       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12124         << /*isConstexpr*/0 << /*isConstructor*/0
12125         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12126     else
12127       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12128     LLVM_FALLTHROUGH;
12129   case Builtin::BI__builtin_strcmp:
12130   case Builtin::BI__builtin_wcscmp:
12131   case Builtin::BI__builtin_strncmp:
12132   case Builtin::BI__builtin_wcsncmp:
12133   case Builtin::BI__builtin_memcmp:
12134   case Builtin::BI__builtin_bcmp:
12135   case Builtin::BI__builtin_wmemcmp: {
12136     LValue String1, String2;
12137     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12138         !EvaluatePointer(E->getArg(1), String2, Info))
12139       return false;
12140 
12141     uint64_t MaxLength = uint64_t(-1);
12142     if (BuiltinOp != Builtin::BIstrcmp &&
12143         BuiltinOp != Builtin::BIwcscmp &&
12144         BuiltinOp != Builtin::BI__builtin_strcmp &&
12145         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12146       APSInt N;
12147       if (!EvaluateInteger(E->getArg(2), N, Info))
12148         return false;
12149       MaxLength = N.getExtValue();
12150     }
12151 
12152     // Empty substrings compare equal by definition.
12153     if (MaxLength == 0u)
12154       return Success(0, E);
12155 
12156     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12157         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12158         String1.Designator.Invalid || String2.Designator.Invalid)
12159       return false;
12160 
12161     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12162     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12163 
12164     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12165                      BuiltinOp == Builtin::BIbcmp ||
12166                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12167                      BuiltinOp == Builtin::BI__builtin_bcmp;
12168 
12169     assert(IsRawByte ||
12170            (Info.Ctx.hasSameUnqualifiedType(
12171                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12172             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12173 
12174     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12175     // 'char8_t', but no other types.
12176     if (IsRawByte &&
12177         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12178       // FIXME: Consider using our bit_cast implementation to support this.
12179       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12180           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12181           << CharTy1 << CharTy2;
12182       return false;
12183     }
12184 
12185     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12186       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12187              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12188              Char1.isInt() && Char2.isInt();
12189     };
12190     const auto &AdvanceElems = [&] {
12191       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12192              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12193     };
12194 
12195     bool StopAtNull =
12196         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12197          BuiltinOp != Builtin::BIwmemcmp &&
12198          BuiltinOp != Builtin::BI__builtin_memcmp &&
12199          BuiltinOp != Builtin::BI__builtin_bcmp &&
12200          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12201     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12202                   BuiltinOp == Builtin::BIwcsncmp ||
12203                   BuiltinOp == Builtin::BIwmemcmp ||
12204                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12205                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12206                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12207 
12208     for (; MaxLength; --MaxLength) {
12209       APValue Char1, Char2;
12210       if (!ReadCurElems(Char1, Char2))
12211         return false;
12212       if (Char1.getInt().ne(Char2.getInt())) {
12213         if (IsWide) // wmemcmp compares with wchar_t signedness.
12214           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12215         // memcmp always compares unsigned chars.
12216         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12217       }
12218       if (StopAtNull && !Char1.getInt())
12219         return Success(0, E);
12220       assert(!(StopAtNull && !Char2.getInt()));
12221       if (!AdvanceElems())
12222         return false;
12223     }
12224     // We hit the strncmp / memcmp limit.
12225     return Success(0, E);
12226   }
12227 
12228   case Builtin::BI__atomic_always_lock_free:
12229   case Builtin::BI__atomic_is_lock_free:
12230   case Builtin::BI__c11_atomic_is_lock_free: {
12231     APSInt SizeVal;
12232     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12233       return false;
12234 
12235     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12236     // of two less than or equal to the maximum inline atomic width, we know it
12237     // is lock-free.  If the size isn't a power of two, or greater than the
12238     // maximum alignment where we promote atomics, we know it is not lock-free
12239     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12240     // the answer can only be determined at runtime; for example, 16-byte
12241     // atomics have lock-free implementations on some, but not all,
12242     // x86-64 processors.
12243 
12244     // Check power-of-two.
12245     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12246     if (Size.isPowerOfTwo()) {
12247       // Check against inlining width.
12248       unsigned InlineWidthBits =
12249           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12250       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12251         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12252             Size == CharUnits::One() ||
12253             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12254                                                 Expr::NPC_NeverValueDependent))
12255           // OK, we will inline appropriately-aligned operations of this size,
12256           // and _Atomic(T) is appropriately-aligned.
12257           return Success(1, E);
12258 
12259         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12260           castAs<PointerType>()->getPointeeType();
12261         if (!PointeeType->isIncompleteType() &&
12262             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12263           // OK, we will inline operations on this object.
12264           return Success(1, E);
12265         }
12266       }
12267     }
12268 
12269     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12270         Success(0, E) : Error(E);
12271   }
12272   case Builtin::BI__builtin_add_overflow:
12273   case Builtin::BI__builtin_sub_overflow:
12274   case Builtin::BI__builtin_mul_overflow:
12275   case Builtin::BI__builtin_sadd_overflow:
12276   case Builtin::BI__builtin_uadd_overflow:
12277   case Builtin::BI__builtin_uaddl_overflow:
12278   case Builtin::BI__builtin_uaddll_overflow:
12279   case Builtin::BI__builtin_usub_overflow:
12280   case Builtin::BI__builtin_usubl_overflow:
12281   case Builtin::BI__builtin_usubll_overflow:
12282   case Builtin::BI__builtin_umul_overflow:
12283   case Builtin::BI__builtin_umull_overflow:
12284   case Builtin::BI__builtin_umulll_overflow:
12285   case Builtin::BI__builtin_saddl_overflow:
12286   case Builtin::BI__builtin_saddll_overflow:
12287   case Builtin::BI__builtin_ssub_overflow:
12288   case Builtin::BI__builtin_ssubl_overflow:
12289   case Builtin::BI__builtin_ssubll_overflow:
12290   case Builtin::BI__builtin_smul_overflow:
12291   case Builtin::BI__builtin_smull_overflow:
12292   case Builtin::BI__builtin_smulll_overflow: {
12293     LValue ResultLValue;
12294     APSInt LHS, RHS;
12295 
12296     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12297     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12298         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12299         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12300       return false;
12301 
12302     APSInt Result;
12303     bool DidOverflow = false;
12304 
12305     // If the types don't have to match, enlarge all 3 to the largest of them.
12306     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12307         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12308         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12309       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12310                       ResultType->isSignedIntegerOrEnumerationType();
12311       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12312                       ResultType->isSignedIntegerOrEnumerationType();
12313       uint64_t LHSSize = LHS.getBitWidth();
12314       uint64_t RHSSize = RHS.getBitWidth();
12315       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12316       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12317 
12318       // Add an additional bit if the signedness isn't uniformly agreed to. We
12319       // could do this ONLY if there is a signed and an unsigned that both have
12320       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12321       // caught in the shrink-to-result later anyway.
12322       if (IsSigned && !AllSigned)
12323         ++MaxBits;
12324 
12325       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12326       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12327       Result = APSInt(MaxBits, !IsSigned);
12328     }
12329 
12330     // Find largest int.
12331     switch (BuiltinOp) {
12332     default:
12333       llvm_unreachable("Invalid value for BuiltinOp");
12334     case Builtin::BI__builtin_add_overflow:
12335     case Builtin::BI__builtin_sadd_overflow:
12336     case Builtin::BI__builtin_saddl_overflow:
12337     case Builtin::BI__builtin_saddll_overflow:
12338     case Builtin::BI__builtin_uadd_overflow:
12339     case Builtin::BI__builtin_uaddl_overflow:
12340     case Builtin::BI__builtin_uaddll_overflow:
12341       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12342                               : LHS.uadd_ov(RHS, DidOverflow);
12343       break;
12344     case Builtin::BI__builtin_sub_overflow:
12345     case Builtin::BI__builtin_ssub_overflow:
12346     case Builtin::BI__builtin_ssubl_overflow:
12347     case Builtin::BI__builtin_ssubll_overflow:
12348     case Builtin::BI__builtin_usub_overflow:
12349     case Builtin::BI__builtin_usubl_overflow:
12350     case Builtin::BI__builtin_usubll_overflow:
12351       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12352                               : LHS.usub_ov(RHS, DidOverflow);
12353       break;
12354     case Builtin::BI__builtin_mul_overflow:
12355     case Builtin::BI__builtin_smul_overflow:
12356     case Builtin::BI__builtin_smull_overflow:
12357     case Builtin::BI__builtin_smulll_overflow:
12358     case Builtin::BI__builtin_umul_overflow:
12359     case Builtin::BI__builtin_umull_overflow:
12360     case Builtin::BI__builtin_umulll_overflow:
12361       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12362                               : LHS.umul_ov(RHS, DidOverflow);
12363       break;
12364     }
12365 
12366     // In the case where multiple sizes are allowed, truncate and see if
12367     // the values are the same.
12368     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12369         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12370         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12371       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12372       // since it will give us the behavior of a TruncOrSelf in the case where
12373       // its parameter <= its size.  We previously set Result to be at least the
12374       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12375       // will work exactly like TruncOrSelf.
12376       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12377       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12378 
12379       if (!APSInt::isSameValue(Temp, Result))
12380         DidOverflow = true;
12381       Result = Temp;
12382     }
12383 
12384     APValue APV{Result};
12385     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12386       return false;
12387     return Success(DidOverflow, E);
12388   }
12389   }
12390 }
12391 
12392 /// Determine whether this is a pointer past the end of the complete
12393 /// object referred to by the lvalue.
12394 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12395                                             const LValue &LV) {
12396   // A null pointer can be viewed as being "past the end" but we don't
12397   // choose to look at it that way here.
12398   if (!LV.getLValueBase())
12399     return false;
12400 
12401   // If the designator is valid and refers to a subobject, we're not pointing
12402   // past the end.
12403   if (!LV.getLValueDesignator().Invalid &&
12404       !LV.getLValueDesignator().isOnePastTheEnd())
12405     return false;
12406 
12407   // A pointer to an incomplete type might be past-the-end if the type's size is
12408   // zero.  We cannot tell because the type is incomplete.
12409   QualType Ty = getType(LV.getLValueBase());
12410   if (Ty->isIncompleteType())
12411     return true;
12412 
12413   // We're a past-the-end pointer if we point to the byte after the object,
12414   // no matter what our type or path is.
12415   auto Size = Ctx.getTypeSizeInChars(Ty);
12416   return LV.getLValueOffset() == Size;
12417 }
12418 
12419 namespace {
12420 
12421 /// Data recursive integer evaluator of certain binary operators.
12422 ///
12423 /// We use a data recursive algorithm for binary operators so that we are able
12424 /// to handle extreme cases of chained binary operators without causing stack
12425 /// overflow.
12426 class DataRecursiveIntBinOpEvaluator {
12427   struct EvalResult {
12428     APValue Val;
12429     bool Failed;
12430 
12431     EvalResult() : Failed(false) { }
12432 
12433     void swap(EvalResult &RHS) {
12434       Val.swap(RHS.Val);
12435       Failed = RHS.Failed;
12436       RHS.Failed = false;
12437     }
12438   };
12439 
12440   struct Job {
12441     const Expr *E;
12442     EvalResult LHSResult; // meaningful only for binary operator expression.
12443     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12444 
12445     Job() = default;
12446     Job(Job &&) = default;
12447 
12448     void startSpeculativeEval(EvalInfo &Info) {
12449       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12450     }
12451 
12452   private:
12453     SpeculativeEvaluationRAII SpecEvalRAII;
12454   };
12455 
12456   SmallVector<Job, 16> Queue;
12457 
12458   IntExprEvaluator &IntEval;
12459   EvalInfo &Info;
12460   APValue &FinalResult;
12461 
12462 public:
12463   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12464     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12465 
12466   /// True if \param E is a binary operator that we are going to handle
12467   /// data recursively.
12468   /// We handle binary operators that are comma, logical, or that have operands
12469   /// with integral or enumeration type.
12470   static bool shouldEnqueue(const BinaryOperator *E) {
12471     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12472            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12473             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12474             E->getRHS()->getType()->isIntegralOrEnumerationType());
12475   }
12476 
12477   bool Traverse(const BinaryOperator *E) {
12478     enqueue(E);
12479     EvalResult PrevResult;
12480     while (!Queue.empty())
12481       process(PrevResult);
12482 
12483     if (PrevResult.Failed) return false;
12484 
12485     FinalResult.swap(PrevResult.Val);
12486     return true;
12487   }
12488 
12489 private:
12490   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12491     return IntEval.Success(Value, E, Result);
12492   }
12493   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12494     return IntEval.Success(Value, E, Result);
12495   }
12496   bool Error(const Expr *E) {
12497     return IntEval.Error(E);
12498   }
12499   bool Error(const Expr *E, diag::kind D) {
12500     return IntEval.Error(E, D);
12501   }
12502 
12503   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12504     return Info.CCEDiag(E, D);
12505   }
12506 
12507   // Returns true if visiting the RHS is necessary, false otherwise.
12508   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12509                          bool &SuppressRHSDiags);
12510 
12511   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12512                   const BinaryOperator *E, APValue &Result);
12513 
12514   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12515     Result.Failed = !Evaluate(Result.Val, Info, E);
12516     if (Result.Failed)
12517       Result.Val = APValue();
12518   }
12519 
12520   void process(EvalResult &Result);
12521 
12522   void enqueue(const Expr *E) {
12523     E = E->IgnoreParens();
12524     Queue.resize(Queue.size()+1);
12525     Queue.back().E = E;
12526     Queue.back().Kind = Job::AnyExprKind;
12527   }
12528 };
12529 
12530 }
12531 
12532 bool DataRecursiveIntBinOpEvaluator::
12533        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12534                          bool &SuppressRHSDiags) {
12535   if (E->getOpcode() == BO_Comma) {
12536     // Ignore LHS but note if we could not evaluate it.
12537     if (LHSResult.Failed)
12538       return Info.noteSideEffect();
12539     return true;
12540   }
12541 
12542   if (E->isLogicalOp()) {
12543     bool LHSAsBool;
12544     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12545       // We were able to evaluate the LHS, see if we can get away with not
12546       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12547       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12548         Success(LHSAsBool, E, LHSResult.Val);
12549         return false; // Ignore RHS
12550       }
12551     } else {
12552       LHSResult.Failed = true;
12553 
12554       // Since we weren't able to evaluate the left hand side, it
12555       // might have had side effects.
12556       if (!Info.noteSideEffect())
12557         return false;
12558 
12559       // We can't evaluate the LHS; however, sometimes the result
12560       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12561       // Don't ignore RHS and suppress diagnostics from this arm.
12562       SuppressRHSDiags = true;
12563     }
12564 
12565     return true;
12566   }
12567 
12568   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12569          E->getRHS()->getType()->isIntegralOrEnumerationType());
12570 
12571   if (LHSResult.Failed && !Info.noteFailure())
12572     return false; // Ignore RHS;
12573 
12574   return true;
12575 }
12576 
12577 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12578                                     bool IsSub) {
12579   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12580   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12581   // offsets.
12582   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12583   CharUnits &Offset = LVal.getLValueOffset();
12584   uint64_t Offset64 = Offset.getQuantity();
12585   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12586   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12587                                          : Offset64 + Index64);
12588 }
12589 
12590 bool DataRecursiveIntBinOpEvaluator::
12591        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12592                   const BinaryOperator *E, APValue &Result) {
12593   if (E->getOpcode() == BO_Comma) {
12594     if (RHSResult.Failed)
12595       return false;
12596     Result = RHSResult.Val;
12597     return true;
12598   }
12599 
12600   if (E->isLogicalOp()) {
12601     bool lhsResult, rhsResult;
12602     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12603     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12604 
12605     if (LHSIsOK) {
12606       if (RHSIsOK) {
12607         if (E->getOpcode() == BO_LOr)
12608           return Success(lhsResult || rhsResult, E, Result);
12609         else
12610           return Success(lhsResult && rhsResult, E, Result);
12611       }
12612     } else {
12613       if (RHSIsOK) {
12614         // We can't evaluate the LHS; however, sometimes the result
12615         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12616         if (rhsResult == (E->getOpcode() == BO_LOr))
12617           return Success(rhsResult, E, Result);
12618       }
12619     }
12620 
12621     return false;
12622   }
12623 
12624   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12625          E->getRHS()->getType()->isIntegralOrEnumerationType());
12626 
12627   if (LHSResult.Failed || RHSResult.Failed)
12628     return false;
12629 
12630   const APValue &LHSVal = LHSResult.Val;
12631   const APValue &RHSVal = RHSResult.Val;
12632 
12633   // Handle cases like (unsigned long)&a + 4.
12634   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12635     Result = LHSVal;
12636     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12637     return true;
12638   }
12639 
12640   // Handle cases like 4 + (unsigned long)&a
12641   if (E->getOpcode() == BO_Add &&
12642       RHSVal.isLValue() && LHSVal.isInt()) {
12643     Result = RHSVal;
12644     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12645     return true;
12646   }
12647 
12648   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12649     // Handle (intptr_t)&&A - (intptr_t)&&B.
12650     if (!LHSVal.getLValueOffset().isZero() ||
12651         !RHSVal.getLValueOffset().isZero())
12652       return false;
12653     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12654     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12655     if (!LHSExpr || !RHSExpr)
12656       return false;
12657     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12658     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12659     if (!LHSAddrExpr || !RHSAddrExpr)
12660       return false;
12661     // Make sure both labels come from the same function.
12662     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12663         RHSAddrExpr->getLabel()->getDeclContext())
12664       return false;
12665     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12666     return true;
12667   }
12668 
12669   // All the remaining cases expect both operands to be an integer
12670   if (!LHSVal.isInt() || !RHSVal.isInt())
12671     return Error(E);
12672 
12673   // Set up the width and signedness manually, in case it can't be deduced
12674   // from the operation we're performing.
12675   // FIXME: Don't do this in the cases where we can deduce it.
12676   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12677                E->getType()->isUnsignedIntegerOrEnumerationType());
12678   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12679                          RHSVal.getInt(), Value))
12680     return false;
12681   return Success(Value, E, Result);
12682 }
12683 
12684 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12685   Job &job = Queue.back();
12686 
12687   switch (job.Kind) {
12688     case Job::AnyExprKind: {
12689       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12690         if (shouldEnqueue(Bop)) {
12691           job.Kind = Job::BinOpKind;
12692           enqueue(Bop->getLHS());
12693           return;
12694         }
12695       }
12696 
12697       EvaluateExpr(job.E, Result);
12698       Queue.pop_back();
12699       return;
12700     }
12701 
12702     case Job::BinOpKind: {
12703       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12704       bool SuppressRHSDiags = false;
12705       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12706         Queue.pop_back();
12707         return;
12708       }
12709       if (SuppressRHSDiags)
12710         job.startSpeculativeEval(Info);
12711       job.LHSResult.swap(Result);
12712       job.Kind = Job::BinOpVisitedLHSKind;
12713       enqueue(Bop->getRHS());
12714       return;
12715     }
12716 
12717     case Job::BinOpVisitedLHSKind: {
12718       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12719       EvalResult RHS;
12720       RHS.swap(Result);
12721       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12722       Queue.pop_back();
12723       return;
12724     }
12725   }
12726 
12727   llvm_unreachable("Invalid Job::Kind!");
12728 }
12729 
12730 namespace {
12731 enum class CmpResult {
12732   Unequal,
12733   Less,
12734   Equal,
12735   Greater,
12736   Unordered,
12737 };
12738 }
12739 
12740 template <class SuccessCB, class AfterCB>
12741 static bool
12742 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12743                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12744   assert(!E->isValueDependent());
12745   assert(E->isComparisonOp() && "expected comparison operator");
12746   assert((E->getOpcode() == BO_Cmp ||
12747           E->getType()->isIntegralOrEnumerationType()) &&
12748          "unsupported binary expression evaluation");
12749   auto Error = [&](const Expr *E) {
12750     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12751     return false;
12752   };
12753 
12754   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12755   bool IsEquality = E->isEqualityOp();
12756 
12757   QualType LHSTy = E->getLHS()->getType();
12758   QualType RHSTy = E->getRHS()->getType();
12759 
12760   if (LHSTy->isIntegralOrEnumerationType() &&
12761       RHSTy->isIntegralOrEnumerationType()) {
12762     APSInt LHS, RHS;
12763     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12764     if (!LHSOK && !Info.noteFailure())
12765       return false;
12766     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12767       return false;
12768     if (LHS < RHS)
12769       return Success(CmpResult::Less, E);
12770     if (LHS > RHS)
12771       return Success(CmpResult::Greater, E);
12772     return Success(CmpResult::Equal, E);
12773   }
12774 
12775   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12776     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12777     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12778 
12779     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12780     if (!LHSOK && !Info.noteFailure())
12781       return false;
12782     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12783       return false;
12784     if (LHSFX < RHSFX)
12785       return Success(CmpResult::Less, E);
12786     if (LHSFX > RHSFX)
12787       return Success(CmpResult::Greater, E);
12788     return Success(CmpResult::Equal, E);
12789   }
12790 
12791   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12792     ComplexValue LHS, RHS;
12793     bool LHSOK;
12794     if (E->isAssignmentOp()) {
12795       LValue LV;
12796       EvaluateLValue(E->getLHS(), LV, Info);
12797       LHSOK = false;
12798     } else if (LHSTy->isRealFloatingType()) {
12799       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12800       if (LHSOK) {
12801         LHS.makeComplexFloat();
12802         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12803       }
12804     } else {
12805       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12806     }
12807     if (!LHSOK && !Info.noteFailure())
12808       return false;
12809 
12810     if (E->getRHS()->getType()->isRealFloatingType()) {
12811       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12812         return false;
12813       RHS.makeComplexFloat();
12814       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12815     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12816       return false;
12817 
12818     if (LHS.isComplexFloat()) {
12819       APFloat::cmpResult CR_r =
12820         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12821       APFloat::cmpResult CR_i =
12822         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12823       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12824       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12825     } else {
12826       assert(IsEquality && "invalid complex comparison");
12827       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12828                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12829       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12830     }
12831   }
12832 
12833   if (LHSTy->isRealFloatingType() &&
12834       RHSTy->isRealFloatingType()) {
12835     APFloat RHS(0.0), LHS(0.0);
12836 
12837     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12838     if (!LHSOK && !Info.noteFailure())
12839       return false;
12840 
12841     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12842       return false;
12843 
12844     assert(E->isComparisonOp() && "Invalid binary operator!");
12845     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12846     if (!Info.InConstantContext &&
12847         APFloatCmpResult == APFloat::cmpUnordered &&
12848         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12849       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12850       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12851       return false;
12852     }
12853     auto GetCmpRes = [&]() {
12854       switch (APFloatCmpResult) {
12855       case APFloat::cmpEqual:
12856         return CmpResult::Equal;
12857       case APFloat::cmpLessThan:
12858         return CmpResult::Less;
12859       case APFloat::cmpGreaterThan:
12860         return CmpResult::Greater;
12861       case APFloat::cmpUnordered:
12862         return CmpResult::Unordered;
12863       }
12864       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12865     };
12866     return Success(GetCmpRes(), E);
12867   }
12868 
12869   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12870     LValue LHSValue, RHSValue;
12871 
12872     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12873     if (!LHSOK && !Info.noteFailure())
12874       return false;
12875 
12876     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12877       return false;
12878 
12879     // Reject differing bases from the normal codepath; we special-case
12880     // comparisons to null.
12881     if (!HasSameBase(LHSValue, RHSValue)) {
12882       // Inequalities and subtractions between unrelated pointers have
12883       // unspecified or undefined behavior.
12884       if (!IsEquality) {
12885         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12886         return false;
12887       }
12888       // A constant address may compare equal to the address of a symbol.
12889       // The one exception is that address of an object cannot compare equal
12890       // to a null pointer constant.
12891       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12892           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12893         return Error(E);
12894       // It's implementation-defined whether distinct literals will have
12895       // distinct addresses. In clang, the result of such a comparison is
12896       // unspecified, so it is not a constant expression. However, we do know
12897       // that the address of a literal will be non-null.
12898       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12899           LHSValue.Base && RHSValue.Base)
12900         return Error(E);
12901       // We can't tell whether weak symbols will end up pointing to the same
12902       // object.
12903       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12904         return Error(E);
12905       // We can't compare the address of the start of one object with the
12906       // past-the-end address of another object, per C++ DR1652.
12907       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12908            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12909           (RHSValue.Base && RHSValue.Offset.isZero() &&
12910            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12911         return Error(E);
12912       // We can't tell whether an object is at the same address as another
12913       // zero sized object.
12914       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12915           (LHSValue.Base && isZeroSized(RHSValue)))
12916         return Error(E);
12917       return Success(CmpResult::Unequal, E);
12918     }
12919 
12920     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12921     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12922 
12923     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12924     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12925 
12926     // C++11 [expr.rel]p3:
12927     //   Pointers to void (after pointer conversions) can be compared, with a
12928     //   result defined as follows: If both pointers represent the same
12929     //   address or are both the null pointer value, the result is true if the
12930     //   operator is <= or >= and false otherwise; otherwise the result is
12931     //   unspecified.
12932     // We interpret this as applying to pointers to *cv* void.
12933     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12934       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12935 
12936     // C++11 [expr.rel]p2:
12937     // - If two pointers point to non-static data members of the same object,
12938     //   or to subobjects or array elements fo such members, recursively, the
12939     //   pointer to the later declared member compares greater provided the
12940     //   two members have the same access control and provided their class is
12941     //   not a union.
12942     //   [...]
12943     // - Otherwise pointer comparisons are unspecified.
12944     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12945       bool WasArrayIndex;
12946       unsigned Mismatch = FindDesignatorMismatch(
12947           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12948       // At the point where the designators diverge, the comparison has a
12949       // specified value if:
12950       //  - we are comparing array indices
12951       //  - we are comparing fields of a union, or fields with the same access
12952       // Otherwise, the result is unspecified and thus the comparison is not a
12953       // constant expression.
12954       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12955           Mismatch < RHSDesignator.Entries.size()) {
12956         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12957         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12958         if (!LF && !RF)
12959           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12960         else if (!LF)
12961           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12962               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12963               << RF->getParent() << RF;
12964         else if (!RF)
12965           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12966               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12967               << LF->getParent() << LF;
12968         else if (!LF->getParent()->isUnion() &&
12969                  LF->getAccess() != RF->getAccess())
12970           Info.CCEDiag(E,
12971                        diag::note_constexpr_pointer_comparison_differing_access)
12972               << LF << LF->getAccess() << RF << RF->getAccess()
12973               << LF->getParent();
12974       }
12975     }
12976 
12977     // The comparison here must be unsigned, and performed with the same
12978     // width as the pointer.
12979     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12980     uint64_t CompareLHS = LHSOffset.getQuantity();
12981     uint64_t CompareRHS = RHSOffset.getQuantity();
12982     assert(PtrSize <= 64 && "Unexpected pointer width");
12983     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12984     CompareLHS &= Mask;
12985     CompareRHS &= Mask;
12986 
12987     // If there is a base and this is a relational operator, we can only
12988     // compare pointers within the object in question; otherwise, the result
12989     // depends on where the object is located in memory.
12990     if (!LHSValue.Base.isNull() && IsRelational) {
12991       QualType BaseTy = getType(LHSValue.Base);
12992       if (BaseTy->isIncompleteType())
12993         return Error(E);
12994       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12995       uint64_t OffsetLimit = Size.getQuantity();
12996       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12997         return Error(E);
12998     }
12999 
13000     if (CompareLHS < CompareRHS)
13001       return Success(CmpResult::Less, E);
13002     if (CompareLHS > CompareRHS)
13003       return Success(CmpResult::Greater, E);
13004     return Success(CmpResult::Equal, E);
13005   }
13006 
13007   if (LHSTy->isMemberPointerType()) {
13008     assert(IsEquality && "unexpected member pointer operation");
13009     assert(RHSTy->isMemberPointerType() && "invalid comparison");
13010 
13011     MemberPtr LHSValue, RHSValue;
13012 
13013     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13014     if (!LHSOK && !Info.noteFailure())
13015       return false;
13016 
13017     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13018       return false;
13019 
13020     // C++11 [expr.eq]p2:
13021     //   If both operands are null, they compare equal. Otherwise if only one is
13022     //   null, they compare unequal.
13023     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13024       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13025       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13026     }
13027 
13028     //   Otherwise if either is a pointer to a virtual member function, the
13029     //   result is unspecified.
13030     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13031       if (MD->isVirtual())
13032         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13033     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13034       if (MD->isVirtual())
13035         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13036 
13037     //   Otherwise they compare equal if and only if they would refer to the
13038     //   same member of the same most derived object or the same subobject if
13039     //   they were dereferenced with a hypothetical object of the associated
13040     //   class type.
13041     bool Equal = LHSValue == RHSValue;
13042     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13043   }
13044 
13045   if (LHSTy->isNullPtrType()) {
13046     assert(E->isComparisonOp() && "unexpected nullptr operation");
13047     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13048     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13049     // are compared, the result is true of the operator is <=, >= or ==, and
13050     // false otherwise.
13051     return Success(CmpResult::Equal, E);
13052   }
13053 
13054   return DoAfter();
13055 }
13056 
13057 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13058   if (!CheckLiteralType(Info, E))
13059     return false;
13060 
13061   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13062     ComparisonCategoryResult CCR;
13063     switch (CR) {
13064     case CmpResult::Unequal:
13065       llvm_unreachable("should never produce Unequal for three-way comparison");
13066     case CmpResult::Less:
13067       CCR = ComparisonCategoryResult::Less;
13068       break;
13069     case CmpResult::Equal:
13070       CCR = ComparisonCategoryResult::Equal;
13071       break;
13072     case CmpResult::Greater:
13073       CCR = ComparisonCategoryResult::Greater;
13074       break;
13075     case CmpResult::Unordered:
13076       CCR = ComparisonCategoryResult::Unordered;
13077       break;
13078     }
13079     // Evaluation succeeded. Lookup the information for the comparison category
13080     // type and fetch the VarDecl for the result.
13081     const ComparisonCategoryInfo &CmpInfo =
13082         Info.Ctx.CompCategories.getInfoForType(E->getType());
13083     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13084     // Check and evaluate the result as a constant expression.
13085     LValue LV;
13086     LV.set(VD);
13087     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13088       return false;
13089     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13090                                    ConstantExprKind::Normal);
13091   };
13092   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13093     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13094   });
13095 }
13096 
13097 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13098   // We don't support assignment in C. C++ assignments don't get here because
13099   // assignment is an lvalue in C++.
13100   if (E->isAssignmentOp()) {
13101     Error(E);
13102     if (!Info.noteFailure())
13103       return false;
13104   }
13105 
13106   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13107     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13108 
13109   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13110           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13111          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13112 
13113   if (E->isComparisonOp()) {
13114     // Evaluate builtin binary comparisons by evaluating them as three-way
13115     // comparisons and then translating the result.
13116     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13117       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13118              "should only produce Unequal for equality comparisons");
13119       bool IsEqual   = CR == CmpResult::Equal,
13120            IsLess    = CR == CmpResult::Less,
13121            IsGreater = CR == CmpResult::Greater;
13122       auto Op = E->getOpcode();
13123       switch (Op) {
13124       default:
13125         llvm_unreachable("unsupported binary operator");
13126       case BO_EQ:
13127       case BO_NE:
13128         return Success(IsEqual == (Op == BO_EQ), E);
13129       case BO_LT:
13130         return Success(IsLess, E);
13131       case BO_GT:
13132         return Success(IsGreater, E);
13133       case BO_LE:
13134         return Success(IsEqual || IsLess, E);
13135       case BO_GE:
13136         return Success(IsEqual || IsGreater, E);
13137       }
13138     };
13139     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13140       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13141     });
13142   }
13143 
13144   QualType LHSTy = E->getLHS()->getType();
13145   QualType RHSTy = E->getRHS()->getType();
13146 
13147   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13148       E->getOpcode() == BO_Sub) {
13149     LValue LHSValue, RHSValue;
13150 
13151     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13152     if (!LHSOK && !Info.noteFailure())
13153       return false;
13154 
13155     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13156       return false;
13157 
13158     // Reject differing bases from the normal codepath; we special-case
13159     // comparisons to null.
13160     if (!HasSameBase(LHSValue, RHSValue)) {
13161       // Handle &&A - &&B.
13162       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13163         return Error(E);
13164       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13165       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13166       if (!LHSExpr || !RHSExpr)
13167         return Error(E);
13168       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13169       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13170       if (!LHSAddrExpr || !RHSAddrExpr)
13171         return Error(E);
13172       // Make sure both labels come from the same function.
13173       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13174           RHSAddrExpr->getLabel()->getDeclContext())
13175         return Error(E);
13176       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13177     }
13178     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13179     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13180 
13181     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13182     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13183 
13184     // C++11 [expr.add]p6:
13185     //   Unless both pointers point to elements of the same array object, or
13186     //   one past the last element of the array object, the behavior is
13187     //   undefined.
13188     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13189         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13190                                 RHSDesignator))
13191       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13192 
13193     QualType Type = E->getLHS()->getType();
13194     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13195 
13196     CharUnits ElementSize;
13197     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13198       return false;
13199 
13200     // As an extension, a type may have zero size (empty struct or union in
13201     // C, array of zero length). Pointer subtraction in such cases has
13202     // undefined behavior, so is not constant.
13203     if (ElementSize.isZero()) {
13204       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13205           << ElementType;
13206       return false;
13207     }
13208 
13209     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13210     // and produce incorrect results when it overflows. Such behavior
13211     // appears to be non-conforming, but is common, so perhaps we should
13212     // assume the standard intended for such cases to be undefined behavior
13213     // and check for them.
13214 
13215     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13216     // overflow in the final conversion to ptrdiff_t.
13217     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13218     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13219     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13220                     false);
13221     APSInt TrueResult = (LHS - RHS) / ElemSize;
13222     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13223 
13224     if (Result.extend(65) != TrueResult &&
13225         !HandleOverflow(Info, E, TrueResult, E->getType()))
13226       return false;
13227     return Success(Result, E);
13228   }
13229 
13230   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13231 }
13232 
13233 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13234 /// a result as the expression's type.
13235 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13236                                     const UnaryExprOrTypeTraitExpr *E) {
13237   switch(E->getKind()) {
13238   case UETT_PreferredAlignOf:
13239   case UETT_AlignOf: {
13240     if (E->isArgumentType())
13241       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13242                      E);
13243     else
13244       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13245                      E);
13246   }
13247 
13248   case UETT_VecStep: {
13249     QualType Ty = E->getTypeOfArgument();
13250 
13251     if (Ty->isVectorType()) {
13252       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13253 
13254       // The vec_step built-in functions that take a 3-component
13255       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13256       if (n == 3)
13257         n = 4;
13258 
13259       return Success(n, E);
13260     } else
13261       return Success(1, E);
13262   }
13263 
13264   case UETT_SizeOf: {
13265     QualType SrcTy = E->getTypeOfArgument();
13266     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13267     //   the result is the size of the referenced type."
13268     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13269       SrcTy = Ref->getPointeeType();
13270 
13271     CharUnits Sizeof;
13272     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13273       return false;
13274     return Success(Sizeof, E);
13275   }
13276   case UETT_OpenMPRequiredSimdAlign:
13277     assert(E->isArgumentType());
13278     return Success(
13279         Info.Ctx.toCharUnitsFromBits(
13280                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13281             .getQuantity(),
13282         E);
13283   }
13284 
13285   llvm_unreachable("unknown expr/type trait");
13286 }
13287 
13288 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13289   CharUnits Result;
13290   unsigned n = OOE->getNumComponents();
13291   if (n == 0)
13292     return Error(OOE);
13293   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13294   for (unsigned i = 0; i != n; ++i) {
13295     OffsetOfNode ON = OOE->getComponent(i);
13296     switch (ON.getKind()) {
13297     case OffsetOfNode::Array: {
13298       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13299       APSInt IdxResult;
13300       if (!EvaluateInteger(Idx, IdxResult, Info))
13301         return false;
13302       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13303       if (!AT)
13304         return Error(OOE);
13305       CurrentType = AT->getElementType();
13306       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13307       Result += IdxResult.getSExtValue() * ElementSize;
13308       break;
13309     }
13310 
13311     case OffsetOfNode::Field: {
13312       FieldDecl *MemberDecl = ON.getField();
13313       const RecordType *RT = CurrentType->getAs<RecordType>();
13314       if (!RT)
13315         return Error(OOE);
13316       RecordDecl *RD = RT->getDecl();
13317       if (RD->isInvalidDecl()) return false;
13318       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13319       unsigned i = MemberDecl->getFieldIndex();
13320       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13321       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13322       CurrentType = MemberDecl->getType().getNonReferenceType();
13323       break;
13324     }
13325 
13326     case OffsetOfNode::Identifier:
13327       llvm_unreachable("dependent __builtin_offsetof");
13328 
13329     case OffsetOfNode::Base: {
13330       CXXBaseSpecifier *BaseSpec = ON.getBase();
13331       if (BaseSpec->isVirtual())
13332         return Error(OOE);
13333 
13334       // Find the layout of the class whose base we are looking into.
13335       const RecordType *RT = CurrentType->getAs<RecordType>();
13336       if (!RT)
13337         return Error(OOE);
13338       RecordDecl *RD = RT->getDecl();
13339       if (RD->isInvalidDecl()) return false;
13340       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13341 
13342       // Find the base class itself.
13343       CurrentType = BaseSpec->getType();
13344       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13345       if (!BaseRT)
13346         return Error(OOE);
13347 
13348       // Add the offset to the base.
13349       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13350       break;
13351     }
13352     }
13353   }
13354   return Success(Result, OOE);
13355 }
13356 
13357 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13358   switch (E->getOpcode()) {
13359   default:
13360     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13361     // See C99 6.6p3.
13362     return Error(E);
13363   case UO_Extension:
13364     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13365     // If so, we could clear the diagnostic ID.
13366     return Visit(E->getSubExpr());
13367   case UO_Plus:
13368     // The result is just the value.
13369     return Visit(E->getSubExpr());
13370   case UO_Minus: {
13371     if (!Visit(E->getSubExpr()))
13372       return false;
13373     if (!Result.isInt()) return Error(E);
13374     const APSInt &Value = Result.getInt();
13375     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13376         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13377                         E->getType()))
13378       return false;
13379     return Success(-Value, E);
13380   }
13381   case UO_Not: {
13382     if (!Visit(E->getSubExpr()))
13383       return false;
13384     if (!Result.isInt()) return Error(E);
13385     return Success(~Result.getInt(), E);
13386   }
13387   case UO_LNot: {
13388     bool bres;
13389     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13390       return false;
13391     return Success(!bres, E);
13392   }
13393   }
13394 }
13395 
13396 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13397 /// result type is integer.
13398 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13399   const Expr *SubExpr = E->getSubExpr();
13400   QualType DestType = E->getType();
13401   QualType SrcType = SubExpr->getType();
13402 
13403   switch (E->getCastKind()) {
13404   case CK_BaseToDerived:
13405   case CK_DerivedToBase:
13406   case CK_UncheckedDerivedToBase:
13407   case CK_Dynamic:
13408   case CK_ToUnion:
13409   case CK_ArrayToPointerDecay:
13410   case CK_FunctionToPointerDecay:
13411   case CK_NullToPointer:
13412   case CK_NullToMemberPointer:
13413   case CK_BaseToDerivedMemberPointer:
13414   case CK_DerivedToBaseMemberPointer:
13415   case CK_ReinterpretMemberPointer:
13416   case CK_ConstructorConversion:
13417   case CK_IntegralToPointer:
13418   case CK_ToVoid:
13419   case CK_VectorSplat:
13420   case CK_IntegralToFloating:
13421   case CK_FloatingCast:
13422   case CK_CPointerToObjCPointerCast:
13423   case CK_BlockPointerToObjCPointerCast:
13424   case CK_AnyPointerToBlockPointerCast:
13425   case CK_ObjCObjectLValueCast:
13426   case CK_FloatingRealToComplex:
13427   case CK_FloatingComplexToReal:
13428   case CK_FloatingComplexCast:
13429   case CK_FloatingComplexToIntegralComplex:
13430   case CK_IntegralRealToComplex:
13431   case CK_IntegralComplexCast:
13432   case CK_IntegralComplexToFloatingComplex:
13433   case CK_BuiltinFnToFnPtr:
13434   case CK_ZeroToOCLOpaqueType:
13435   case CK_NonAtomicToAtomic:
13436   case CK_AddressSpaceConversion:
13437   case CK_IntToOCLSampler:
13438   case CK_FloatingToFixedPoint:
13439   case CK_FixedPointToFloating:
13440   case CK_FixedPointCast:
13441   case CK_IntegralToFixedPoint:
13442   case CK_MatrixCast:
13443     llvm_unreachable("invalid cast kind for integral value");
13444 
13445   case CK_BitCast:
13446   case CK_Dependent:
13447   case CK_LValueBitCast:
13448   case CK_ARCProduceObject:
13449   case CK_ARCConsumeObject:
13450   case CK_ARCReclaimReturnedObject:
13451   case CK_ARCExtendBlockObject:
13452   case CK_CopyAndAutoreleaseBlockObject:
13453     return Error(E);
13454 
13455   case CK_UserDefinedConversion:
13456   case CK_LValueToRValue:
13457   case CK_AtomicToNonAtomic:
13458   case CK_NoOp:
13459   case CK_LValueToRValueBitCast:
13460     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13461 
13462   case CK_MemberPointerToBoolean:
13463   case CK_PointerToBoolean:
13464   case CK_IntegralToBoolean:
13465   case CK_FloatingToBoolean:
13466   case CK_BooleanToSignedIntegral:
13467   case CK_FloatingComplexToBoolean:
13468   case CK_IntegralComplexToBoolean: {
13469     bool BoolResult;
13470     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13471       return false;
13472     uint64_t IntResult = BoolResult;
13473     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13474       IntResult = (uint64_t)-1;
13475     return Success(IntResult, E);
13476   }
13477 
13478   case CK_FixedPointToIntegral: {
13479     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13480     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13481       return false;
13482     bool Overflowed;
13483     llvm::APSInt Result = Src.convertToInt(
13484         Info.Ctx.getIntWidth(DestType),
13485         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13486     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13487       return false;
13488     return Success(Result, E);
13489   }
13490 
13491   case CK_FixedPointToBoolean: {
13492     // Unsigned padding does not affect this.
13493     APValue Val;
13494     if (!Evaluate(Val, Info, SubExpr))
13495       return false;
13496     return Success(Val.getFixedPoint().getBoolValue(), E);
13497   }
13498 
13499   case CK_IntegralCast: {
13500     if (!Visit(SubExpr))
13501       return false;
13502 
13503     if (!Result.isInt()) {
13504       // Allow casts of address-of-label differences if they are no-ops
13505       // or narrowing.  (The narrowing case isn't actually guaranteed to
13506       // be constant-evaluatable except in some narrow cases which are hard
13507       // to detect here.  We let it through on the assumption the user knows
13508       // what they are doing.)
13509       if (Result.isAddrLabelDiff())
13510         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13511       // Only allow casts of lvalues if they are lossless.
13512       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13513     }
13514 
13515     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13516                                       Result.getInt()), E);
13517   }
13518 
13519   case CK_PointerToIntegral: {
13520     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13521 
13522     LValue LV;
13523     if (!EvaluatePointer(SubExpr, LV, Info))
13524       return false;
13525 
13526     if (LV.getLValueBase()) {
13527       // Only allow based lvalue casts if they are lossless.
13528       // FIXME: Allow a larger integer size than the pointer size, and allow
13529       // narrowing back down to pointer width in subsequent integral casts.
13530       // FIXME: Check integer type's active bits, not its type size.
13531       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13532         return Error(E);
13533 
13534       LV.Designator.setInvalid();
13535       LV.moveInto(Result);
13536       return true;
13537     }
13538 
13539     APSInt AsInt;
13540     APValue V;
13541     LV.moveInto(V);
13542     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13543       llvm_unreachable("Can't cast this!");
13544 
13545     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13546   }
13547 
13548   case CK_IntegralComplexToReal: {
13549     ComplexValue C;
13550     if (!EvaluateComplex(SubExpr, C, Info))
13551       return false;
13552     return Success(C.getComplexIntReal(), E);
13553   }
13554 
13555   case CK_FloatingToIntegral: {
13556     APFloat F(0.0);
13557     if (!EvaluateFloat(SubExpr, F, Info))
13558       return false;
13559 
13560     APSInt Value;
13561     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13562       return false;
13563     return Success(Value, E);
13564   }
13565   }
13566 
13567   llvm_unreachable("unknown cast resulting in integral value");
13568 }
13569 
13570 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13571   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13572     ComplexValue LV;
13573     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13574       return false;
13575     if (!LV.isComplexInt())
13576       return Error(E);
13577     return Success(LV.getComplexIntReal(), E);
13578   }
13579 
13580   return Visit(E->getSubExpr());
13581 }
13582 
13583 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13584   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13585     ComplexValue LV;
13586     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13587       return false;
13588     if (!LV.isComplexInt())
13589       return Error(E);
13590     return Success(LV.getComplexIntImag(), E);
13591   }
13592 
13593   VisitIgnoredValue(E->getSubExpr());
13594   return Success(0, E);
13595 }
13596 
13597 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13598   return Success(E->getPackLength(), E);
13599 }
13600 
13601 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13602   return Success(E->getValue(), E);
13603 }
13604 
13605 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13606        const ConceptSpecializationExpr *E) {
13607   return Success(E->isSatisfied(), E);
13608 }
13609 
13610 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13611   return Success(E->isSatisfied(), E);
13612 }
13613 
13614 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13615   switch (E->getOpcode()) {
13616     default:
13617       // Invalid unary operators
13618       return Error(E);
13619     case UO_Plus:
13620       // The result is just the value.
13621       return Visit(E->getSubExpr());
13622     case UO_Minus: {
13623       if (!Visit(E->getSubExpr())) return false;
13624       if (!Result.isFixedPoint())
13625         return Error(E);
13626       bool Overflowed;
13627       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13628       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13629         return false;
13630       return Success(Negated, E);
13631     }
13632     case UO_LNot: {
13633       bool bres;
13634       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13635         return false;
13636       return Success(!bres, E);
13637     }
13638   }
13639 }
13640 
13641 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13642   const Expr *SubExpr = E->getSubExpr();
13643   QualType DestType = E->getType();
13644   assert(DestType->isFixedPointType() &&
13645          "Expected destination type to be a fixed point type");
13646   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13647 
13648   switch (E->getCastKind()) {
13649   case CK_FixedPointCast: {
13650     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13651     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13652       return false;
13653     bool Overflowed;
13654     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13655     if (Overflowed) {
13656       if (Info.checkingForUndefinedBehavior())
13657         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13658                                          diag::warn_fixedpoint_constant_overflow)
13659           << Result.toString() << E->getType();
13660       if (!HandleOverflow(Info, E, Result, E->getType()))
13661         return false;
13662     }
13663     return Success(Result, E);
13664   }
13665   case CK_IntegralToFixedPoint: {
13666     APSInt Src;
13667     if (!EvaluateInteger(SubExpr, Src, Info))
13668       return false;
13669 
13670     bool Overflowed;
13671     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13672         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13673 
13674     if (Overflowed) {
13675       if (Info.checkingForUndefinedBehavior())
13676         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13677                                          diag::warn_fixedpoint_constant_overflow)
13678           << IntResult.toString() << E->getType();
13679       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13680         return false;
13681     }
13682 
13683     return Success(IntResult, E);
13684   }
13685   case CK_FloatingToFixedPoint: {
13686     APFloat Src(0.0);
13687     if (!EvaluateFloat(SubExpr, Src, Info))
13688       return false;
13689 
13690     bool Overflowed;
13691     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13692         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13693 
13694     if (Overflowed) {
13695       if (Info.checkingForUndefinedBehavior())
13696         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13697                                          diag::warn_fixedpoint_constant_overflow)
13698           << Result.toString() << E->getType();
13699       if (!HandleOverflow(Info, E, Result, E->getType()))
13700         return false;
13701     }
13702 
13703     return Success(Result, E);
13704   }
13705   case CK_NoOp:
13706   case CK_LValueToRValue:
13707     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13708   default:
13709     return Error(E);
13710   }
13711 }
13712 
13713 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13714   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13715     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13716 
13717   const Expr *LHS = E->getLHS();
13718   const Expr *RHS = E->getRHS();
13719   FixedPointSemantics ResultFXSema =
13720       Info.Ctx.getFixedPointSemantics(E->getType());
13721 
13722   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13723   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13724     return false;
13725   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13726   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13727     return false;
13728 
13729   bool OpOverflow = false, ConversionOverflow = false;
13730   APFixedPoint Result(LHSFX.getSemantics());
13731   switch (E->getOpcode()) {
13732   case BO_Add: {
13733     Result = LHSFX.add(RHSFX, &OpOverflow)
13734                   .convert(ResultFXSema, &ConversionOverflow);
13735     break;
13736   }
13737   case BO_Sub: {
13738     Result = LHSFX.sub(RHSFX, &OpOverflow)
13739                   .convert(ResultFXSema, &ConversionOverflow);
13740     break;
13741   }
13742   case BO_Mul: {
13743     Result = LHSFX.mul(RHSFX, &OpOverflow)
13744                   .convert(ResultFXSema, &ConversionOverflow);
13745     break;
13746   }
13747   case BO_Div: {
13748     if (RHSFX.getValue() == 0) {
13749       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13750       return false;
13751     }
13752     Result = LHSFX.div(RHSFX, &OpOverflow)
13753                   .convert(ResultFXSema, &ConversionOverflow);
13754     break;
13755   }
13756   case BO_Shl:
13757   case BO_Shr: {
13758     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13759     llvm::APSInt RHSVal = RHSFX.getValue();
13760 
13761     unsigned ShiftBW =
13762         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13763     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13764     // Embedded-C 4.1.6.2.2:
13765     //   The right operand must be nonnegative and less than the total number
13766     //   of (nonpadding) bits of the fixed-point operand ...
13767     if (RHSVal.isNegative())
13768       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13769     else if (Amt != RHSVal)
13770       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13771           << RHSVal << E->getType() << ShiftBW;
13772 
13773     if (E->getOpcode() == BO_Shl)
13774       Result = LHSFX.shl(Amt, &OpOverflow);
13775     else
13776       Result = LHSFX.shr(Amt, &OpOverflow);
13777     break;
13778   }
13779   default:
13780     return false;
13781   }
13782   if (OpOverflow || ConversionOverflow) {
13783     if (Info.checkingForUndefinedBehavior())
13784       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13785                                        diag::warn_fixedpoint_constant_overflow)
13786         << Result.toString() << E->getType();
13787     if (!HandleOverflow(Info, E, Result, E->getType()))
13788       return false;
13789   }
13790   return Success(Result, E);
13791 }
13792 
13793 //===----------------------------------------------------------------------===//
13794 // Float Evaluation
13795 //===----------------------------------------------------------------------===//
13796 
13797 namespace {
13798 class FloatExprEvaluator
13799   : public ExprEvaluatorBase<FloatExprEvaluator> {
13800   APFloat &Result;
13801 public:
13802   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13803     : ExprEvaluatorBaseTy(info), Result(result) {}
13804 
13805   bool Success(const APValue &V, const Expr *e) {
13806     Result = V.getFloat();
13807     return true;
13808   }
13809 
13810   bool ZeroInitialization(const Expr *E) {
13811     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13812     return true;
13813   }
13814 
13815   bool VisitCallExpr(const CallExpr *E);
13816 
13817   bool VisitUnaryOperator(const UnaryOperator *E);
13818   bool VisitBinaryOperator(const BinaryOperator *E);
13819   bool VisitFloatingLiteral(const FloatingLiteral *E);
13820   bool VisitCastExpr(const CastExpr *E);
13821 
13822   bool VisitUnaryReal(const UnaryOperator *E);
13823   bool VisitUnaryImag(const UnaryOperator *E);
13824 
13825   // FIXME: Missing: array subscript of vector, member of vector
13826 };
13827 } // end anonymous namespace
13828 
13829 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13830   assert(!E->isValueDependent());
13831   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13832   return FloatExprEvaluator(Info, Result).Visit(E);
13833 }
13834 
13835 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13836                                   QualType ResultTy,
13837                                   const Expr *Arg,
13838                                   bool SNaN,
13839                                   llvm::APFloat &Result) {
13840   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13841   if (!S) return false;
13842 
13843   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13844 
13845   llvm::APInt fill;
13846 
13847   // Treat empty strings as if they were zero.
13848   if (S->getString().empty())
13849     fill = llvm::APInt(32, 0);
13850   else if (S->getString().getAsInteger(0, fill))
13851     return false;
13852 
13853   if (Context.getTargetInfo().isNan2008()) {
13854     if (SNaN)
13855       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13856     else
13857       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13858   } else {
13859     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13860     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13861     // a different encoding to what became a standard in 2008, and for pre-
13862     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13863     // sNaN. This is now known as "legacy NaN" encoding.
13864     if (SNaN)
13865       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13866     else
13867       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13868   }
13869 
13870   return true;
13871 }
13872 
13873 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13874   switch (E->getBuiltinCallee()) {
13875   default:
13876     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13877 
13878   case Builtin::BI__builtin_huge_val:
13879   case Builtin::BI__builtin_huge_valf:
13880   case Builtin::BI__builtin_huge_vall:
13881   case Builtin::BI__builtin_huge_valf16:
13882   case Builtin::BI__builtin_huge_valf128:
13883   case Builtin::BI__builtin_inf:
13884   case Builtin::BI__builtin_inff:
13885   case Builtin::BI__builtin_infl:
13886   case Builtin::BI__builtin_inff16:
13887   case Builtin::BI__builtin_inff128: {
13888     const llvm::fltSemantics &Sem =
13889       Info.Ctx.getFloatTypeSemantics(E->getType());
13890     Result = llvm::APFloat::getInf(Sem);
13891     return true;
13892   }
13893 
13894   case Builtin::BI__builtin_nans:
13895   case Builtin::BI__builtin_nansf:
13896   case Builtin::BI__builtin_nansl:
13897   case Builtin::BI__builtin_nansf16:
13898   case Builtin::BI__builtin_nansf128:
13899     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13900                                true, Result))
13901       return Error(E);
13902     return true;
13903 
13904   case Builtin::BI__builtin_nan:
13905   case Builtin::BI__builtin_nanf:
13906   case Builtin::BI__builtin_nanl:
13907   case Builtin::BI__builtin_nanf16:
13908   case Builtin::BI__builtin_nanf128:
13909     // If this is __builtin_nan() turn this into a nan, otherwise we
13910     // can't constant fold it.
13911     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13912                                false, Result))
13913       return Error(E);
13914     return true;
13915 
13916   case Builtin::BI__builtin_fabs:
13917   case Builtin::BI__builtin_fabsf:
13918   case Builtin::BI__builtin_fabsl:
13919   case Builtin::BI__builtin_fabsf128:
13920     // The C standard says "fabs raises no floating-point exceptions,
13921     // even if x is a signaling NaN. The returned value is independent of
13922     // the current rounding direction mode."  Therefore constant folding can
13923     // proceed without regard to the floating point settings.
13924     // Reference, WG14 N2478 F.10.4.3
13925     if (!EvaluateFloat(E->getArg(0), Result, Info))
13926       return false;
13927 
13928     if (Result.isNegative())
13929       Result.changeSign();
13930     return true;
13931 
13932   case Builtin::BI__arithmetic_fence:
13933     return EvaluateFloat(E->getArg(0), Result, Info);
13934 
13935   // FIXME: Builtin::BI__builtin_powi
13936   // FIXME: Builtin::BI__builtin_powif
13937   // FIXME: Builtin::BI__builtin_powil
13938 
13939   case Builtin::BI__builtin_copysign:
13940   case Builtin::BI__builtin_copysignf:
13941   case Builtin::BI__builtin_copysignl:
13942   case Builtin::BI__builtin_copysignf128: {
13943     APFloat RHS(0.);
13944     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13945         !EvaluateFloat(E->getArg(1), RHS, Info))
13946       return false;
13947     Result.copySign(RHS);
13948     return true;
13949   }
13950   }
13951 }
13952 
13953 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13954   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13955     ComplexValue CV;
13956     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13957       return false;
13958     Result = CV.FloatReal;
13959     return true;
13960   }
13961 
13962   return Visit(E->getSubExpr());
13963 }
13964 
13965 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13966   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13967     ComplexValue CV;
13968     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13969       return false;
13970     Result = CV.FloatImag;
13971     return true;
13972   }
13973 
13974   VisitIgnoredValue(E->getSubExpr());
13975   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13976   Result = llvm::APFloat::getZero(Sem);
13977   return true;
13978 }
13979 
13980 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13981   switch (E->getOpcode()) {
13982   default: return Error(E);
13983   case UO_Plus:
13984     return EvaluateFloat(E->getSubExpr(), Result, Info);
13985   case UO_Minus:
13986     // In C standard, WG14 N2478 F.3 p4
13987     // "the unary - raises no floating point exceptions,
13988     // even if the operand is signalling."
13989     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13990       return false;
13991     Result.changeSign();
13992     return true;
13993   }
13994 }
13995 
13996 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13997   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13998     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13999 
14000   APFloat RHS(0.0);
14001   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14002   if (!LHSOK && !Info.noteFailure())
14003     return false;
14004   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14005          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14006 }
14007 
14008 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14009   Result = E->getValue();
14010   return true;
14011 }
14012 
14013 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14014   const Expr* SubExpr = E->getSubExpr();
14015 
14016   switch (E->getCastKind()) {
14017   default:
14018     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14019 
14020   case CK_IntegralToFloating: {
14021     APSInt IntResult;
14022     const FPOptions FPO = E->getFPFeaturesInEffect(
14023                                   Info.Ctx.getLangOpts());
14024     return EvaluateInteger(SubExpr, IntResult, Info) &&
14025            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14026                                 IntResult, E->getType(), Result);
14027   }
14028 
14029   case CK_FixedPointToFloating: {
14030     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14031     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14032       return false;
14033     Result =
14034         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14035     return true;
14036   }
14037 
14038   case CK_FloatingCast: {
14039     if (!Visit(SubExpr))
14040       return false;
14041     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14042                                   Result);
14043   }
14044 
14045   case CK_FloatingComplexToReal: {
14046     ComplexValue V;
14047     if (!EvaluateComplex(SubExpr, V, Info))
14048       return false;
14049     Result = V.getComplexFloatReal();
14050     return true;
14051   }
14052   }
14053 }
14054 
14055 //===----------------------------------------------------------------------===//
14056 // Complex Evaluation (for float and integer)
14057 //===----------------------------------------------------------------------===//
14058 
14059 namespace {
14060 class ComplexExprEvaluator
14061   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14062   ComplexValue &Result;
14063 
14064 public:
14065   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14066     : ExprEvaluatorBaseTy(info), Result(Result) {}
14067 
14068   bool Success(const APValue &V, const Expr *e) {
14069     Result.setFrom(V);
14070     return true;
14071   }
14072 
14073   bool ZeroInitialization(const Expr *E);
14074 
14075   //===--------------------------------------------------------------------===//
14076   //                            Visitor Methods
14077   //===--------------------------------------------------------------------===//
14078 
14079   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14080   bool VisitCastExpr(const CastExpr *E);
14081   bool VisitBinaryOperator(const BinaryOperator *E);
14082   bool VisitUnaryOperator(const UnaryOperator *E);
14083   bool VisitInitListExpr(const InitListExpr *E);
14084   bool VisitCallExpr(const CallExpr *E);
14085 };
14086 } // end anonymous namespace
14087 
14088 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14089                             EvalInfo &Info) {
14090   assert(!E->isValueDependent());
14091   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14092   return ComplexExprEvaluator(Info, Result).Visit(E);
14093 }
14094 
14095 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14096   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14097   if (ElemTy->isRealFloatingType()) {
14098     Result.makeComplexFloat();
14099     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14100     Result.FloatReal = Zero;
14101     Result.FloatImag = Zero;
14102   } else {
14103     Result.makeComplexInt();
14104     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14105     Result.IntReal = Zero;
14106     Result.IntImag = Zero;
14107   }
14108   return true;
14109 }
14110 
14111 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14112   const Expr* SubExpr = E->getSubExpr();
14113 
14114   if (SubExpr->getType()->isRealFloatingType()) {
14115     Result.makeComplexFloat();
14116     APFloat &Imag = Result.FloatImag;
14117     if (!EvaluateFloat(SubExpr, Imag, Info))
14118       return false;
14119 
14120     Result.FloatReal = APFloat(Imag.getSemantics());
14121     return true;
14122   } else {
14123     assert(SubExpr->getType()->isIntegerType() &&
14124            "Unexpected imaginary literal.");
14125 
14126     Result.makeComplexInt();
14127     APSInt &Imag = Result.IntImag;
14128     if (!EvaluateInteger(SubExpr, Imag, Info))
14129       return false;
14130 
14131     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14132     return true;
14133   }
14134 }
14135 
14136 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14137 
14138   switch (E->getCastKind()) {
14139   case CK_BitCast:
14140   case CK_BaseToDerived:
14141   case CK_DerivedToBase:
14142   case CK_UncheckedDerivedToBase:
14143   case CK_Dynamic:
14144   case CK_ToUnion:
14145   case CK_ArrayToPointerDecay:
14146   case CK_FunctionToPointerDecay:
14147   case CK_NullToPointer:
14148   case CK_NullToMemberPointer:
14149   case CK_BaseToDerivedMemberPointer:
14150   case CK_DerivedToBaseMemberPointer:
14151   case CK_MemberPointerToBoolean:
14152   case CK_ReinterpretMemberPointer:
14153   case CK_ConstructorConversion:
14154   case CK_IntegralToPointer:
14155   case CK_PointerToIntegral:
14156   case CK_PointerToBoolean:
14157   case CK_ToVoid:
14158   case CK_VectorSplat:
14159   case CK_IntegralCast:
14160   case CK_BooleanToSignedIntegral:
14161   case CK_IntegralToBoolean:
14162   case CK_IntegralToFloating:
14163   case CK_FloatingToIntegral:
14164   case CK_FloatingToBoolean:
14165   case CK_FloatingCast:
14166   case CK_CPointerToObjCPointerCast:
14167   case CK_BlockPointerToObjCPointerCast:
14168   case CK_AnyPointerToBlockPointerCast:
14169   case CK_ObjCObjectLValueCast:
14170   case CK_FloatingComplexToReal:
14171   case CK_FloatingComplexToBoolean:
14172   case CK_IntegralComplexToReal:
14173   case CK_IntegralComplexToBoolean:
14174   case CK_ARCProduceObject:
14175   case CK_ARCConsumeObject:
14176   case CK_ARCReclaimReturnedObject:
14177   case CK_ARCExtendBlockObject:
14178   case CK_CopyAndAutoreleaseBlockObject:
14179   case CK_BuiltinFnToFnPtr:
14180   case CK_ZeroToOCLOpaqueType:
14181   case CK_NonAtomicToAtomic:
14182   case CK_AddressSpaceConversion:
14183   case CK_IntToOCLSampler:
14184   case CK_FloatingToFixedPoint:
14185   case CK_FixedPointToFloating:
14186   case CK_FixedPointCast:
14187   case CK_FixedPointToBoolean:
14188   case CK_FixedPointToIntegral:
14189   case CK_IntegralToFixedPoint:
14190   case CK_MatrixCast:
14191     llvm_unreachable("invalid cast kind for complex value");
14192 
14193   case CK_LValueToRValue:
14194   case CK_AtomicToNonAtomic:
14195   case CK_NoOp:
14196   case CK_LValueToRValueBitCast:
14197     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14198 
14199   case CK_Dependent:
14200   case CK_LValueBitCast:
14201   case CK_UserDefinedConversion:
14202     return Error(E);
14203 
14204   case CK_FloatingRealToComplex: {
14205     APFloat &Real = Result.FloatReal;
14206     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14207       return false;
14208 
14209     Result.makeComplexFloat();
14210     Result.FloatImag = APFloat(Real.getSemantics());
14211     return true;
14212   }
14213 
14214   case CK_FloatingComplexCast: {
14215     if (!Visit(E->getSubExpr()))
14216       return false;
14217 
14218     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14219     QualType From
14220       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14221 
14222     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14223            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14224   }
14225 
14226   case CK_FloatingComplexToIntegralComplex: {
14227     if (!Visit(E->getSubExpr()))
14228       return false;
14229 
14230     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14231     QualType From
14232       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14233     Result.makeComplexInt();
14234     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14235                                 To, Result.IntReal) &&
14236            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14237                                 To, Result.IntImag);
14238   }
14239 
14240   case CK_IntegralRealToComplex: {
14241     APSInt &Real = Result.IntReal;
14242     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14243       return false;
14244 
14245     Result.makeComplexInt();
14246     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14247     return true;
14248   }
14249 
14250   case CK_IntegralComplexCast: {
14251     if (!Visit(E->getSubExpr()))
14252       return false;
14253 
14254     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14255     QualType From
14256       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14257 
14258     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14259     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14260     return true;
14261   }
14262 
14263   case CK_IntegralComplexToFloatingComplex: {
14264     if (!Visit(E->getSubExpr()))
14265       return false;
14266 
14267     const FPOptions FPO = E->getFPFeaturesInEffect(
14268                                   Info.Ctx.getLangOpts());
14269     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14270     QualType From
14271       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14272     Result.makeComplexFloat();
14273     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14274                                 To, Result.FloatReal) &&
14275            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14276                                 To, Result.FloatImag);
14277   }
14278   }
14279 
14280   llvm_unreachable("unknown cast resulting in complex value");
14281 }
14282 
14283 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14284   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14285     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14286 
14287   // Track whether the LHS or RHS is real at the type system level. When this is
14288   // the case we can simplify our evaluation strategy.
14289   bool LHSReal = false, RHSReal = false;
14290 
14291   bool LHSOK;
14292   if (E->getLHS()->getType()->isRealFloatingType()) {
14293     LHSReal = true;
14294     APFloat &Real = Result.FloatReal;
14295     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14296     if (LHSOK) {
14297       Result.makeComplexFloat();
14298       Result.FloatImag = APFloat(Real.getSemantics());
14299     }
14300   } else {
14301     LHSOK = Visit(E->getLHS());
14302   }
14303   if (!LHSOK && !Info.noteFailure())
14304     return false;
14305 
14306   ComplexValue RHS;
14307   if (E->getRHS()->getType()->isRealFloatingType()) {
14308     RHSReal = true;
14309     APFloat &Real = RHS.FloatReal;
14310     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14311       return false;
14312     RHS.makeComplexFloat();
14313     RHS.FloatImag = APFloat(Real.getSemantics());
14314   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14315     return false;
14316 
14317   assert(!(LHSReal && RHSReal) &&
14318          "Cannot have both operands of a complex operation be real.");
14319   switch (E->getOpcode()) {
14320   default: return Error(E);
14321   case BO_Add:
14322     if (Result.isComplexFloat()) {
14323       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14324                                        APFloat::rmNearestTiesToEven);
14325       if (LHSReal)
14326         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14327       else if (!RHSReal)
14328         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14329                                          APFloat::rmNearestTiesToEven);
14330     } else {
14331       Result.getComplexIntReal() += RHS.getComplexIntReal();
14332       Result.getComplexIntImag() += RHS.getComplexIntImag();
14333     }
14334     break;
14335   case BO_Sub:
14336     if (Result.isComplexFloat()) {
14337       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14338                                             APFloat::rmNearestTiesToEven);
14339       if (LHSReal) {
14340         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14341         Result.getComplexFloatImag().changeSign();
14342       } else if (!RHSReal) {
14343         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14344                                               APFloat::rmNearestTiesToEven);
14345       }
14346     } else {
14347       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14348       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14349     }
14350     break;
14351   case BO_Mul:
14352     if (Result.isComplexFloat()) {
14353       // This is an implementation of complex multiplication according to the
14354       // constraints laid out in C11 Annex G. The implementation uses the
14355       // following naming scheme:
14356       //   (a + ib) * (c + id)
14357       ComplexValue LHS = Result;
14358       APFloat &A = LHS.getComplexFloatReal();
14359       APFloat &B = LHS.getComplexFloatImag();
14360       APFloat &C = RHS.getComplexFloatReal();
14361       APFloat &D = RHS.getComplexFloatImag();
14362       APFloat &ResR = Result.getComplexFloatReal();
14363       APFloat &ResI = Result.getComplexFloatImag();
14364       if (LHSReal) {
14365         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14366         ResR = A * C;
14367         ResI = A * D;
14368       } else if (RHSReal) {
14369         ResR = C * A;
14370         ResI = C * B;
14371       } else {
14372         // In the fully general case, we need to handle NaNs and infinities
14373         // robustly.
14374         APFloat AC = A * C;
14375         APFloat BD = B * D;
14376         APFloat AD = A * D;
14377         APFloat BC = B * C;
14378         ResR = AC - BD;
14379         ResI = AD + BC;
14380         if (ResR.isNaN() && ResI.isNaN()) {
14381           bool Recalc = false;
14382           if (A.isInfinity() || B.isInfinity()) {
14383             A = APFloat::copySign(
14384                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14385             B = APFloat::copySign(
14386                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14387             if (C.isNaN())
14388               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14389             if (D.isNaN())
14390               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14391             Recalc = true;
14392           }
14393           if (C.isInfinity() || D.isInfinity()) {
14394             C = APFloat::copySign(
14395                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14396             D = APFloat::copySign(
14397                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14398             if (A.isNaN())
14399               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14400             if (B.isNaN())
14401               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14402             Recalc = true;
14403           }
14404           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14405                           AD.isInfinity() || BC.isInfinity())) {
14406             if (A.isNaN())
14407               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14408             if (B.isNaN())
14409               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14410             if (C.isNaN())
14411               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14412             if (D.isNaN())
14413               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14414             Recalc = true;
14415           }
14416           if (Recalc) {
14417             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14418             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14419           }
14420         }
14421       }
14422     } else {
14423       ComplexValue LHS = Result;
14424       Result.getComplexIntReal() =
14425         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14426          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14427       Result.getComplexIntImag() =
14428         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14429          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14430     }
14431     break;
14432   case BO_Div:
14433     if (Result.isComplexFloat()) {
14434       // This is an implementation of complex division according to the
14435       // constraints laid out in C11 Annex G. The implementation uses the
14436       // following naming scheme:
14437       //   (a + ib) / (c + id)
14438       ComplexValue LHS = Result;
14439       APFloat &A = LHS.getComplexFloatReal();
14440       APFloat &B = LHS.getComplexFloatImag();
14441       APFloat &C = RHS.getComplexFloatReal();
14442       APFloat &D = RHS.getComplexFloatImag();
14443       APFloat &ResR = Result.getComplexFloatReal();
14444       APFloat &ResI = Result.getComplexFloatImag();
14445       if (RHSReal) {
14446         ResR = A / C;
14447         ResI = B / C;
14448       } else {
14449         if (LHSReal) {
14450           // No real optimizations we can do here, stub out with zero.
14451           B = APFloat::getZero(A.getSemantics());
14452         }
14453         int DenomLogB = 0;
14454         APFloat MaxCD = maxnum(abs(C), abs(D));
14455         if (MaxCD.isFinite()) {
14456           DenomLogB = ilogb(MaxCD);
14457           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14458           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14459         }
14460         APFloat Denom = C * C + D * D;
14461         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14462                       APFloat::rmNearestTiesToEven);
14463         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14464                       APFloat::rmNearestTiesToEven);
14465         if (ResR.isNaN() && ResI.isNaN()) {
14466           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14467             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14468             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14469           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14470                      D.isFinite()) {
14471             A = APFloat::copySign(
14472                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14473             B = APFloat::copySign(
14474                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14475             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14476             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14477           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14478             C = APFloat::copySign(
14479                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14480             D = APFloat::copySign(
14481                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14482             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14483             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14484           }
14485         }
14486       }
14487     } else {
14488       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14489         return Error(E, diag::note_expr_divide_by_zero);
14490 
14491       ComplexValue LHS = Result;
14492       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14493         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14494       Result.getComplexIntReal() =
14495         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14496          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14497       Result.getComplexIntImag() =
14498         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14499          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14500     }
14501     break;
14502   }
14503 
14504   return true;
14505 }
14506 
14507 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14508   // Get the operand value into 'Result'.
14509   if (!Visit(E->getSubExpr()))
14510     return false;
14511 
14512   switch (E->getOpcode()) {
14513   default:
14514     return Error(E);
14515   case UO_Extension:
14516     return true;
14517   case UO_Plus:
14518     // The result is always just the subexpr.
14519     return true;
14520   case UO_Minus:
14521     if (Result.isComplexFloat()) {
14522       Result.getComplexFloatReal().changeSign();
14523       Result.getComplexFloatImag().changeSign();
14524     }
14525     else {
14526       Result.getComplexIntReal() = -Result.getComplexIntReal();
14527       Result.getComplexIntImag() = -Result.getComplexIntImag();
14528     }
14529     return true;
14530   case UO_Not:
14531     if (Result.isComplexFloat())
14532       Result.getComplexFloatImag().changeSign();
14533     else
14534       Result.getComplexIntImag() = -Result.getComplexIntImag();
14535     return true;
14536   }
14537 }
14538 
14539 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14540   if (E->getNumInits() == 2) {
14541     if (E->getType()->isComplexType()) {
14542       Result.makeComplexFloat();
14543       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14544         return false;
14545       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14546         return false;
14547     } else {
14548       Result.makeComplexInt();
14549       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14550         return false;
14551       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14552         return false;
14553     }
14554     return true;
14555   }
14556   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14557 }
14558 
14559 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14560   switch (E->getBuiltinCallee()) {
14561   case Builtin::BI__builtin_complex:
14562     Result.makeComplexFloat();
14563     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14564       return false;
14565     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14566       return false;
14567     return true;
14568 
14569   default:
14570     break;
14571   }
14572 
14573   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14574 }
14575 
14576 //===----------------------------------------------------------------------===//
14577 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14578 // implicit conversion.
14579 //===----------------------------------------------------------------------===//
14580 
14581 namespace {
14582 class AtomicExprEvaluator :
14583     public ExprEvaluatorBase<AtomicExprEvaluator> {
14584   const LValue *This;
14585   APValue &Result;
14586 public:
14587   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14588       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14589 
14590   bool Success(const APValue &V, const Expr *E) {
14591     Result = V;
14592     return true;
14593   }
14594 
14595   bool ZeroInitialization(const Expr *E) {
14596     ImplicitValueInitExpr VIE(
14597         E->getType()->castAs<AtomicType>()->getValueType());
14598     // For atomic-qualified class (and array) types in C++, initialize the
14599     // _Atomic-wrapped subobject directly, in-place.
14600     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14601                 : Evaluate(Result, Info, &VIE);
14602   }
14603 
14604   bool VisitCastExpr(const CastExpr *E) {
14605     switch (E->getCastKind()) {
14606     default:
14607       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14608     case CK_NonAtomicToAtomic:
14609       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14610                   : Evaluate(Result, Info, E->getSubExpr());
14611     }
14612   }
14613 };
14614 } // end anonymous namespace
14615 
14616 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14617                            EvalInfo &Info) {
14618   assert(!E->isValueDependent());
14619   assert(E->isPRValue() && E->getType()->isAtomicType());
14620   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14621 }
14622 
14623 //===----------------------------------------------------------------------===//
14624 // Void expression evaluation, primarily for a cast to void on the LHS of a
14625 // comma operator
14626 //===----------------------------------------------------------------------===//
14627 
14628 namespace {
14629 class VoidExprEvaluator
14630   : public ExprEvaluatorBase<VoidExprEvaluator> {
14631 public:
14632   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14633 
14634   bool Success(const APValue &V, const Expr *e) { return true; }
14635 
14636   bool ZeroInitialization(const Expr *E) { return true; }
14637 
14638   bool VisitCastExpr(const CastExpr *E) {
14639     switch (E->getCastKind()) {
14640     default:
14641       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14642     case CK_ToVoid:
14643       VisitIgnoredValue(E->getSubExpr());
14644       return true;
14645     }
14646   }
14647 
14648   bool VisitCallExpr(const CallExpr *E) {
14649     switch (E->getBuiltinCallee()) {
14650     case Builtin::BI__assume:
14651     case Builtin::BI__builtin_assume:
14652       // The argument is not evaluated!
14653       return true;
14654 
14655     case Builtin::BI__builtin_operator_delete:
14656       return HandleOperatorDeleteCall(Info, E);
14657 
14658     default:
14659       break;
14660     }
14661 
14662     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14663   }
14664 
14665   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14666 };
14667 } // end anonymous namespace
14668 
14669 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14670   // We cannot speculatively evaluate a delete expression.
14671   if (Info.SpeculativeEvaluationDepth)
14672     return false;
14673 
14674   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14675   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14676     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14677         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14678     return false;
14679   }
14680 
14681   const Expr *Arg = E->getArgument();
14682 
14683   LValue Pointer;
14684   if (!EvaluatePointer(Arg, Pointer, Info))
14685     return false;
14686   if (Pointer.Designator.Invalid)
14687     return false;
14688 
14689   // Deleting a null pointer has no effect.
14690   if (Pointer.isNullPointer()) {
14691     // This is the only case where we need to produce an extension warning:
14692     // the only other way we can succeed is if we find a dynamic allocation,
14693     // and we will have warned when we allocated it in that case.
14694     if (!Info.getLangOpts().CPlusPlus20)
14695       Info.CCEDiag(E, diag::note_constexpr_new);
14696     return true;
14697   }
14698 
14699   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14700       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14701   if (!Alloc)
14702     return false;
14703   QualType AllocType = Pointer.Base.getDynamicAllocType();
14704 
14705   // For the non-array case, the designator must be empty if the static type
14706   // does not have a virtual destructor.
14707   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14708       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14709     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14710         << Arg->getType()->getPointeeType() << AllocType;
14711     return false;
14712   }
14713 
14714   // For a class type with a virtual destructor, the selected operator delete
14715   // is the one looked up when building the destructor.
14716   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14717     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14718     if (VirtualDelete &&
14719         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14720       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14721           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14722       return false;
14723     }
14724   }
14725 
14726   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14727                          (*Alloc)->Value, AllocType))
14728     return false;
14729 
14730   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14731     // The element was already erased. This means the destructor call also
14732     // deleted the object.
14733     // FIXME: This probably results in undefined behavior before we get this
14734     // far, and should be diagnosed elsewhere first.
14735     Info.FFDiag(E, diag::note_constexpr_double_delete);
14736     return false;
14737   }
14738 
14739   return true;
14740 }
14741 
14742 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14743   assert(!E->isValueDependent());
14744   assert(E->isPRValue() && E->getType()->isVoidType());
14745   return VoidExprEvaluator(Info).Visit(E);
14746 }
14747 
14748 //===----------------------------------------------------------------------===//
14749 // Top level Expr::EvaluateAsRValue method.
14750 //===----------------------------------------------------------------------===//
14751 
14752 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14753   assert(!E->isValueDependent());
14754   // In C, function designators are not lvalues, but we evaluate them as if they
14755   // are.
14756   QualType T = E->getType();
14757   if (E->isGLValue() || T->isFunctionType()) {
14758     LValue LV;
14759     if (!EvaluateLValue(E, LV, Info))
14760       return false;
14761     LV.moveInto(Result);
14762   } else if (T->isVectorType()) {
14763     if (!EvaluateVector(E, Result, Info))
14764       return false;
14765   } else if (T->isIntegralOrEnumerationType()) {
14766     if (!IntExprEvaluator(Info, Result).Visit(E))
14767       return false;
14768   } else if (T->hasPointerRepresentation()) {
14769     LValue LV;
14770     if (!EvaluatePointer(E, LV, Info))
14771       return false;
14772     LV.moveInto(Result);
14773   } else if (T->isRealFloatingType()) {
14774     llvm::APFloat F(0.0);
14775     if (!EvaluateFloat(E, F, Info))
14776       return false;
14777     Result = APValue(F);
14778   } else if (T->isAnyComplexType()) {
14779     ComplexValue C;
14780     if (!EvaluateComplex(E, C, Info))
14781       return false;
14782     C.moveInto(Result);
14783   } else if (T->isFixedPointType()) {
14784     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14785   } else if (T->isMemberPointerType()) {
14786     MemberPtr P;
14787     if (!EvaluateMemberPointer(E, P, Info))
14788       return false;
14789     P.moveInto(Result);
14790     return true;
14791   } else if (T->isArrayType()) {
14792     LValue LV;
14793     APValue &Value =
14794         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14795     if (!EvaluateArray(E, LV, Value, Info))
14796       return false;
14797     Result = Value;
14798   } else if (T->isRecordType()) {
14799     LValue LV;
14800     APValue &Value =
14801         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14802     if (!EvaluateRecord(E, LV, Value, Info))
14803       return false;
14804     Result = Value;
14805   } else if (T->isVoidType()) {
14806     if (!Info.getLangOpts().CPlusPlus11)
14807       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14808         << E->getType();
14809     if (!EvaluateVoid(E, Info))
14810       return false;
14811   } else if (T->isAtomicType()) {
14812     QualType Unqual = T.getAtomicUnqualifiedType();
14813     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14814       LValue LV;
14815       APValue &Value = Info.CurrentCall->createTemporary(
14816           E, Unqual, ScopeKind::FullExpression, LV);
14817       if (!EvaluateAtomic(E, &LV, Value, Info))
14818         return false;
14819     } else {
14820       if (!EvaluateAtomic(E, nullptr, Result, Info))
14821         return false;
14822     }
14823   } else if (Info.getLangOpts().CPlusPlus11) {
14824     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14825     return false;
14826   } else {
14827     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14828     return false;
14829   }
14830 
14831   return true;
14832 }
14833 
14834 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14835 /// cases, the in-place evaluation is essential, since later initializers for
14836 /// an object can indirectly refer to subobjects which were initialized earlier.
14837 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14838                             const Expr *E, bool AllowNonLiteralTypes) {
14839   assert(!E->isValueDependent());
14840 
14841   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14842     return false;
14843 
14844   if (E->isPRValue()) {
14845     // Evaluate arrays and record types in-place, so that later initializers can
14846     // refer to earlier-initialized members of the object.
14847     QualType T = E->getType();
14848     if (T->isArrayType())
14849       return EvaluateArray(E, This, Result, Info);
14850     else if (T->isRecordType())
14851       return EvaluateRecord(E, This, Result, Info);
14852     else if (T->isAtomicType()) {
14853       QualType Unqual = T.getAtomicUnqualifiedType();
14854       if (Unqual->isArrayType() || Unqual->isRecordType())
14855         return EvaluateAtomic(E, &This, Result, Info);
14856     }
14857   }
14858 
14859   // For any other type, in-place evaluation is unimportant.
14860   return Evaluate(Result, Info, E);
14861 }
14862 
14863 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14864 /// lvalue-to-rvalue cast if it is an lvalue.
14865 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14866   assert(!E->isValueDependent());
14867   if (Info.EnableNewConstInterp) {
14868     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14869       return false;
14870   } else {
14871     if (E->getType().isNull())
14872       return false;
14873 
14874     if (!CheckLiteralType(Info, E))
14875       return false;
14876 
14877     if (!::Evaluate(Result, Info, E))
14878       return false;
14879 
14880     if (E->isGLValue()) {
14881       LValue LV;
14882       LV.setFrom(Info.Ctx, Result);
14883       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14884         return false;
14885     }
14886   }
14887 
14888   // Check this core constant expression is a constant expression.
14889   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14890                                  ConstantExprKind::Normal) &&
14891          CheckMemoryLeaks(Info);
14892 }
14893 
14894 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14895                                  const ASTContext &Ctx, bool &IsConst) {
14896   // Fast-path evaluations of integer literals, since we sometimes see files
14897   // containing vast quantities of these.
14898   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14899     Result.Val = APValue(APSInt(L->getValue(),
14900                                 L->getType()->isUnsignedIntegerType()));
14901     IsConst = true;
14902     return true;
14903   }
14904 
14905   // This case should be rare, but we need to check it before we check on
14906   // the type below.
14907   if (Exp->getType().isNull()) {
14908     IsConst = false;
14909     return true;
14910   }
14911 
14912   // FIXME: Evaluating values of large array and record types can cause
14913   // performance problems. Only do so in C++11 for now.
14914   if (Exp->isPRValue() &&
14915       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14916       !Ctx.getLangOpts().CPlusPlus11) {
14917     IsConst = false;
14918     return true;
14919   }
14920   return false;
14921 }
14922 
14923 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14924                                       Expr::SideEffectsKind SEK) {
14925   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14926          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14927 }
14928 
14929 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14930                              const ASTContext &Ctx, EvalInfo &Info) {
14931   assert(!E->isValueDependent());
14932   bool IsConst;
14933   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14934     return IsConst;
14935 
14936   return EvaluateAsRValue(Info, E, Result.Val);
14937 }
14938 
14939 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14940                           const ASTContext &Ctx,
14941                           Expr::SideEffectsKind AllowSideEffects,
14942                           EvalInfo &Info) {
14943   assert(!E->isValueDependent());
14944   if (!E->getType()->isIntegralOrEnumerationType())
14945     return false;
14946 
14947   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14948       !ExprResult.Val.isInt() ||
14949       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14950     return false;
14951 
14952   return true;
14953 }
14954 
14955 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14956                                  const ASTContext &Ctx,
14957                                  Expr::SideEffectsKind AllowSideEffects,
14958                                  EvalInfo &Info) {
14959   assert(!E->isValueDependent());
14960   if (!E->getType()->isFixedPointType())
14961     return false;
14962 
14963   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14964     return false;
14965 
14966   if (!ExprResult.Val.isFixedPoint() ||
14967       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14968     return false;
14969 
14970   return true;
14971 }
14972 
14973 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14974 /// any crazy technique (that has nothing to do with language standards) that
14975 /// we want to.  If this function returns true, it returns the folded constant
14976 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14977 /// will be applied to the result.
14978 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14979                             bool InConstantContext) const {
14980   assert(!isValueDependent() &&
14981          "Expression evaluator can't be called on a dependent expression.");
14982   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14983   Info.InConstantContext = InConstantContext;
14984   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14985 }
14986 
14987 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14988                                       bool InConstantContext) const {
14989   assert(!isValueDependent() &&
14990          "Expression evaluator can't be called on a dependent expression.");
14991   EvalResult Scratch;
14992   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14993          HandleConversionToBool(Scratch.Val, Result);
14994 }
14995 
14996 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14997                          SideEffectsKind AllowSideEffects,
14998                          bool InConstantContext) const {
14999   assert(!isValueDependent() &&
15000          "Expression evaluator can't be called on a dependent expression.");
15001   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15002   Info.InConstantContext = InConstantContext;
15003   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15004 }
15005 
15006 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15007                                 SideEffectsKind AllowSideEffects,
15008                                 bool InConstantContext) const {
15009   assert(!isValueDependent() &&
15010          "Expression evaluator can't be called on a dependent expression.");
15011   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15012   Info.InConstantContext = InConstantContext;
15013   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15014 }
15015 
15016 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15017                            SideEffectsKind AllowSideEffects,
15018                            bool InConstantContext) const {
15019   assert(!isValueDependent() &&
15020          "Expression evaluator can't be called on a dependent expression.");
15021 
15022   if (!getType()->isRealFloatingType())
15023     return false;
15024 
15025   EvalResult ExprResult;
15026   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15027       !ExprResult.Val.isFloat() ||
15028       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15029     return false;
15030 
15031   Result = ExprResult.Val.getFloat();
15032   return true;
15033 }
15034 
15035 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15036                             bool InConstantContext) const {
15037   assert(!isValueDependent() &&
15038          "Expression evaluator can't be called on a dependent expression.");
15039 
15040   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15041   Info.InConstantContext = InConstantContext;
15042   LValue LV;
15043   CheckedTemporaries CheckedTemps;
15044   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15045       Result.HasSideEffects ||
15046       !CheckLValueConstantExpression(Info, getExprLoc(),
15047                                      Ctx.getLValueReferenceType(getType()), LV,
15048                                      ConstantExprKind::Normal, CheckedTemps))
15049     return false;
15050 
15051   LV.moveInto(Result.Val);
15052   return true;
15053 }
15054 
15055 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15056                                 APValue DestroyedValue, QualType Type,
15057                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15058                                 bool IsConstantDestruction) {
15059   EvalInfo Info(Ctx, EStatus,
15060                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15061                                       : EvalInfo::EM_ConstantFold);
15062   Info.setEvaluatingDecl(Base, DestroyedValue,
15063                          EvalInfo::EvaluatingDeclKind::Dtor);
15064   Info.InConstantContext = IsConstantDestruction;
15065 
15066   LValue LVal;
15067   LVal.set(Base);
15068 
15069   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15070       EStatus.HasSideEffects)
15071     return false;
15072 
15073   if (!Info.discardCleanups())
15074     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15075 
15076   return true;
15077 }
15078 
15079 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15080                                   ConstantExprKind Kind) const {
15081   assert(!isValueDependent() &&
15082          "Expression evaluator can't be called on a dependent expression.");
15083 
15084   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15085   EvalInfo Info(Ctx, Result, EM);
15086   Info.InConstantContext = true;
15087 
15088   // The type of the object we're initializing is 'const T' for a class NTTP.
15089   QualType T = getType();
15090   if (Kind == ConstantExprKind::ClassTemplateArgument)
15091     T.addConst();
15092 
15093   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15094   // represent the result of the evaluation. CheckConstantExpression ensures
15095   // this doesn't escape.
15096   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15097   APValue::LValueBase Base(&BaseMTE);
15098 
15099   Info.setEvaluatingDecl(Base, Result.Val);
15100   LValue LVal;
15101   LVal.set(Base);
15102 
15103   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15104     return false;
15105 
15106   if (!Info.discardCleanups())
15107     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15108 
15109   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15110                                Result.Val, Kind))
15111     return false;
15112   if (!CheckMemoryLeaks(Info))
15113     return false;
15114 
15115   // If this is a class template argument, it's required to have constant
15116   // destruction too.
15117   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15118       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15119                             true) ||
15120        Result.HasSideEffects)) {
15121     // FIXME: Prefix a note to indicate that the problem is lack of constant
15122     // destruction.
15123     return false;
15124   }
15125 
15126   return true;
15127 }
15128 
15129 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15130                                  const VarDecl *VD,
15131                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15132   assert(!isValueDependent() &&
15133          "Expression evaluator can't be called on a dependent expression.");
15134 
15135   // FIXME: Evaluating initializers for large array and record types can cause
15136   // performance problems. Only do so in C++11 for now.
15137   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15138       !Ctx.getLangOpts().CPlusPlus11)
15139     return false;
15140 
15141   Expr::EvalStatus EStatus;
15142   EStatus.Diag = &Notes;
15143 
15144   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
15145                                       ? EvalInfo::EM_ConstantExpression
15146                                       : EvalInfo::EM_ConstantFold);
15147   Info.setEvaluatingDecl(VD, Value);
15148   Info.InConstantContext = true;
15149 
15150   SourceLocation DeclLoc = VD->getLocation();
15151   QualType DeclTy = VD->getType();
15152 
15153   if (Info.EnableNewConstInterp) {
15154     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15155     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15156       return false;
15157   } else {
15158     LValue LVal;
15159     LVal.set(VD);
15160 
15161     if (!EvaluateInPlace(Value, Info, LVal, this,
15162                          /*AllowNonLiteralTypes=*/true) ||
15163         EStatus.HasSideEffects)
15164       return false;
15165 
15166     // At this point, any lifetime-extended temporaries are completely
15167     // initialized.
15168     Info.performLifetimeExtension();
15169 
15170     if (!Info.discardCleanups())
15171       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15172   }
15173   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15174                                  ConstantExprKind::Normal) &&
15175          CheckMemoryLeaks(Info);
15176 }
15177 
15178 bool VarDecl::evaluateDestruction(
15179     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15180   Expr::EvalStatus EStatus;
15181   EStatus.Diag = &Notes;
15182 
15183   // Only treat the destruction as constant destruction if we formally have
15184   // constant initialization (or are usable in a constant expression).
15185   bool IsConstantDestruction = hasConstantInitialization();
15186 
15187   // Make a copy of the value for the destructor to mutate, if we know it.
15188   // Otherwise, treat the value as default-initialized; if the destructor works
15189   // anyway, then the destruction is constant (and must be essentially empty).
15190   APValue DestroyedValue;
15191   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15192     DestroyedValue = *getEvaluatedValue();
15193   else if (!getDefaultInitValue(getType(), DestroyedValue))
15194     return false;
15195 
15196   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15197                            getType(), getLocation(), EStatus,
15198                            IsConstantDestruction) ||
15199       EStatus.HasSideEffects)
15200     return false;
15201 
15202   ensureEvaluatedStmt()->HasConstantDestruction = true;
15203   return true;
15204 }
15205 
15206 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15207 /// constant folded, but discard the result.
15208 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15209   assert(!isValueDependent() &&
15210          "Expression evaluator can't be called on a dependent expression.");
15211 
15212   EvalResult Result;
15213   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15214          !hasUnacceptableSideEffect(Result, SEK);
15215 }
15216 
15217 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15218                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15219   assert(!isValueDependent() &&
15220          "Expression evaluator can't be called on a dependent expression.");
15221 
15222   EvalResult EVResult;
15223   EVResult.Diag = Diag;
15224   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15225   Info.InConstantContext = true;
15226 
15227   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15228   (void)Result;
15229   assert(Result && "Could not evaluate expression");
15230   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15231 
15232   return EVResult.Val.getInt();
15233 }
15234 
15235 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15236     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15237   assert(!isValueDependent() &&
15238          "Expression evaluator can't be called on a dependent expression.");
15239 
15240   EvalResult EVResult;
15241   EVResult.Diag = Diag;
15242   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15243   Info.InConstantContext = true;
15244   Info.CheckingForUndefinedBehavior = true;
15245 
15246   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15247   (void)Result;
15248   assert(Result && "Could not evaluate expression");
15249   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15250 
15251   return EVResult.Val.getInt();
15252 }
15253 
15254 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15255   assert(!isValueDependent() &&
15256          "Expression evaluator can't be called on a dependent expression.");
15257 
15258   bool IsConst;
15259   EvalResult EVResult;
15260   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15261     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15262     Info.CheckingForUndefinedBehavior = true;
15263     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15264   }
15265 }
15266 
15267 bool Expr::EvalResult::isGlobalLValue() const {
15268   assert(Val.isLValue());
15269   return IsGlobalLValue(Val.getLValueBase());
15270 }
15271 
15272 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15273 /// an integer constant expression.
15274 
15275 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15276 /// comma, etc
15277 
15278 // CheckICE - This function does the fundamental ICE checking: the returned
15279 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15280 // and a (possibly null) SourceLocation indicating the location of the problem.
15281 //
15282 // Note that to reduce code duplication, this helper does no evaluation
15283 // itself; the caller checks whether the expression is evaluatable, and
15284 // in the rare cases where CheckICE actually cares about the evaluated
15285 // value, it calls into Evaluate.
15286 
15287 namespace {
15288 
15289 enum ICEKind {
15290   /// This expression is an ICE.
15291   IK_ICE,
15292   /// This expression is not an ICE, but if it isn't evaluated, it's
15293   /// a legal subexpression for an ICE. This return value is used to handle
15294   /// the comma operator in C99 mode, and non-constant subexpressions.
15295   IK_ICEIfUnevaluated,
15296   /// This expression is not an ICE, and is not a legal subexpression for one.
15297   IK_NotICE
15298 };
15299 
15300 struct ICEDiag {
15301   ICEKind Kind;
15302   SourceLocation Loc;
15303 
15304   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15305 };
15306 
15307 }
15308 
15309 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15310 
15311 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15312 
15313 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15314   Expr::EvalResult EVResult;
15315   Expr::EvalStatus Status;
15316   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15317 
15318   Info.InConstantContext = true;
15319   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15320       !EVResult.Val.isInt())
15321     return ICEDiag(IK_NotICE, E->getBeginLoc());
15322 
15323   return NoDiag();
15324 }
15325 
15326 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15327   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15328   if (!E->getType()->isIntegralOrEnumerationType())
15329     return ICEDiag(IK_NotICE, E->getBeginLoc());
15330 
15331   switch (E->getStmtClass()) {
15332 #define ABSTRACT_STMT(Node)
15333 #define STMT(Node, Base) case Expr::Node##Class:
15334 #define EXPR(Node, Base)
15335 #include "clang/AST/StmtNodes.inc"
15336   case Expr::PredefinedExprClass:
15337   case Expr::FloatingLiteralClass:
15338   case Expr::ImaginaryLiteralClass:
15339   case Expr::StringLiteralClass:
15340   case Expr::ArraySubscriptExprClass:
15341   case Expr::MatrixSubscriptExprClass:
15342   case Expr::OMPArraySectionExprClass:
15343   case Expr::OMPArrayShapingExprClass:
15344   case Expr::OMPIteratorExprClass:
15345   case Expr::MemberExprClass:
15346   case Expr::CompoundAssignOperatorClass:
15347   case Expr::CompoundLiteralExprClass:
15348   case Expr::ExtVectorElementExprClass:
15349   case Expr::DesignatedInitExprClass:
15350   case Expr::ArrayInitLoopExprClass:
15351   case Expr::ArrayInitIndexExprClass:
15352   case Expr::NoInitExprClass:
15353   case Expr::DesignatedInitUpdateExprClass:
15354   case Expr::ImplicitValueInitExprClass:
15355   case Expr::ParenListExprClass:
15356   case Expr::VAArgExprClass:
15357   case Expr::AddrLabelExprClass:
15358   case Expr::StmtExprClass:
15359   case Expr::CXXMemberCallExprClass:
15360   case Expr::CUDAKernelCallExprClass:
15361   case Expr::CXXAddrspaceCastExprClass:
15362   case Expr::CXXDynamicCastExprClass:
15363   case Expr::CXXTypeidExprClass:
15364   case Expr::CXXUuidofExprClass:
15365   case Expr::MSPropertyRefExprClass:
15366   case Expr::MSPropertySubscriptExprClass:
15367   case Expr::CXXNullPtrLiteralExprClass:
15368   case Expr::UserDefinedLiteralClass:
15369   case Expr::CXXThisExprClass:
15370   case Expr::CXXThrowExprClass:
15371   case Expr::CXXNewExprClass:
15372   case Expr::CXXDeleteExprClass:
15373   case Expr::CXXPseudoDestructorExprClass:
15374   case Expr::UnresolvedLookupExprClass:
15375   case Expr::TypoExprClass:
15376   case Expr::RecoveryExprClass:
15377   case Expr::DependentScopeDeclRefExprClass:
15378   case Expr::CXXConstructExprClass:
15379   case Expr::CXXInheritedCtorInitExprClass:
15380   case Expr::CXXStdInitializerListExprClass:
15381   case Expr::CXXBindTemporaryExprClass:
15382   case Expr::ExprWithCleanupsClass:
15383   case Expr::CXXTemporaryObjectExprClass:
15384   case Expr::CXXUnresolvedConstructExprClass:
15385   case Expr::CXXDependentScopeMemberExprClass:
15386   case Expr::UnresolvedMemberExprClass:
15387   case Expr::ObjCStringLiteralClass:
15388   case Expr::ObjCBoxedExprClass:
15389   case Expr::ObjCArrayLiteralClass:
15390   case Expr::ObjCDictionaryLiteralClass:
15391   case Expr::ObjCEncodeExprClass:
15392   case Expr::ObjCMessageExprClass:
15393   case Expr::ObjCSelectorExprClass:
15394   case Expr::ObjCProtocolExprClass:
15395   case Expr::ObjCIvarRefExprClass:
15396   case Expr::ObjCPropertyRefExprClass:
15397   case Expr::ObjCSubscriptRefExprClass:
15398   case Expr::ObjCIsaExprClass:
15399   case Expr::ObjCAvailabilityCheckExprClass:
15400   case Expr::ShuffleVectorExprClass:
15401   case Expr::ConvertVectorExprClass:
15402   case Expr::BlockExprClass:
15403   case Expr::NoStmtClass:
15404   case Expr::OpaqueValueExprClass:
15405   case Expr::PackExpansionExprClass:
15406   case Expr::SubstNonTypeTemplateParmPackExprClass:
15407   case Expr::FunctionParmPackExprClass:
15408   case Expr::AsTypeExprClass:
15409   case Expr::ObjCIndirectCopyRestoreExprClass:
15410   case Expr::MaterializeTemporaryExprClass:
15411   case Expr::PseudoObjectExprClass:
15412   case Expr::AtomicExprClass:
15413   case Expr::LambdaExprClass:
15414   case Expr::CXXFoldExprClass:
15415   case Expr::CoawaitExprClass:
15416   case Expr::DependentCoawaitExprClass:
15417   case Expr::CoyieldExprClass:
15418   case Expr::SYCLUniqueStableNameExprClass:
15419     return ICEDiag(IK_NotICE, E->getBeginLoc());
15420 
15421   case Expr::InitListExprClass: {
15422     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15423     // form "T x = { a };" is equivalent to "T x = a;".
15424     // Unless we're initializing a reference, T is a scalar as it is known to be
15425     // of integral or enumeration type.
15426     if (E->isPRValue())
15427       if (cast<InitListExpr>(E)->getNumInits() == 1)
15428         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15429     return ICEDiag(IK_NotICE, E->getBeginLoc());
15430   }
15431 
15432   case Expr::SizeOfPackExprClass:
15433   case Expr::GNUNullExprClass:
15434   case Expr::SourceLocExprClass:
15435     return NoDiag();
15436 
15437   case Expr::SubstNonTypeTemplateParmExprClass:
15438     return
15439       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15440 
15441   case Expr::ConstantExprClass:
15442     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15443 
15444   case Expr::ParenExprClass:
15445     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15446   case Expr::GenericSelectionExprClass:
15447     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15448   case Expr::IntegerLiteralClass:
15449   case Expr::FixedPointLiteralClass:
15450   case Expr::CharacterLiteralClass:
15451   case Expr::ObjCBoolLiteralExprClass:
15452   case Expr::CXXBoolLiteralExprClass:
15453   case Expr::CXXScalarValueInitExprClass:
15454   case Expr::TypeTraitExprClass:
15455   case Expr::ConceptSpecializationExprClass:
15456   case Expr::RequiresExprClass:
15457   case Expr::ArrayTypeTraitExprClass:
15458   case Expr::ExpressionTraitExprClass:
15459   case Expr::CXXNoexceptExprClass:
15460     return NoDiag();
15461   case Expr::CallExprClass:
15462   case Expr::CXXOperatorCallExprClass: {
15463     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15464     // constant expressions, but they can never be ICEs because an ICE cannot
15465     // contain an operand of (pointer to) function type.
15466     const CallExpr *CE = cast<CallExpr>(E);
15467     if (CE->getBuiltinCallee())
15468       return CheckEvalInICE(E, Ctx);
15469     return ICEDiag(IK_NotICE, E->getBeginLoc());
15470   }
15471   case Expr::CXXRewrittenBinaryOperatorClass:
15472     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15473                     Ctx);
15474   case Expr::DeclRefExprClass: {
15475     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15476     if (isa<EnumConstantDecl>(D))
15477       return NoDiag();
15478 
15479     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15480     // integer variables in constant expressions:
15481     //
15482     // C++ 7.1.5.1p2
15483     //   A variable of non-volatile const-qualified integral or enumeration
15484     //   type initialized by an ICE can be used in ICEs.
15485     //
15486     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15487     // that mode, use of reference variables should not be allowed.
15488     const VarDecl *VD = dyn_cast<VarDecl>(D);
15489     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15490         !VD->getType()->isReferenceType())
15491       return NoDiag();
15492 
15493     return ICEDiag(IK_NotICE, E->getBeginLoc());
15494   }
15495   case Expr::UnaryOperatorClass: {
15496     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15497     switch (Exp->getOpcode()) {
15498     case UO_PostInc:
15499     case UO_PostDec:
15500     case UO_PreInc:
15501     case UO_PreDec:
15502     case UO_AddrOf:
15503     case UO_Deref:
15504     case UO_Coawait:
15505       // C99 6.6/3 allows increment and decrement within unevaluated
15506       // subexpressions of constant expressions, but they can never be ICEs
15507       // because an ICE cannot contain an lvalue operand.
15508       return ICEDiag(IK_NotICE, E->getBeginLoc());
15509     case UO_Extension:
15510     case UO_LNot:
15511     case UO_Plus:
15512     case UO_Minus:
15513     case UO_Not:
15514     case UO_Real:
15515     case UO_Imag:
15516       return CheckICE(Exp->getSubExpr(), Ctx);
15517     }
15518     llvm_unreachable("invalid unary operator class");
15519   }
15520   case Expr::OffsetOfExprClass: {
15521     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15522     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15523     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15524     // compliance: we should warn earlier for offsetof expressions with
15525     // array subscripts that aren't ICEs, and if the array subscripts
15526     // are ICEs, the value of the offsetof must be an integer constant.
15527     return CheckEvalInICE(E, Ctx);
15528   }
15529   case Expr::UnaryExprOrTypeTraitExprClass: {
15530     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15531     if ((Exp->getKind() ==  UETT_SizeOf) &&
15532         Exp->getTypeOfArgument()->isVariableArrayType())
15533       return ICEDiag(IK_NotICE, E->getBeginLoc());
15534     return NoDiag();
15535   }
15536   case Expr::BinaryOperatorClass: {
15537     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15538     switch (Exp->getOpcode()) {
15539     case BO_PtrMemD:
15540     case BO_PtrMemI:
15541     case BO_Assign:
15542     case BO_MulAssign:
15543     case BO_DivAssign:
15544     case BO_RemAssign:
15545     case BO_AddAssign:
15546     case BO_SubAssign:
15547     case BO_ShlAssign:
15548     case BO_ShrAssign:
15549     case BO_AndAssign:
15550     case BO_XorAssign:
15551     case BO_OrAssign:
15552       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15553       // constant expressions, but they can never be ICEs because an ICE cannot
15554       // contain an lvalue operand.
15555       return ICEDiag(IK_NotICE, E->getBeginLoc());
15556 
15557     case BO_Mul:
15558     case BO_Div:
15559     case BO_Rem:
15560     case BO_Add:
15561     case BO_Sub:
15562     case BO_Shl:
15563     case BO_Shr:
15564     case BO_LT:
15565     case BO_GT:
15566     case BO_LE:
15567     case BO_GE:
15568     case BO_EQ:
15569     case BO_NE:
15570     case BO_And:
15571     case BO_Xor:
15572     case BO_Or:
15573     case BO_Comma:
15574     case BO_Cmp: {
15575       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15576       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15577       if (Exp->getOpcode() == BO_Div ||
15578           Exp->getOpcode() == BO_Rem) {
15579         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15580         // we don't evaluate one.
15581         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15582           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15583           if (REval == 0)
15584             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15585           if (REval.isSigned() && REval.isAllOnes()) {
15586             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15587             if (LEval.isMinSignedValue())
15588               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15589           }
15590         }
15591       }
15592       if (Exp->getOpcode() == BO_Comma) {
15593         if (Ctx.getLangOpts().C99) {
15594           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15595           // if it isn't evaluated.
15596           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15597             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15598         } else {
15599           // In both C89 and C++, commas in ICEs are illegal.
15600           return ICEDiag(IK_NotICE, E->getBeginLoc());
15601         }
15602       }
15603       return Worst(LHSResult, RHSResult);
15604     }
15605     case BO_LAnd:
15606     case BO_LOr: {
15607       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15608       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15609       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15610         // Rare case where the RHS has a comma "side-effect"; we need
15611         // to actually check the condition to see whether the side
15612         // with the comma is evaluated.
15613         if ((Exp->getOpcode() == BO_LAnd) !=
15614             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15615           return RHSResult;
15616         return NoDiag();
15617       }
15618 
15619       return Worst(LHSResult, RHSResult);
15620     }
15621     }
15622     llvm_unreachable("invalid binary operator kind");
15623   }
15624   case Expr::ImplicitCastExprClass:
15625   case Expr::CStyleCastExprClass:
15626   case Expr::CXXFunctionalCastExprClass:
15627   case Expr::CXXStaticCastExprClass:
15628   case Expr::CXXReinterpretCastExprClass:
15629   case Expr::CXXConstCastExprClass:
15630   case Expr::ObjCBridgedCastExprClass: {
15631     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15632     if (isa<ExplicitCastExpr>(E)) {
15633       if (const FloatingLiteral *FL
15634             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15635         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15636         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15637         APSInt IgnoredVal(DestWidth, !DestSigned);
15638         bool Ignored;
15639         // If the value does not fit in the destination type, the behavior is
15640         // undefined, so we are not required to treat it as a constant
15641         // expression.
15642         if (FL->getValue().convertToInteger(IgnoredVal,
15643                                             llvm::APFloat::rmTowardZero,
15644                                             &Ignored) & APFloat::opInvalidOp)
15645           return ICEDiag(IK_NotICE, E->getBeginLoc());
15646         return NoDiag();
15647       }
15648     }
15649     switch (cast<CastExpr>(E)->getCastKind()) {
15650     case CK_LValueToRValue:
15651     case CK_AtomicToNonAtomic:
15652     case CK_NonAtomicToAtomic:
15653     case CK_NoOp:
15654     case CK_IntegralToBoolean:
15655     case CK_IntegralCast:
15656       return CheckICE(SubExpr, Ctx);
15657     default:
15658       return ICEDiag(IK_NotICE, E->getBeginLoc());
15659     }
15660   }
15661   case Expr::BinaryConditionalOperatorClass: {
15662     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15663     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15664     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15665     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15666     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15667     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15668     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15669         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15670     return FalseResult;
15671   }
15672   case Expr::ConditionalOperatorClass: {
15673     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15674     // If the condition (ignoring parens) is a __builtin_constant_p call,
15675     // then only the true side is actually considered in an integer constant
15676     // expression, and it is fully evaluated.  This is an important GNU
15677     // extension.  See GCC PR38377 for discussion.
15678     if (const CallExpr *CallCE
15679         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15680       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15681         return CheckEvalInICE(E, Ctx);
15682     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15683     if (CondResult.Kind == IK_NotICE)
15684       return CondResult;
15685 
15686     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15687     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15688 
15689     if (TrueResult.Kind == IK_NotICE)
15690       return TrueResult;
15691     if (FalseResult.Kind == IK_NotICE)
15692       return FalseResult;
15693     if (CondResult.Kind == IK_ICEIfUnevaluated)
15694       return CondResult;
15695     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15696       return NoDiag();
15697     // Rare case where the diagnostics depend on which side is evaluated
15698     // Note that if we get here, CondResult is 0, and at least one of
15699     // TrueResult and FalseResult is non-zero.
15700     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15701       return FalseResult;
15702     return TrueResult;
15703   }
15704   case Expr::CXXDefaultArgExprClass:
15705     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15706   case Expr::CXXDefaultInitExprClass:
15707     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15708   case Expr::ChooseExprClass: {
15709     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15710   }
15711   case Expr::BuiltinBitCastExprClass: {
15712     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15713       return ICEDiag(IK_NotICE, E->getBeginLoc());
15714     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15715   }
15716   }
15717 
15718   llvm_unreachable("Invalid StmtClass!");
15719 }
15720 
15721 /// Evaluate an expression as a C++11 integral constant expression.
15722 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15723                                                     const Expr *E,
15724                                                     llvm::APSInt *Value,
15725                                                     SourceLocation *Loc) {
15726   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15727     if (Loc) *Loc = E->getExprLoc();
15728     return false;
15729   }
15730 
15731   APValue Result;
15732   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15733     return false;
15734 
15735   if (!Result.isInt()) {
15736     if (Loc) *Loc = E->getExprLoc();
15737     return false;
15738   }
15739 
15740   if (Value) *Value = Result.getInt();
15741   return true;
15742 }
15743 
15744 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15745                                  SourceLocation *Loc) const {
15746   assert(!isValueDependent() &&
15747          "Expression evaluator can't be called on a dependent expression.");
15748 
15749   if (Ctx.getLangOpts().CPlusPlus11)
15750     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15751 
15752   ICEDiag D = CheckICE(this, Ctx);
15753   if (D.Kind != IK_ICE) {
15754     if (Loc) *Loc = D.Loc;
15755     return false;
15756   }
15757   return true;
15758 }
15759 
15760 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15761                                                     SourceLocation *Loc,
15762                                                     bool isEvaluated) const {
15763   if (isValueDependent()) {
15764     // Expression evaluator can't succeed on a dependent expression.
15765     return None;
15766   }
15767 
15768   APSInt Value;
15769 
15770   if (Ctx.getLangOpts().CPlusPlus11) {
15771     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15772       return Value;
15773     return None;
15774   }
15775 
15776   if (!isIntegerConstantExpr(Ctx, Loc))
15777     return None;
15778 
15779   // The only possible side-effects here are due to UB discovered in the
15780   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15781   // required to treat the expression as an ICE, so we produce the folded
15782   // value.
15783   EvalResult ExprResult;
15784   Expr::EvalStatus Status;
15785   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15786   Info.InConstantContext = true;
15787 
15788   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15789     llvm_unreachable("ICE cannot be evaluated!");
15790 
15791   return ExprResult.Val.getInt();
15792 }
15793 
15794 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15795   assert(!isValueDependent() &&
15796          "Expression evaluator can't be called on a dependent expression.");
15797 
15798   return CheckICE(this, Ctx).Kind == IK_ICE;
15799 }
15800 
15801 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15802                                SourceLocation *Loc) const {
15803   assert(!isValueDependent() &&
15804          "Expression evaluator can't be called on a dependent expression.");
15805 
15806   // We support this checking in C++98 mode in order to diagnose compatibility
15807   // issues.
15808   assert(Ctx.getLangOpts().CPlusPlus);
15809 
15810   // Build evaluation settings.
15811   Expr::EvalStatus Status;
15812   SmallVector<PartialDiagnosticAt, 8> Diags;
15813   Status.Diag = &Diags;
15814   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15815 
15816   APValue Scratch;
15817   bool IsConstExpr =
15818       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15819       // FIXME: We don't produce a diagnostic for this, but the callers that
15820       // call us on arbitrary full-expressions should generally not care.
15821       Info.discardCleanups() && !Status.HasSideEffects;
15822 
15823   if (!Diags.empty()) {
15824     IsConstExpr = false;
15825     if (Loc) *Loc = Diags[0].first;
15826   } else if (!IsConstExpr) {
15827     // FIXME: This shouldn't happen.
15828     if (Loc) *Loc = getExprLoc();
15829   }
15830 
15831   return IsConstExpr;
15832 }
15833 
15834 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15835                                     const FunctionDecl *Callee,
15836                                     ArrayRef<const Expr*> Args,
15837                                     const Expr *This) const {
15838   assert(!isValueDependent() &&
15839          "Expression evaluator can't be called on a dependent expression.");
15840 
15841   Expr::EvalStatus Status;
15842   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15843   Info.InConstantContext = true;
15844 
15845   LValue ThisVal;
15846   const LValue *ThisPtr = nullptr;
15847   if (This) {
15848 #ifndef NDEBUG
15849     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15850     assert(MD && "Don't provide `this` for non-methods.");
15851     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15852 #endif
15853     if (!This->isValueDependent() &&
15854         EvaluateObjectArgument(Info, This, ThisVal) &&
15855         !Info.EvalStatus.HasSideEffects)
15856       ThisPtr = &ThisVal;
15857 
15858     // Ignore any side-effects from a failed evaluation. This is safe because
15859     // they can't interfere with any other argument evaluation.
15860     Info.EvalStatus.HasSideEffects = false;
15861   }
15862 
15863   CallRef Call = Info.CurrentCall->createCall(Callee);
15864   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15865        I != E; ++I) {
15866     unsigned Idx = I - Args.begin();
15867     if (Idx >= Callee->getNumParams())
15868       break;
15869     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15870     if ((*I)->isValueDependent() ||
15871         !EvaluateCallArg(PVD, *I, Call, Info) ||
15872         Info.EvalStatus.HasSideEffects) {
15873       // If evaluation fails, throw away the argument entirely.
15874       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15875         *Slot = APValue();
15876     }
15877 
15878     // Ignore any side-effects from a failed evaluation. This is safe because
15879     // they can't interfere with any other argument evaluation.
15880     Info.EvalStatus.HasSideEffects = false;
15881   }
15882 
15883   // Parameter cleanups happen in the caller and are not part of this
15884   // evaluation.
15885   Info.discardCleanups();
15886   Info.EvalStatus.HasSideEffects = false;
15887 
15888   // Build fake call to Callee.
15889   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15890   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15891   FullExpressionRAII Scope(Info);
15892   return Evaluate(Value, Info, this) && Scope.destroy() &&
15893          !Info.EvalStatus.HasSideEffects;
15894 }
15895 
15896 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15897                                    SmallVectorImpl<
15898                                      PartialDiagnosticAt> &Diags) {
15899   // FIXME: It would be useful to check constexpr function templates, but at the
15900   // moment the constant expression evaluator cannot cope with the non-rigorous
15901   // ASTs which we build for dependent expressions.
15902   if (FD->isDependentContext())
15903     return true;
15904 
15905   Expr::EvalStatus Status;
15906   Status.Diag = &Diags;
15907 
15908   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15909   Info.InConstantContext = true;
15910   Info.CheckingPotentialConstantExpression = true;
15911 
15912   // The constexpr VM attempts to compile all methods to bytecode here.
15913   if (Info.EnableNewConstInterp) {
15914     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15915     return Diags.empty();
15916   }
15917 
15918   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15919   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15920 
15921   // Fabricate an arbitrary expression on the stack and pretend that it
15922   // is a temporary being used as the 'this' pointer.
15923   LValue This;
15924   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15925   This.set({&VIE, Info.CurrentCall->Index});
15926 
15927   ArrayRef<const Expr*> Args;
15928 
15929   APValue Scratch;
15930   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15931     // Evaluate the call as a constant initializer, to allow the construction
15932     // of objects of non-literal types.
15933     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15934     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15935   } else {
15936     SourceLocation Loc = FD->getLocation();
15937     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15938                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15939   }
15940 
15941   return Diags.empty();
15942 }
15943 
15944 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15945                                               const FunctionDecl *FD,
15946                                               SmallVectorImpl<
15947                                                 PartialDiagnosticAt> &Diags) {
15948   assert(!E->isValueDependent() &&
15949          "Expression evaluator can't be called on a dependent expression.");
15950 
15951   Expr::EvalStatus Status;
15952   Status.Diag = &Diags;
15953 
15954   EvalInfo Info(FD->getASTContext(), Status,
15955                 EvalInfo::EM_ConstantExpressionUnevaluated);
15956   Info.InConstantContext = true;
15957   Info.CheckingPotentialConstantExpression = true;
15958 
15959   // Fabricate a call stack frame to give the arguments a plausible cover story.
15960   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15961 
15962   APValue ResultScratch;
15963   Evaluate(ResultScratch, Info, E);
15964   return Diags.empty();
15965 }
15966 
15967 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15968                                  unsigned Type) const {
15969   if (!getType()->isPointerType())
15970     return false;
15971 
15972   Expr::EvalStatus Status;
15973   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15974   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15975 }
15976 
15977 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15978                                   EvalInfo &Info) {
15979   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15980     return false;
15981 
15982   LValue String;
15983 
15984   if (!EvaluatePointer(E, String, Info))
15985     return false;
15986 
15987   QualType CharTy = E->getType()->getPointeeType();
15988 
15989   // Fast path: if it's a string literal, search the string value.
15990   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15991           String.getLValueBase().dyn_cast<const Expr *>())) {
15992     StringRef Str = S->getBytes();
15993     int64_t Off = String.Offset.getQuantity();
15994     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15995         S->getCharByteWidth() == 1 &&
15996         // FIXME: Add fast-path for wchar_t too.
15997         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15998       Str = Str.substr(Off);
15999 
16000       StringRef::size_type Pos = Str.find(0);
16001       if (Pos != StringRef::npos)
16002         Str = Str.substr(0, Pos);
16003 
16004       Result = Str.size();
16005       return true;
16006     }
16007 
16008     // Fall through to slow path.
16009   }
16010 
16011   // Slow path: scan the bytes of the string looking for the terminating 0.
16012   for (uint64_t Strlen = 0; /**/; ++Strlen) {
16013     APValue Char;
16014     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16015         !Char.isInt())
16016       return false;
16017     if (!Char.getInt()) {
16018       Result = Strlen;
16019       return true;
16020     }
16021     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16022       return false;
16023   }
16024 }
16025 
16026 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16027   Expr::EvalStatus Status;
16028   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16029   return EvaluateBuiltinStrLen(this, Result, Info);
16030 }
16031