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   if (!VD->evaluateValue()) {
3328     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3329     NoteLValueLocation(Info, Base);
3330     return false;
3331   }
3332 
3333   // Check that the variable is actually usable in constant expressions. For a
3334   // const integral variable or a reference, we might have a non-constant
3335   // initializer that we can nonetheless evaluate the initializer for. Such
3336   // variables are not usable in constant expressions. In C++98, the
3337   // initializer also syntactically needs to be an ICE.
3338   //
3339   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3340   // expressions here; doing so would regress diagnostics for things like
3341   // reading from a volatile constexpr variable.
3342   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3343        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3344       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3345        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3346     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3347     NoteLValueLocation(Info, Base);
3348   }
3349 
3350   // Never use the initializer of a weak variable, not even for constant
3351   // folding. We can't be sure that this is the definition that will be used.
3352   if (VD->isWeak()) {
3353     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3354     NoteLValueLocation(Info, Base);
3355     return false;
3356   }
3357 
3358   Result = VD->getEvaluatedValue();
3359   return true;
3360 }
3361 
3362 /// Get the base index of the given base class within an APValue representing
3363 /// the given derived class.
3364 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3365                              const CXXRecordDecl *Base) {
3366   Base = Base->getCanonicalDecl();
3367   unsigned Index = 0;
3368   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3369          E = Derived->bases_end(); I != E; ++I, ++Index) {
3370     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3371       return Index;
3372   }
3373 
3374   llvm_unreachable("base class missing from derived class's bases list");
3375 }
3376 
3377 /// Extract the value of a character from a string literal.
3378 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3379                                             uint64_t Index) {
3380   assert(!isa<SourceLocExpr>(Lit) &&
3381          "SourceLocExpr should have already been converted to a StringLiteral");
3382 
3383   // FIXME: Support MakeStringConstant
3384   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3385     std::string Str;
3386     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3387     assert(Index <= Str.size() && "Index too large");
3388     return APSInt::getUnsigned(Str.c_str()[Index]);
3389   }
3390 
3391   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3392     Lit = PE->getFunctionName();
3393   const StringLiteral *S = cast<StringLiteral>(Lit);
3394   const ConstantArrayType *CAT =
3395       Info.Ctx.getAsConstantArrayType(S->getType());
3396   assert(CAT && "string literal isn't an array");
3397   QualType CharType = CAT->getElementType();
3398   assert(CharType->isIntegerType() && "unexpected character type");
3399 
3400   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3401                CharType->isUnsignedIntegerType());
3402   if (Index < S->getLength())
3403     Value = S->getCodeUnit(Index);
3404   return Value;
3405 }
3406 
3407 // Expand a string literal into an array of characters.
3408 //
3409 // FIXME: This is inefficient; we should probably introduce something similar
3410 // to the LLVM ConstantDataArray to make this cheaper.
3411 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3412                                 APValue &Result,
3413                                 QualType AllocType = QualType()) {
3414   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3415       AllocType.isNull() ? S->getType() : AllocType);
3416   assert(CAT && "string literal isn't an array");
3417   QualType CharType = CAT->getElementType();
3418   assert(CharType->isIntegerType() && "unexpected character type");
3419 
3420   unsigned Elts = CAT->getSize().getZExtValue();
3421   Result = APValue(APValue::UninitArray(),
3422                    std::min(S->getLength(), Elts), Elts);
3423   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3424                CharType->isUnsignedIntegerType());
3425   if (Result.hasArrayFiller())
3426     Result.getArrayFiller() = APValue(Value);
3427   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3428     Value = S->getCodeUnit(I);
3429     Result.getArrayInitializedElt(I) = APValue(Value);
3430   }
3431 }
3432 
3433 // Expand an array so that it has more than Index filled elements.
3434 static void expandArray(APValue &Array, unsigned Index) {
3435   unsigned Size = Array.getArraySize();
3436   assert(Index < Size);
3437 
3438   // Always at least double the number of elements for which we store a value.
3439   unsigned OldElts = Array.getArrayInitializedElts();
3440   unsigned NewElts = std::max(Index+1, OldElts * 2);
3441   NewElts = std::min(Size, std::max(NewElts, 8u));
3442 
3443   // Copy the data across.
3444   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3445   for (unsigned I = 0; I != OldElts; ++I)
3446     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3447   for (unsigned I = OldElts; I != NewElts; ++I)
3448     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3449   if (NewValue.hasArrayFiller())
3450     NewValue.getArrayFiller() = Array.getArrayFiller();
3451   Array.swap(NewValue);
3452 }
3453 
3454 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3455 /// conversion. If it's of class type, we may assume that the copy operation
3456 /// is trivial. Note that this is never true for a union type with fields
3457 /// (because the copy always "reads" the active member) and always true for
3458 /// a non-class type.
3459 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3460 static bool isReadByLvalueToRvalueConversion(QualType T) {
3461   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3462   return !RD || isReadByLvalueToRvalueConversion(RD);
3463 }
3464 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3465   // FIXME: A trivial copy of a union copies the object representation, even if
3466   // the union is empty.
3467   if (RD->isUnion())
3468     return !RD->field_empty();
3469   if (RD->isEmpty())
3470     return false;
3471 
3472   for (auto *Field : RD->fields())
3473     if (!Field->isUnnamedBitfield() &&
3474         isReadByLvalueToRvalueConversion(Field->getType()))
3475       return true;
3476 
3477   for (auto &BaseSpec : RD->bases())
3478     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3479       return true;
3480 
3481   return false;
3482 }
3483 
3484 /// Diagnose an attempt to read from any unreadable field within the specified
3485 /// type, which might be a class type.
3486 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3487                                   QualType T) {
3488   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3489   if (!RD)
3490     return false;
3491 
3492   if (!RD->hasMutableFields())
3493     return false;
3494 
3495   for (auto *Field : RD->fields()) {
3496     // If we're actually going to read this field in some way, then it can't
3497     // be mutable. If we're in a union, then assigning to a mutable field
3498     // (even an empty one) can change the active member, so that's not OK.
3499     // FIXME: Add core issue number for the union case.
3500     if (Field->isMutable() &&
3501         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3502       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3503       Info.Note(Field->getLocation(), diag::note_declared_at);
3504       return true;
3505     }
3506 
3507     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3508       return true;
3509   }
3510 
3511   for (auto &BaseSpec : RD->bases())
3512     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3513       return true;
3514 
3515   // All mutable fields were empty, and thus not actually read.
3516   return false;
3517 }
3518 
3519 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3520                                         APValue::LValueBase Base,
3521                                         bool MutableSubobject = false) {
3522   // A temporary or transient heap allocation we created.
3523   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3524     return true;
3525 
3526   switch (Info.IsEvaluatingDecl) {
3527   case EvalInfo::EvaluatingDeclKind::None:
3528     return false;
3529 
3530   case EvalInfo::EvaluatingDeclKind::Ctor:
3531     // The variable whose initializer we're evaluating.
3532     if (Info.EvaluatingDecl == Base)
3533       return true;
3534 
3535     // A temporary lifetime-extended by the variable whose initializer we're
3536     // evaluating.
3537     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3538       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3539         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3540     return false;
3541 
3542   case EvalInfo::EvaluatingDeclKind::Dtor:
3543     // C++2a [expr.const]p6:
3544     //   [during constant destruction] the lifetime of a and its non-mutable
3545     //   subobjects (but not its mutable subobjects) [are] considered to start
3546     //   within e.
3547     if (MutableSubobject || Base != Info.EvaluatingDecl)
3548       return false;
3549     // FIXME: We can meaningfully extend this to cover non-const objects, but
3550     // we will need special handling: we should be able to access only
3551     // subobjects of such objects that are themselves declared const.
3552     QualType T = getType(Base);
3553     return T.isConstQualified() || T->isReferenceType();
3554   }
3555 
3556   llvm_unreachable("unknown evaluating decl kind");
3557 }
3558 
3559 namespace {
3560 /// A handle to a complete object (an object that is not a subobject of
3561 /// another object).
3562 struct CompleteObject {
3563   /// The identity of the object.
3564   APValue::LValueBase Base;
3565   /// The value of the complete object.
3566   APValue *Value;
3567   /// The type of the complete object.
3568   QualType Type;
3569 
3570   CompleteObject() : Value(nullptr) {}
3571   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3572       : Base(Base), Value(Value), Type(Type) {}
3573 
3574   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3575     // If this isn't a "real" access (eg, if it's just accessing the type
3576     // info), allow it. We assume the type doesn't change dynamically for
3577     // subobjects of constexpr objects (even though we'd hit UB here if it
3578     // did). FIXME: Is this right?
3579     if (!isAnyAccess(AK))
3580       return true;
3581 
3582     // In C++14 onwards, it is permitted to read a mutable member whose
3583     // lifetime began within the evaluation.
3584     // FIXME: Should we also allow this in C++11?
3585     if (!Info.getLangOpts().CPlusPlus14)
3586       return false;
3587     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3588   }
3589 
3590   explicit operator bool() const { return !Type.isNull(); }
3591 };
3592 } // end anonymous namespace
3593 
3594 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3595                                  bool IsMutable = false) {
3596   // C++ [basic.type.qualifier]p1:
3597   // - A const object is an object of type const T or a non-mutable subobject
3598   //   of a const object.
3599   if (ObjType.isConstQualified() && !IsMutable)
3600     SubobjType.addConst();
3601   // - A volatile object is an object of type const T or a subobject of a
3602   //   volatile object.
3603   if (ObjType.isVolatileQualified())
3604     SubobjType.addVolatile();
3605   return SubobjType;
3606 }
3607 
3608 /// Find the designated sub-object of an rvalue.
3609 template<typename SubobjectHandler>
3610 typename SubobjectHandler::result_type
3611 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3612               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3613   if (Sub.Invalid)
3614     // A diagnostic will have already been produced.
3615     return handler.failed();
3616   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3617     if (Info.getLangOpts().CPlusPlus11)
3618       Info.FFDiag(E, Sub.isOnePastTheEnd()
3619                          ? diag::note_constexpr_access_past_end
3620                          : diag::note_constexpr_access_unsized_array)
3621           << handler.AccessKind;
3622     else
3623       Info.FFDiag(E);
3624     return handler.failed();
3625   }
3626 
3627   APValue *O = Obj.Value;
3628   QualType ObjType = Obj.Type;
3629   const FieldDecl *LastField = nullptr;
3630   const FieldDecl *VolatileField = nullptr;
3631 
3632   // Walk the designator's path to find the subobject.
3633   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3634     // Reading an indeterminate value is undefined, but assigning over one is OK.
3635     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3636         (O->isIndeterminate() &&
3637          !isValidIndeterminateAccess(handler.AccessKind))) {
3638       if (!Info.checkingPotentialConstantExpression())
3639         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3640             << handler.AccessKind << O->isIndeterminate();
3641       return handler.failed();
3642     }
3643 
3644     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3645     //    const and volatile semantics are not applied on an object under
3646     //    {con,de}struction.
3647     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3648         ObjType->isRecordType() &&
3649         Info.isEvaluatingCtorDtor(
3650             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3651                                          Sub.Entries.begin() + I)) !=
3652                           ConstructionPhase::None) {
3653       ObjType = Info.Ctx.getCanonicalType(ObjType);
3654       ObjType.removeLocalConst();
3655       ObjType.removeLocalVolatile();
3656     }
3657 
3658     // If this is our last pass, check that the final object type is OK.
3659     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3660       // Accesses to volatile objects are prohibited.
3661       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3662         if (Info.getLangOpts().CPlusPlus) {
3663           int DiagKind;
3664           SourceLocation Loc;
3665           const NamedDecl *Decl = nullptr;
3666           if (VolatileField) {
3667             DiagKind = 2;
3668             Loc = VolatileField->getLocation();
3669             Decl = VolatileField;
3670           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3671             DiagKind = 1;
3672             Loc = VD->getLocation();
3673             Decl = VD;
3674           } else {
3675             DiagKind = 0;
3676             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3677               Loc = E->getExprLoc();
3678           }
3679           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3680               << handler.AccessKind << DiagKind << Decl;
3681           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3682         } else {
3683           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3684         }
3685         return handler.failed();
3686       }
3687 
3688       // If we are reading an object of class type, there may still be more
3689       // things we need to check: if there are any mutable subobjects, we
3690       // cannot perform this read. (This only happens when performing a trivial
3691       // copy or assignment.)
3692       if (ObjType->isRecordType() &&
3693           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3694           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3695         return handler.failed();
3696     }
3697 
3698     if (I == N) {
3699       if (!handler.found(*O, ObjType))
3700         return false;
3701 
3702       // If we modified a bit-field, truncate it to the right width.
3703       if (isModification(handler.AccessKind) &&
3704           LastField && LastField->isBitField() &&
3705           !truncateBitfieldValue(Info, E, *O, LastField))
3706         return false;
3707 
3708       return true;
3709     }
3710 
3711     LastField = nullptr;
3712     if (ObjType->isArrayType()) {
3713       // Next subobject is an array element.
3714       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3715       assert(CAT && "vla in literal type?");
3716       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3717       if (CAT->getSize().ule(Index)) {
3718         // Note, it should not be possible to form a pointer with a valid
3719         // designator which points more than one past the end of the array.
3720         if (Info.getLangOpts().CPlusPlus11)
3721           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3722             << handler.AccessKind;
3723         else
3724           Info.FFDiag(E);
3725         return handler.failed();
3726       }
3727 
3728       ObjType = CAT->getElementType();
3729 
3730       if (O->getArrayInitializedElts() > Index)
3731         O = &O->getArrayInitializedElt(Index);
3732       else if (!isRead(handler.AccessKind)) {
3733         expandArray(*O, Index);
3734         O = &O->getArrayInitializedElt(Index);
3735       } else
3736         O = &O->getArrayFiller();
3737     } else if (ObjType->isAnyComplexType()) {
3738       // Next subobject is a complex number.
3739       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3740       if (Index > 1) {
3741         if (Info.getLangOpts().CPlusPlus11)
3742           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3743             << handler.AccessKind;
3744         else
3745           Info.FFDiag(E);
3746         return handler.failed();
3747       }
3748 
3749       ObjType = getSubobjectType(
3750           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3751 
3752       assert(I == N - 1 && "extracting subobject of scalar?");
3753       if (O->isComplexInt()) {
3754         return handler.found(Index ? O->getComplexIntImag()
3755                                    : O->getComplexIntReal(), ObjType);
3756       } else {
3757         assert(O->isComplexFloat());
3758         return handler.found(Index ? O->getComplexFloatImag()
3759                                    : O->getComplexFloatReal(), ObjType);
3760       }
3761     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3762       if (Field->isMutable() &&
3763           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3764         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3765           << handler.AccessKind << Field;
3766         Info.Note(Field->getLocation(), diag::note_declared_at);
3767         return handler.failed();
3768       }
3769 
3770       // Next subobject is a class, struct or union field.
3771       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3772       if (RD->isUnion()) {
3773         const FieldDecl *UnionField = O->getUnionField();
3774         if (!UnionField ||
3775             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3776           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3777             // Placement new onto an inactive union member makes it active.
3778             O->setUnion(Field, APValue());
3779           } else {
3780             // FIXME: If O->getUnionValue() is absent, report that there's no
3781             // active union member rather than reporting the prior active union
3782             // member. We'll need to fix nullptr_t to not use APValue() as its
3783             // representation first.
3784             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3785                 << handler.AccessKind << Field << !UnionField << UnionField;
3786             return handler.failed();
3787           }
3788         }
3789         O = &O->getUnionValue();
3790       } else
3791         O = &O->getStructField(Field->getFieldIndex());
3792 
3793       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3794       LastField = Field;
3795       if (Field->getType().isVolatileQualified())
3796         VolatileField = Field;
3797     } else {
3798       // Next subobject is a base class.
3799       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3800       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3801       O = &O->getStructBase(getBaseIndex(Derived, Base));
3802 
3803       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3804     }
3805   }
3806 }
3807 
3808 namespace {
3809 struct ExtractSubobjectHandler {
3810   EvalInfo &Info;
3811   const Expr *E;
3812   APValue &Result;
3813   const AccessKinds AccessKind;
3814 
3815   typedef bool result_type;
3816   bool failed() { return false; }
3817   bool found(APValue &Subobj, QualType SubobjType) {
3818     Result = Subobj;
3819     if (AccessKind == AK_ReadObjectRepresentation)
3820       return true;
3821     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3822   }
3823   bool found(APSInt &Value, QualType SubobjType) {
3824     Result = APValue(Value);
3825     return true;
3826   }
3827   bool found(APFloat &Value, QualType SubobjType) {
3828     Result = APValue(Value);
3829     return true;
3830   }
3831 };
3832 } // end anonymous namespace
3833 
3834 /// Extract the designated sub-object of an rvalue.
3835 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3836                              const CompleteObject &Obj,
3837                              const SubobjectDesignator &Sub, APValue &Result,
3838                              AccessKinds AK = AK_Read) {
3839   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3840   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3841   return findSubobject(Info, E, Obj, Sub, Handler);
3842 }
3843 
3844 namespace {
3845 struct ModifySubobjectHandler {
3846   EvalInfo &Info;
3847   APValue &NewVal;
3848   const Expr *E;
3849 
3850   typedef bool result_type;
3851   static const AccessKinds AccessKind = AK_Assign;
3852 
3853   bool checkConst(QualType QT) {
3854     // Assigning to a const object has undefined behavior.
3855     if (QT.isConstQualified()) {
3856       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3857       return false;
3858     }
3859     return true;
3860   }
3861 
3862   bool failed() { return false; }
3863   bool found(APValue &Subobj, QualType SubobjType) {
3864     if (!checkConst(SubobjType))
3865       return false;
3866     // We've been given ownership of NewVal, so just swap it in.
3867     Subobj.swap(NewVal);
3868     return true;
3869   }
3870   bool found(APSInt &Value, QualType SubobjType) {
3871     if (!checkConst(SubobjType))
3872       return false;
3873     if (!NewVal.isInt()) {
3874       // Maybe trying to write a cast pointer value into a complex?
3875       Info.FFDiag(E);
3876       return false;
3877     }
3878     Value = NewVal.getInt();
3879     return true;
3880   }
3881   bool found(APFloat &Value, QualType SubobjType) {
3882     if (!checkConst(SubobjType))
3883       return false;
3884     Value = NewVal.getFloat();
3885     return true;
3886   }
3887 };
3888 } // end anonymous namespace
3889 
3890 const AccessKinds ModifySubobjectHandler::AccessKind;
3891 
3892 /// Update the designated sub-object of an rvalue to the given value.
3893 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3894                             const CompleteObject &Obj,
3895                             const SubobjectDesignator &Sub,
3896                             APValue &NewVal) {
3897   ModifySubobjectHandler Handler = { Info, NewVal, E };
3898   return findSubobject(Info, E, Obj, Sub, Handler);
3899 }
3900 
3901 /// Find the position where two subobject designators diverge, or equivalently
3902 /// the length of the common initial subsequence.
3903 static unsigned FindDesignatorMismatch(QualType ObjType,
3904                                        const SubobjectDesignator &A,
3905                                        const SubobjectDesignator &B,
3906                                        bool &WasArrayIndex) {
3907   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3908   for (/**/; I != N; ++I) {
3909     if (!ObjType.isNull() &&
3910         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3911       // Next subobject is an array element.
3912       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3913         WasArrayIndex = true;
3914         return I;
3915       }
3916       if (ObjType->isAnyComplexType())
3917         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3918       else
3919         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3920     } else {
3921       if (A.Entries[I].getAsBaseOrMember() !=
3922           B.Entries[I].getAsBaseOrMember()) {
3923         WasArrayIndex = false;
3924         return I;
3925       }
3926       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3927         // Next subobject is a field.
3928         ObjType = FD->getType();
3929       else
3930         // Next subobject is a base class.
3931         ObjType = QualType();
3932     }
3933   }
3934   WasArrayIndex = false;
3935   return I;
3936 }
3937 
3938 /// Determine whether the given subobject designators refer to elements of the
3939 /// same array object.
3940 static bool AreElementsOfSameArray(QualType ObjType,
3941                                    const SubobjectDesignator &A,
3942                                    const SubobjectDesignator &B) {
3943   if (A.Entries.size() != B.Entries.size())
3944     return false;
3945 
3946   bool IsArray = A.MostDerivedIsArrayElement;
3947   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3948     // A is a subobject of the array element.
3949     return false;
3950 
3951   // If A (and B) designates an array element, the last entry will be the array
3952   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3953   // of length 1' case, and the entire path must match.
3954   bool WasArrayIndex;
3955   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3956   return CommonLength >= A.Entries.size() - IsArray;
3957 }
3958 
3959 /// Find the complete object to which an LValue refers.
3960 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3961                                          AccessKinds AK, const LValue &LVal,
3962                                          QualType LValType) {
3963   if (LVal.InvalidBase) {
3964     Info.FFDiag(E);
3965     return CompleteObject();
3966   }
3967 
3968   if (!LVal.Base) {
3969     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3970     return CompleteObject();
3971   }
3972 
3973   CallStackFrame *Frame = nullptr;
3974   unsigned Depth = 0;
3975   if (LVal.getLValueCallIndex()) {
3976     std::tie(Frame, Depth) =
3977         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3978     if (!Frame) {
3979       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3980         << AK << LVal.Base.is<const ValueDecl*>();
3981       NoteLValueLocation(Info, LVal.Base);
3982       return CompleteObject();
3983     }
3984   }
3985 
3986   bool IsAccess = isAnyAccess(AK);
3987 
3988   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3989   // is not a constant expression (even if the object is non-volatile). We also
3990   // apply this rule to C++98, in order to conform to the expected 'volatile'
3991   // semantics.
3992   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3993     if (Info.getLangOpts().CPlusPlus)
3994       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3995         << AK << LValType;
3996     else
3997       Info.FFDiag(E);
3998     return CompleteObject();
3999   }
4000 
4001   // Compute value storage location and type of base object.
4002   APValue *BaseVal = nullptr;
4003   QualType BaseType = getType(LVal.Base);
4004 
4005   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4006       lifetimeStartedInEvaluation(Info, LVal.Base)) {
4007     // This is the object whose initializer we're evaluating, so its lifetime
4008     // started in the current evaluation.
4009     BaseVal = Info.EvaluatingDeclValue;
4010   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4011     // Allow reading from a GUID declaration.
4012     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4013       if (isModification(AK)) {
4014         // All the remaining cases do not permit modification of the object.
4015         Info.FFDiag(E, diag::note_constexpr_modify_global);
4016         return CompleteObject();
4017       }
4018       APValue &V = GD->getAsAPValue();
4019       if (V.isAbsent()) {
4020         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4021             << GD->getType();
4022         return CompleteObject();
4023       }
4024       return CompleteObject(LVal.Base, &V, GD->getType());
4025     }
4026 
4027     // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4028     if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4029       if (isModification(AK)) {
4030         Info.FFDiag(E, diag::note_constexpr_modify_global);
4031         return CompleteObject();
4032       }
4033       return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4034                             GCD->getType());
4035     }
4036 
4037     // Allow reading from template parameter objects.
4038     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4039       if (isModification(AK)) {
4040         Info.FFDiag(E, diag::note_constexpr_modify_global);
4041         return CompleteObject();
4042       }
4043       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4044                             TPO->getType());
4045     }
4046 
4047     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4048     // In C++11, constexpr, non-volatile variables initialized with constant
4049     // expressions are constant expressions too. Inside constexpr functions,
4050     // parameters are constant expressions even if they're non-const.
4051     // In C++1y, objects local to a constant expression (those with a Frame) are
4052     // both readable and writable inside constant expressions.
4053     // In C, such things can also be folded, although they are not ICEs.
4054     const VarDecl *VD = dyn_cast<VarDecl>(D);
4055     if (VD) {
4056       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4057         VD = VDef;
4058     }
4059     if (!VD || VD->isInvalidDecl()) {
4060       Info.FFDiag(E);
4061       return CompleteObject();
4062     }
4063 
4064     bool IsConstant = BaseType.isConstant(Info.Ctx);
4065 
4066     // Unless we're looking at a local variable or argument in a constexpr call,
4067     // the variable we're reading must be const.
4068     if (!Frame) {
4069       if (IsAccess && isa<ParmVarDecl>(VD)) {
4070         // Access of a parameter that's not associated with a frame isn't going
4071         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4072         // suitable diagnostic.
4073       } else if (Info.getLangOpts().CPlusPlus14 &&
4074                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4075         // OK, we can read and modify an object if we're in the process of
4076         // evaluating its initializer, because its lifetime began in this
4077         // evaluation.
4078       } else if (isModification(AK)) {
4079         // All the remaining cases do not permit modification of the object.
4080         Info.FFDiag(E, diag::note_constexpr_modify_global);
4081         return CompleteObject();
4082       } else if (VD->isConstexpr()) {
4083         // OK, we can read this variable.
4084       } else if (BaseType->isIntegralOrEnumerationType()) {
4085         if (!IsConstant) {
4086           if (!IsAccess)
4087             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4088           if (Info.getLangOpts().CPlusPlus) {
4089             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4090             Info.Note(VD->getLocation(), diag::note_declared_at);
4091           } else {
4092             Info.FFDiag(E);
4093           }
4094           return CompleteObject();
4095         }
4096       } else if (!IsAccess) {
4097         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4098       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4099                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4100         // This variable might end up being constexpr. Don't diagnose it yet.
4101       } else if (IsConstant) {
4102         // Keep evaluating to see what we can do. In particular, we support
4103         // folding of const floating-point types, in order to make static const
4104         // data members of such types (supported as an extension) more useful.
4105         if (Info.getLangOpts().CPlusPlus) {
4106           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4107                               ? diag::note_constexpr_ltor_non_constexpr
4108                               : diag::note_constexpr_ltor_non_integral, 1)
4109               << VD << BaseType;
4110           Info.Note(VD->getLocation(), diag::note_declared_at);
4111         } else {
4112           Info.CCEDiag(E);
4113         }
4114       } else {
4115         // Never allow reading a non-const value.
4116         if (Info.getLangOpts().CPlusPlus) {
4117           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4118                              ? diag::note_constexpr_ltor_non_constexpr
4119                              : diag::note_constexpr_ltor_non_integral, 1)
4120               << VD << BaseType;
4121           Info.Note(VD->getLocation(), diag::note_declared_at);
4122         } else {
4123           Info.FFDiag(E);
4124         }
4125         return CompleteObject();
4126       }
4127     }
4128 
4129     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4130       return CompleteObject();
4131   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4132     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4133     if (!Alloc) {
4134       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4135       return CompleteObject();
4136     }
4137     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4138                           LVal.Base.getDynamicAllocType());
4139   } else {
4140     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4141 
4142     if (!Frame) {
4143       if (const MaterializeTemporaryExpr *MTE =
4144               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4145         assert(MTE->getStorageDuration() == SD_Static &&
4146                "should have a frame for a non-global materialized temporary");
4147 
4148         // C++20 [expr.const]p4: [DR2126]
4149         //   An object or reference is usable in constant expressions if it is
4150         //   - a temporary object of non-volatile const-qualified literal type
4151         //     whose lifetime is extended to that of a variable that is usable
4152         //     in constant expressions
4153         //
4154         // C++20 [expr.const]p5:
4155         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4156         //   - a non-volatile glvalue that refers to an object that is usable
4157         //     in constant expressions, or
4158         //   - a non-volatile glvalue of literal type that refers to a
4159         //     non-volatile object whose lifetime began within the evaluation
4160         //     of E;
4161         //
4162         // C++11 misses the 'began within the evaluation of e' check and
4163         // instead allows all temporaries, including things like:
4164         //   int &&r = 1;
4165         //   int x = ++r;
4166         //   constexpr int k = r;
4167         // Therefore we use the C++14-onwards rules in C++11 too.
4168         //
4169         // Note that temporaries whose lifetimes began while evaluating a
4170         // variable's constructor are not usable while evaluating the
4171         // corresponding destructor, not even if they're of const-qualified
4172         // types.
4173         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4174             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4175           if (!IsAccess)
4176             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4177           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4178           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4179           return CompleteObject();
4180         }
4181 
4182         BaseVal = MTE->getOrCreateValue(false);
4183         assert(BaseVal && "got reference to unevaluated temporary");
4184       } else {
4185         if (!IsAccess)
4186           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4187         APValue Val;
4188         LVal.moveInto(Val);
4189         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4190             << AK
4191             << Val.getAsString(Info.Ctx,
4192                                Info.Ctx.getLValueReferenceType(LValType));
4193         NoteLValueLocation(Info, LVal.Base);
4194         return CompleteObject();
4195       }
4196     } else {
4197       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4198       assert(BaseVal && "missing value for temporary");
4199     }
4200   }
4201 
4202   // In C++14, we can't safely access any mutable state when we might be
4203   // evaluating after an unmodeled side effect. Parameters are modeled as state
4204   // in the caller, but aren't visible once the call returns, so they can be
4205   // modified in a speculatively-evaluated call.
4206   //
4207   // FIXME: Not all local state is mutable. Allow local constant subobjects
4208   // to be read here (but take care with 'mutable' fields).
4209   unsigned VisibleDepth = Depth;
4210   if (llvm::isa_and_nonnull<ParmVarDecl>(
4211           LVal.Base.dyn_cast<const ValueDecl *>()))
4212     ++VisibleDepth;
4213   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4214        Info.EvalStatus.HasSideEffects) ||
4215       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4216     return CompleteObject();
4217 
4218   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4219 }
4220 
4221 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4222 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4223 /// glvalue referred to by an entity of reference type.
4224 ///
4225 /// \param Info - Information about the ongoing evaluation.
4226 /// \param Conv - The expression for which we are performing the conversion.
4227 ///               Used for diagnostics.
4228 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4229 ///               case of a non-class type).
4230 /// \param LVal - The glvalue on which we are attempting to perform this action.
4231 /// \param RVal - The produced value will be placed here.
4232 /// \param WantObjectRepresentation - If true, we're looking for the object
4233 ///               representation rather than the value, and in particular,
4234 ///               there is no requirement that the result be fully initialized.
4235 static bool
4236 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4237                                const LValue &LVal, APValue &RVal,
4238                                bool WantObjectRepresentation = false) {
4239   if (LVal.Designator.Invalid)
4240     return false;
4241 
4242   // Check for special cases where there is no existing APValue to look at.
4243   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4244 
4245   AccessKinds AK =
4246       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4247 
4248   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4249     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4250       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4251       // initializer until now for such expressions. Such an expression can't be
4252       // an ICE in C, so this only matters for fold.
4253       if (Type.isVolatileQualified()) {
4254         Info.FFDiag(Conv);
4255         return false;
4256       }
4257 
4258       APValue Lit;
4259       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4260         return false;
4261 
4262       // According to GCC info page:
4263       //
4264       // 6.28 Compound Literals
4265       //
4266       // As an optimization, G++ sometimes gives array compound literals longer
4267       // lifetimes: when the array either appears outside a function or has a
4268       // const-qualified type. If foo and its initializer had elements of type
4269       // char *const rather than char *, or if foo were a global variable, the
4270       // array would have static storage duration. But it is probably safest
4271       // just to avoid the use of array compound literals in C++ code.
4272       //
4273       // Obey that rule by checking constness for converted array types.
4274 
4275       QualType CLETy = CLE->getType();
4276       if (CLETy->isArrayType() && !Type->isArrayType()) {
4277         if (!CLETy.isConstant(Info.Ctx)) {
4278           Info.FFDiag(Conv);
4279           Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4280           return false;
4281         }
4282       }
4283 
4284       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4285       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4286     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4287       // Special-case character extraction so we don't have to construct an
4288       // APValue for the whole string.
4289       assert(LVal.Designator.Entries.size() <= 1 &&
4290              "Can only read characters from string literals");
4291       if (LVal.Designator.Entries.empty()) {
4292         // Fail for now for LValue to RValue conversion of an array.
4293         // (This shouldn't show up in C/C++, but it could be triggered by a
4294         // weird EvaluateAsRValue call from a tool.)
4295         Info.FFDiag(Conv);
4296         return false;
4297       }
4298       if (LVal.Designator.isOnePastTheEnd()) {
4299         if (Info.getLangOpts().CPlusPlus11)
4300           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4301         else
4302           Info.FFDiag(Conv);
4303         return false;
4304       }
4305       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4306       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4307       return true;
4308     }
4309   }
4310 
4311   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4312   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4313 }
4314 
4315 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4316 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4317                              QualType LValType, APValue &Val) {
4318   if (LVal.Designator.Invalid)
4319     return false;
4320 
4321   if (!Info.getLangOpts().CPlusPlus14) {
4322     Info.FFDiag(E);
4323     return false;
4324   }
4325 
4326   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4327   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4328 }
4329 
4330 namespace {
4331 struct CompoundAssignSubobjectHandler {
4332   EvalInfo &Info;
4333   const CompoundAssignOperator *E;
4334   QualType PromotedLHSType;
4335   BinaryOperatorKind Opcode;
4336   const APValue &RHS;
4337 
4338   static const AccessKinds AccessKind = AK_Assign;
4339 
4340   typedef bool result_type;
4341 
4342   bool checkConst(QualType QT) {
4343     // Assigning to a const object has undefined behavior.
4344     if (QT.isConstQualified()) {
4345       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4346       return false;
4347     }
4348     return true;
4349   }
4350 
4351   bool failed() { return false; }
4352   bool found(APValue &Subobj, QualType SubobjType) {
4353     switch (Subobj.getKind()) {
4354     case APValue::Int:
4355       return found(Subobj.getInt(), SubobjType);
4356     case APValue::Float:
4357       return found(Subobj.getFloat(), SubobjType);
4358     case APValue::ComplexInt:
4359     case APValue::ComplexFloat:
4360       // FIXME: Implement complex compound assignment.
4361       Info.FFDiag(E);
4362       return false;
4363     case APValue::LValue:
4364       return foundPointer(Subobj, SubobjType);
4365     case APValue::Vector:
4366       return foundVector(Subobj, SubobjType);
4367     default:
4368       // FIXME: can this happen?
4369       Info.FFDiag(E);
4370       return false;
4371     }
4372   }
4373 
4374   bool foundVector(APValue &Value, QualType SubobjType) {
4375     if (!checkConst(SubobjType))
4376       return false;
4377 
4378     if (!SubobjType->isVectorType()) {
4379       Info.FFDiag(E);
4380       return false;
4381     }
4382     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4383   }
4384 
4385   bool found(APSInt &Value, QualType SubobjType) {
4386     if (!checkConst(SubobjType))
4387       return false;
4388 
4389     if (!SubobjType->isIntegerType()) {
4390       // We don't support compound assignment on integer-cast-to-pointer
4391       // values.
4392       Info.FFDiag(E);
4393       return false;
4394     }
4395 
4396     if (RHS.isInt()) {
4397       APSInt LHS =
4398           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4399       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4400         return false;
4401       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4402       return true;
4403     } else if (RHS.isFloat()) {
4404       const FPOptions FPO = E->getFPFeaturesInEffect(
4405                                     Info.Ctx.getLangOpts());
4406       APFloat FValue(0.0);
4407       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4408                                   PromotedLHSType, FValue) &&
4409              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4410              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4411                                   Value);
4412     }
4413 
4414     Info.FFDiag(E);
4415     return false;
4416   }
4417   bool found(APFloat &Value, QualType SubobjType) {
4418     return checkConst(SubobjType) &&
4419            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4420                                   Value) &&
4421            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4422            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4423   }
4424   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4425     if (!checkConst(SubobjType))
4426       return false;
4427 
4428     QualType PointeeType;
4429     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4430       PointeeType = PT->getPointeeType();
4431 
4432     if (PointeeType.isNull() || !RHS.isInt() ||
4433         (Opcode != BO_Add && Opcode != BO_Sub)) {
4434       Info.FFDiag(E);
4435       return false;
4436     }
4437 
4438     APSInt Offset = RHS.getInt();
4439     if (Opcode == BO_Sub)
4440       negateAsSigned(Offset);
4441 
4442     LValue LVal;
4443     LVal.setFrom(Info.Ctx, Subobj);
4444     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4445       return false;
4446     LVal.moveInto(Subobj);
4447     return true;
4448   }
4449 };
4450 } // end anonymous namespace
4451 
4452 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4453 
4454 /// Perform a compound assignment of LVal <op>= RVal.
4455 static bool handleCompoundAssignment(EvalInfo &Info,
4456                                      const CompoundAssignOperator *E,
4457                                      const LValue &LVal, QualType LValType,
4458                                      QualType PromotedLValType,
4459                                      BinaryOperatorKind Opcode,
4460                                      const APValue &RVal) {
4461   if (LVal.Designator.Invalid)
4462     return false;
4463 
4464   if (!Info.getLangOpts().CPlusPlus14) {
4465     Info.FFDiag(E);
4466     return false;
4467   }
4468 
4469   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4470   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4471                                              RVal };
4472   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4473 }
4474 
4475 namespace {
4476 struct IncDecSubobjectHandler {
4477   EvalInfo &Info;
4478   const UnaryOperator *E;
4479   AccessKinds AccessKind;
4480   APValue *Old;
4481 
4482   typedef bool result_type;
4483 
4484   bool checkConst(QualType QT) {
4485     // Assigning to a const object has undefined behavior.
4486     if (QT.isConstQualified()) {
4487       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4488       return false;
4489     }
4490     return true;
4491   }
4492 
4493   bool failed() { return false; }
4494   bool found(APValue &Subobj, QualType SubobjType) {
4495     // Stash the old value. Also clear Old, so we don't clobber it later
4496     // if we're post-incrementing a complex.
4497     if (Old) {
4498       *Old = Subobj;
4499       Old = nullptr;
4500     }
4501 
4502     switch (Subobj.getKind()) {
4503     case APValue::Int:
4504       return found(Subobj.getInt(), SubobjType);
4505     case APValue::Float:
4506       return found(Subobj.getFloat(), SubobjType);
4507     case APValue::ComplexInt:
4508       return found(Subobj.getComplexIntReal(),
4509                    SubobjType->castAs<ComplexType>()->getElementType()
4510                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4511     case APValue::ComplexFloat:
4512       return found(Subobj.getComplexFloatReal(),
4513                    SubobjType->castAs<ComplexType>()->getElementType()
4514                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4515     case APValue::LValue:
4516       return foundPointer(Subobj, SubobjType);
4517     default:
4518       // FIXME: can this happen?
4519       Info.FFDiag(E);
4520       return false;
4521     }
4522   }
4523   bool found(APSInt &Value, QualType SubobjType) {
4524     if (!checkConst(SubobjType))
4525       return false;
4526 
4527     if (!SubobjType->isIntegerType()) {
4528       // We don't support increment / decrement on integer-cast-to-pointer
4529       // values.
4530       Info.FFDiag(E);
4531       return false;
4532     }
4533 
4534     if (Old) *Old = APValue(Value);
4535 
4536     // bool arithmetic promotes to int, and the conversion back to bool
4537     // doesn't reduce mod 2^n, so special-case it.
4538     if (SubobjType->isBooleanType()) {
4539       if (AccessKind == AK_Increment)
4540         Value = 1;
4541       else
4542         Value = !Value;
4543       return true;
4544     }
4545 
4546     bool WasNegative = Value.isNegative();
4547     if (AccessKind == AK_Increment) {
4548       ++Value;
4549 
4550       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4551         APSInt ActualValue(Value, /*IsUnsigned*/true);
4552         return HandleOverflow(Info, E, ActualValue, SubobjType);
4553       }
4554     } else {
4555       --Value;
4556 
4557       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4558         unsigned BitWidth = Value.getBitWidth();
4559         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4560         ActualValue.setBit(BitWidth);
4561         return HandleOverflow(Info, E, ActualValue, SubobjType);
4562       }
4563     }
4564     return true;
4565   }
4566   bool found(APFloat &Value, QualType SubobjType) {
4567     if (!checkConst(SubobjType))
4568       return false;
4569 
4570     if (Old) *Old = APValue(Value);
4571 
4572     APFloat One(Value.getSemantics(), 1);
4573     if (AccessKind == AK_Increment)
4574       Value.add(One, APFloat::rmNearestTiesToEven);
4575     else
4576       Value.subtract(One, APFloat::rmNearestTiesToEven);
4577     return true;
4578   }
4579   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4580     if (!checkConst(SubobjType))
4581       return false;
4582 
4583     QualType PointeeType;
4584     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4585       PointeeType = PT->getPointeeType();
4586     else {
4587       Info.FFDiag(E);
4588       return false;
4589     }
4590 
4591     LValue LVal;
4592     LVal.setFrom(Info.Ctx, Subobj);
4593     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4594                                      AccessKind == AK_Increment ? 1 : -1))
4595       return false;
4596     LVal.moveInto(Subobj);
4597     return true;
4598   }
4599 };
4600 } // end anonymous namespace
4601 
4602 /// Perform an increment or decrement on LVal.
4603 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4604                          QualType LValType, bool IsIncrement, APValue *Old) {
4605   if (LVal.Designator.Invalid)
4606     return false;
4607 
4608   if (!Info.getLangOpts().CPlusPlus14) {
4609     Info.FFDiag(E);
4610     return false;
4611   }
4612 
4613   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4614   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4615   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4616   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4617 }
4618 
4619 /// Build an lvalue for the object argument of a member function call.
4620 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4621                                    LValue &This) {
4622   if (Object->getType()->isPointerType() && Object->isPRValue())
4623     return EvaluatePointer(Object, This, Info);
4624 
4625   if (Object->isGLValue())
4626     return EvaluateLValue(Object, This, Info);
4627 
4628   if (Object->getType()->isLiteralType(Info.Ctx))
4629     return EvaluateTemporary(Object, This, Info);
4630 
4631   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4632   return false;
4633 }
4634 
4635 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4636 /// lvalue referring to the result.
4637 ///
4638 /// \param Info - Information about the ongoing evaluation.
4639 /// \param LV - An lvalue referring to the base of the member pointer.
4640 /// \param RHS - The member pointer expression.
4641 /// \param IncludeMember - Specifies whether the member itself is included in
4642 ///        the resulting LValue subobject designator. This is not possible when
4643 ///        creating a bound member function.
4644 /// \return The field or method declaration to which the member pointer refers,
4645 ///         or 0 if evaluation fails.
4646 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4647                                                   QualType LVType,
4648                                                   LValue &LV,
4649                                                   const Expr *RHS,
4650                                                   bool IncludeMember = true) {
4651   MemberPtr MemPtr;
4652   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4653     return nullptr;
4654 
4655   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4656   // member value, the behavior is undefined.
4657   if (!MemPtr.getDecl()) {
4658     // FIXME: Specific diagnostic.
4659     Info.FFDiag(RHS);
4660     return nullptr;
4661   }
4662 
4663   if (MemPtr.isDerivedMember()) {
4664     // This is a member of some derived class. Truncate LV appropriately.
4665     // The end of the derived-to-base path for the base object must match the
4666     // derived-to-base path for the member pointer.
4667     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4668         LV.Designator.Entries.size()) {
4669       Info.FFDiag(RHS);
4670       return nullptr;
4671     }
4672     unsigned PathLengthToMember =
4673         LV.Designator.Entries.size() - MemPtr.Path.size();
4674     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4675       const CXXRecordDecl *LVDecl = getAsBaseClass(
4676           LV.Designator.Entries[PathLengthToMember + I]);
4677       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4678       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4679         Info.FFDiag(RHS);
4680         return nullptr;
4681       }
4682     }
4683 
4684     // Truncate the lvalue to the appropriate derived class.
4685     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4686                             PathLengthToMember))
4687       return nullptr;
4688   } else if (!MemPtr.Path.empty()) {
4689     // Extend the LValue path with the member pointer's path.
4690     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4691                                   MemPtr.Path.size() + IncludeMember);
4692 
4693     // Walk down to the appropriate base class.
4694     if (const PointerType *PT = LVType->getAs<PointerType>())
4695       LVType = PT->getPointeeType();
4696     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4697     assert(RD && "member pointer access on non-class-type expression");
4698     // The first class in the path is that of the lvalue.
4699     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4700       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4701       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4702         return nullptr;
4703       RD = Base;
4704     }
4705     // Finally cast to the class containing the member.
4706     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4707                                 MemPtr.getContainingRecord()))
4708       return nullptr;
4709   }
4710 
4711   // Add the member. Note that we cannot build bound member functions here.
4712   if (IncludeMember) {
4713     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4714       if (!HandleLValueMember(Info, RHS, LV, FD))
4715         return nullptr;
4716     } else if (const IndirectFieldDecl *IFD =
4717                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4718       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4719         return nullptr;
4720     } else {
4721       llvm_unreachable("can't construct reference to bound member function");
4722     }
4723   }
4724 
4725   return MemPtr.getDecl();
4726 }
4727 
4728 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4729                                                   const BinaryOperator *BO,
4730                                                   LValue &LV,
4731                                                   bool IncludeMember = true) {
4732   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4733 
4734   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4735     if (Info.noteFailure()) {
4736       MemberPtr MemPtr;
4737       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4738     }
4739     return nullptr;
4740   }
4741 
4742   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4743                                    BO->getRHS(), IncludeMember);
4744 }
4745 
4746 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4747 /// the provided lvalue, which currently refers to the base object.
4748 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4749                                     LValue &Result) {
4750   SubobjectDesignator &D = Result.Designator;
4751   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4752     return false;
4753 
4754   QualType TargetQT = E->getType();
4755   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4756     TargetQT = PT->getPointeeType();
4757 
4758   // Check this cast lands within the final derived-to-base subobject path.
4759   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4760     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4761       << D.MostDerivedType << TargetQT;
4762     return false;
4763   }
4764 
4765   // Check the type of the final cast. We don't need to check the path,
4766   // since a cast can only be formed if the path is unique.
4767   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4768   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4769   const CXXRecordDecl *FinalType;
4770   if (NewEntriesSize == D.MostDerivedPathLength)
4771     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4772   else
4773     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4774   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4775     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4776       << D.MostDerivedType << TargetQT;
4777     return false;
4778   }
4779 
4780   // Truncate the lvalue to the appropriate derived class.
4781   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4782 }
4783 
4784 /// Get the value to use for a default-initialized object of type T.
4785 /// Return false if it encounters something invalid.
4786 static bool getDefaultInitValue(QualType T, APValue &Result) {
4787   bool Success = true;
4788   if (auto *RD = T->getAsCXXRecordDecl()) {
4789     if (RD->isInvalidDecl()) {
4790       Result = APValue();
4791       return false;
4792     }
4793     if (RD->isUnion()) {
4794       Result = APValue((const FieldDecl *)nullptr);
4795       return true;
4796     }
4797     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4798                      std::distance(RD->field_begin(), RD->field_end()));
4799 
4800     unsigned Index = 0;
4801     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4802                                                   End = RD->bases_end();
4803          I != End; ++I, ++Index)
4804       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4805 
4806     for (const auto *I : RD->fields()) {
4807       if (I->isUnnamedBitfield())
4808         continue;
4809       Success &= getDefaultInitValue(I->getType(),
4810                                      Result.getStructField(I->getFieldIndex()));
4811     }
4812     return Success;
4813   }
4814 
4815   if (auto *AT =
4816           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4817     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4818     if (Result.hasArrayFiller())
4819       Success &=
4820           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4821 
4822     return Success;
4823   }
4824 
4825   Result = APValue::IndeterminateValue();
4826   return true;
4827 }
4828 
4829 namespace {
4830 enum EvalStmtResult {
4831   /// Evaluation failed.
4832   ESR_Failed,
4833   /// Hit a 'return' statement.
4834   ESR_Returned,
4835   /// Evaluation succeeded.
4836   ESR_Succeeded,
4837   /// Hit a 'continue' statement.
4838   ESR_Continue,
4839   /// Hit a 'break' statement.
4840   ESR_Break,
4841   /// Still scanning for 'case' or 'default' statement.
4842   ESR_CaseNotFound
4843 };
4844 }
4845 
4846 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4847   // We don't need to evaluate the initializer for a static local.
4848   if (!VD->hasLocalStorage())
4849     return true;
4850 
4851   LValue Result;
4852   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4853                                                    ScopeKind::Block, Result);
4854 
4855   const Expr *InitE = VD->getInit();
4856   if (!InitE) {
4857     if (VD->getType()->isDependentType())
4858       return Info.noteSideEffect();
4859     return getDefaultInitValue(VD->getType(), Val);
4860   }
4861   if (InitE->isValueDependent())
4862     return false;
4863 
4864   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4865     // Wipe out any partially-computed value, to allow tracking that this
4866     // evaluation failed.
4867     Val = APValue();
4868     return false;
4869   }
4870 
4871   return true;
4872 }
4873 
4874 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4875   bool OK = true;
4876 
4877   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4878     OK &= EvaluateVarDecl(Info, VD);
4879 
4880   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4881     for (auto *BD : DD->bindings())
4882       if (auto *VD = BD->getHoldingVar())
4883         OK &= EvaluateDecl(Info, VD);
4884 
4885   return OK;
4886 }
4887 
4888 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4889   assert(E->isValueDependent());
4890   if (Info.noteSideEffect())
4891     return true;
4892   assert(E->containsErrors() && "valid value-dependent expression should never "
4893                                 "reach invalid code path.");
4894   return false;
4895 }
4896 
4897 /// Evaluate a condition (either a variable declaration or an expression).
4898 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4899                          const Expr *Cond, bool &Result) {
4900   if (Cond->isValueDependent())
4901     return false;
4902   FullExpressionRAII Scope(Info);
4903   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4904     return false;
4905   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4906     return false;
4907   return Scope.destroy();
4908 }
4909 
4910 namespace {
4911 /// A location where the result (returned value) of evaluating a
4912 /// statement should be stored.
4913 struct StmtResult {
4914   /// The APValue that should be filled in with the returned value.
4915   APValue &Value;
4916   /// The location containing the result, if any (used to support RVO).
4917   const LValue *Slot;
4918 };
4919 
4920 struct TempVersionRAII {
4921   CallStackFrame &Frame;
4922 
4923   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4924     Frame.pushTempVersion();
4925   }
4926 
4927   ~TempVersionRAII() {
4928     Frame.popTempVersion();
4929   }
4930 };
4931 
4932 }
4933 
4934 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4935                                    const Stmt *S,
4936                                    const SwitchCase *SC = nullptr);
4937 
4938 /// Evaluate the body of a loop, and translate the result as appropriate.
4939 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4940                                        const Stmt *Body,
4941                                        const SwitchCase *Case = nullptr) {
4942   BlockScopeRAII Scope(Info);
4943 
4944   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4945   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4946     ESR = ESR_Failed;
4947 
4948   switch (ESR) {
4949   case ESR_Break:
4950     return ESR_Succeeded;
4951   case ESR_Succeeded:
4952   case ESR_Continue:
4953     return ESR_Continue;
4954   case ESR_Failed:
4955   case ESR_Returned:
4956   case ESR_CaseNotFound:
4957     return ESR;
4958   }
4959   llvm_unreachable("Invalid EvalStmtResult!");
4960 }
4961 
4962 /// Evaluate a switch statement.
4963 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4964                                      const SwitchStmt *SS) {
4965   BlockScopeRAII Scope(Info);
4966 
4967   // Evaluate the switch condition.
4968   APSInt Value;
4969   {
4970     if (const Stmt *Init = SS->getInit()) {
4971       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4972       if (ESR != ESR_Succeeded) {
4973         if (ESR != ESR_Failed && !Scope.destroy())
4974           ESR = ESR_Failed;
4975         return ESR;
4976       }
4977     }
4978 
4979     FullExpressionRAII CondScope(Info);
4980     if (SS->getConditionVariable() &&
4981         !EvaluateDecl(Info, SS->getConditionVariable()))
4982       return ESR_Failed;
4983     if (SS->getCond()->isValueDependent()) {
4984       if (!EvaluateDependentExpr(SS->getCond(), Info))
4985         return ESR_Failed;
4986     } else {
4987       if (!EvaluateInteger(SS->getCond(), Value, Info))
4988         return ESR_Failed;
4989     }
4990     if (!CondScope.destroy())
4991       return ESR_Failed;
4992   }
4993 
4994   // Find the switch case corresponding to the value of the condition.
4995   // FIXME: Cache this lookup.
4996   const SwitchCase *Found = nullptr;
4997   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4998        SC = SC->getNextSwitchCase()) {
4999     if (isa<DefaultStmt>(SC)) {
5000       Found = SC;
5001       continue;
5002     }
5003 
5004     const CaseStmt *CS = cast<CaseStmt>(SC);
5005     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5006     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5007                               : LHS;
5008     if (LHS <= Value && Value <= RHS) {
5009       Found = SC;
5010       break;
5011     }
5012   }
5013 
5014   if (!Found)
5015     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5016 
5017   // Search the switch body for the switch case and evaluate it from there.
5018   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5019   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5020     return ESR_Failed;
5021 
5022   switch (ESR) {
5023   case ESR_Break:
5024     return ESR_Succeeded;
5025   case ESR_Succeeded:
5026   case ESR_Continue:
5027   case ESR_Failed:
5028   case ESR_Returned:
5029     return ESR;
5030   case ESR_CaseNotFound:
5031     // This can only happen if the switch case is nested within a statement
5032     // expression. We have no intention of supporting that.
5033     Info.FFDiag(Found->getBeginLoc(),
5034                 diag::note_constexpr_stmt_expr_unsupported);
5035     return ESR_Failed;
5036   }
5037   llvm_unreachable("Invalid EvalStmtResult!");
5038 }
5039 
5040 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5041   // An expression E is a core constant expression unless the evaluation of E
5042   // would evaluate one of the following: [C++2b] - a control flow that passes
5043   // through a declaration of a variable with static or thread storage duration.
5044   if (VD->isLocalVarDecl() && VD->isStaticLocal()) {
5045     Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5046         << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5047     return false;
5048   }
5049   return true;
5050 }
5051 
5052 // Evaluate a statement.
5053 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5054                                    const Stmt *S, const SwitchCase *Case) {
5055   if (!Info.nextStep(S))
5056     return ESR_Failed;
5057 
5058   // If we're hunting down a 'case' or 'default' label, recurse through
5059   // substatements until we hit the label.
5060   if (Case) {
5061     switch (S->getStmtClass()) {
5062     case Stmt::CompoundStmtClass:
5063       // FIXME: Precompute which substatement of a compound statement we
5064       // would jump to, and go straight there rather than performing a
5065       // linear scan each time.
5066     case Stmt::LabelStmtClass:
5067     case Stmt::AttributedStmtClass:
5068     case Stmt::DoStmtClass:
5069       break;
5070 
5071     case Stmt::CaseStmtClass:
5072     case Stmt::DefaultStmtClass:
5073       if (Case == S)
5074         Case = nullptr;
5075       break;
5076 
5077     case Stmt::IfStmtClass: {
5078       // FIXME: Precompute which side of an 'if' we would jump to, and go
5079       // straight there rather than scanning both sides.
5080       const IfStmt *IS = cast<IfStmt>(S);
5081 
5082       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5083       // preceded by our switch label.
5084       BlockScopeRAII Scope(Info);
5085 
5086       // Step into the init statement in case it brings an (uninitialized)
5087       // variable into scope.
5088       if (const Stmt *Init = IS->getInit()) {
5089         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5090         if (ESR != ESR_CaseNotFound) {
5091           assert(ESR != ESR_Succeeded);
5092           return ESR;
5093         }
5094       }
5095 
5096       // Condition variable must be initialized if it exists.
5097       // FIXME: We can skip evaluating the body if there's a condition
5098       // variable, as there can't be any case labels within it.
5099       // (The same is true for 'for' statements.)
5100 
5101       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5102       if (ESR == ESR_Failed)
5103         return ESR;
5104       if (ESR != ESR_CaseNotFound)
5105         return Scope.destroy() ? ESR : ESR_Failed;
5106       if (!IS->getElse())
5107         return ESR_CaseNotFound;
5108 
5109       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5110       if (ESR == ESR_Failed)
5111         return ESR;
5112       if (ESR != ESR_CaseNotFound)
5113         return Scope.destroy() ? ESR : ESR_Failed;
5114       return ESR_CaseNotFound;
5115     }
5116 
5117     case Stmt::WhileStmtClass: {
5118       EvalStmtResult ESR =
5119           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5120       if (ESR != ESR_Continue)
5121         return ESR;
5122       break;
5123     }
5124 
5125     case Stmt::ForStmtClass: {
5126       const ForStmt *FS = cast<ForStmt>(S);
5127       BlockScopeRAII Scope(Info);
5128 
5129       // Step into the init statement in case it brings an (uninitialized)
5130       // variable into scope.
5131       if (const Stmt *Init = FS->getInit()) {
5132         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5133         if (ESR != ESR_CaseNotFound) {
5134           assert(ESR != ESR_Succeeded);
5135           return ESR;
5136         }
5137       }
5138 
5139       EvalStmtResult ESR =
5140           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5141       if (ESR != ESR_Continue)
5142         return ESR;
5143       if (const auto *Inc = FS->getInc()) {
5144         if (Inc->isValueDependent()) {
5145           if (!EvaluateDependentExpr(Inc, Info))
5146             return ESR_Failed;
5147         } else {
5148           FullExpressionRAII IncScope(Info);
5149           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5150             return ESR_Failed;
5151         }
5152       }
5153       break;
5154     }
5155 
5156     case Stmt::DeclStmtClass: {
5157       // Start the lifetime of any uninitialized variables we encounter. They
5158       // might be used by the selected branch of the switch.
5159       const DeclStmt *DS = cast<DeclStmt>(S);
5160       for (const auto *D : DS->decls()) {
5161         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5162           if (!CheckLocalVariableDeclaration(Info, VD))
5163             return ESR_Failed;
5164           if (VD->hasLocalStorage() && !VD->getInit())
5165             if (!EvaluateVarDecl(Info, VD))
5166               return ESR_Failed;
5167           // FIXME: If the variable has initialization that can't be jumped
5168           // over, bail out of any immediately-surrounding compound-statement
5169           // too. There can't be any case labels here.
5170         }
5171       }
5172       return ESR_CaseNotFound;
5173     }
5174 
5175     default:
5176       return ESR_CaseNotFound;
5177     }
5178   }
5179 
5180   switch (S->getStmtClass()) {
5181   default:
5182     if (const Expr *E = dyn_cast<Expr>(S)) {
5183       if (E->isValueDependent()) {
5184         if (!EvaluateDependentExpr(E, Info))
5185           return ESR_Failed;
5186       } else {
5187         // Don't bother evaluating beyond an expression-statement which couldn't
5188         // be evaluated.
5189         // FIXME: Do we need the FullExpressionRAII object here?
5190         // VisitExprWithCleanups should create one when necessary.
5191         FullExpressionRAII Scope(Info);
5192         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5193           return ESR_Failed;
5194       }
5195       return ESR_Succeeded;
5196     }
5197 
5198     Info.FFDiag(S->getBeginLoc());
5199     return ESR_Failed;
5200 
5201   case Stmt::NullStmtClass:
5202     return ESR_Succeeded;
5203 
5204   case Stmt::DeclStmtClass: {
5205     const DeclStmt *DS = cast<DeclStmt>(S);
5206     for (const auto *D : DS->decls()) {
5207       const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5208       if (VD && !CheckLocalVariableDeclaration(Info, VD))
5209         return ESR_Failed;
5210       // Each declaration initialization is its own full-expression.
5211       FullExpressionRAII Scope(Info);
5212       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5213         return ESR_Failed;
5214       if (!Scope.destroy())
5215         return ESR_Failed;
5216     }
5217     return ESR_Succeeded;
5218   }
5219 
5220   case Stmt::ReturnStmtClass: {
5221     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5222     FullExpressionRAII Scope(Info);
5223     if (RetExpr && RetExpr->isValueDependent()) {
5224       EvaluateDependentExpr(RetExpr, Info);
5225       // We know we returned, but we don't know what the value is.
5226       return ESR_Failed;
5227     }
5228     if (RetExpr &&
5229         !(Result.Slot
5230               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5231               : Evaluate(Result.Value, Info, RetExpr)))
5232       return ESR_Failed;
5233     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5234   }
5235 
5236   case Stmt::CompoundStmtClass: {
5237     BlockScopeRAII Scope(Info);
5238 
5239     const CompoundStmt *CS = cast<CompoundStmt>(S);
5240     for (const auto *BI : CS->body()) {
5241       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5242       if (ESR == ESR_Succeeded)
5243         Case = nullptr;
5244       else if (ESR != ESR_CaseNotFound) {
5245         if (ESR != ESR_Failed && !Scope.destroy())
5246           return ESR_Failed;
5247         return ESR;
5248       }
5249     }
5250     if (Case)
5251       return ESR_CaseNotFound;
5252     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5253   }
5254 
5255   case Stmt::IfStmtClass: {
5256     const IfStmt *IS = cast<IfStmt>(S);
5257 
5258     // Evaluate the condition, as either a var decl or as an expression.
5259     BlockScopeRAII Scope(Info);
5260     if (const Stmt *Init = IS->getInit()) {
5261       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5262       if (ESR != ESR_Succeeded) {
5263         if (ESR != ESR_Failed && !Scope.destroy())
5264           return ESR_Failed;
5265         return ESR;
5266       }
5267     }
5268     bool Cond;
5269     if (IS->isConsteval())
5270       Cond = IS->isNonNegatedConsteval();
5271     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5272                            Cond))
5273       return ESR_Failed;
5274 
5275     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5276       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5277       if (ESR != ESR_Succeeded) {
5278         if (ESR != ESR_Failed && !Scope.destroy())
5279           return ESR_Failed;
5280         return ESR;
5281       }
5282     }
5283     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5284   }
5285 
5286   case Stmt::WhileStmtClass: {
5287     const WhileStmt *WS = cast<WhileStmt>(S);
5288     while (true) {
5289       BlockScopeRAII Scope(Info);
5290       bool Continue;
5291       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5292                         Continue))
5293         return ESR_Failed;
5294       if (!Continue)
5295         break;
5296 
5297       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5298       if (ESR != ESR_Continue) {
5299         if (ESR != ESR_Failed && !Scope.destroy())
5300           return ESR_Failed;
5301         return ESR;
5302       }
5303       if (!Scope.destroy())
5304         return ESR_Failed;
5305     }
5306     return ESR_Succeeded;
5307   }
5308 
5309   case Stmt::DoStmtClass: {
5310     const DoStmt *DS = cast<DoStmt>(S);
5311     bool Continue;
5312     do {
5313       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5314       if (ESR != ESR_Continue)
5315         return ESR;
5316       Case = nullptr;
5317 
5318       if (DS->getCond()->isValueDependent()) {
5319         EvaluateDependentExpr(DS->getCond(), Info);
5320         // Bailout as we don't know whether to keep going or terminate the loop.
5321         return ESR_Failed;
5322       }
5323       FullExpressionRAII CondScope(Info);
5324       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5325           !CondScope.destroy())
5326         return ESR_Failed;
5327     } while (Continue);
5328     return ESR_Succeeded;
5329   }
5330 
5331   case Stmt::ForStmtClass: {
5332     const ForStmt *FS = cast<ForStmt>(S);
5333     BlockScopeRAII ForScope(Info);
5334     if (FS->getInit()) {
5335       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5336       if (ESR != ESR_Succeeded) {
5337         if (ESR != ESR_Failed && !ForScope.destroy())
5338           return ESR_Failed;
5339         return ESR;
5340       }
5341     }
5342     while (true) {
5343       BlockScopeRAII IterScope(Info);
5344       bool Continue = true;
5345       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5346                                          FS->getCond(), Continue))
5347         return ESR_Failed;
5348       if (!Continue)
5349         break;
5350 
5351       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5352       if (ESR != ESR_Continue) {
5353         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5354           return ESR_Failed;
5355         return ESR;
5356       }
5357 
5358       if (const auto *Inc = FS->getInc()) {
5359         if (Inc->isValueDependent()) {
5360           if (!EvaluateDependentExpr(Inc, Info))
5361             return ESR_Failed;
5362         } else {
5363           FullExpressionRAII IncScope(Info);
5364           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5365             return ESR_Failed;
5366         }
5367       }
5368 
5369       if (!IterScope.destroy())
5370         return ESR_Failed;
5371     }
5372     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5373   }
5374 
5375   case Stmt::CXXForRangeStmtClass: {
5376     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5377     BlockScopeRAII Scope(Info);
5378 
5379     // Evaluate the init-statement if present.
5380     if (FS->getInit()) {
5381       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5382       if (ESR != ESR_Succeeded) {
5383         if (ESR != ESR_Failed && !Scope.destroy())
5384           return ESR_Failed;
5385         return ESR;
5386       }
5387     }
5388 
5389     // Initialize the __range variable.
5390     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5391     if (ESR != ESR_Succeeded) {
5392       if (ESR != ESR_Failed && !Scope.destroy())
5393         return ESR_Failed;
5394       return ESR;
5395     }
5396 
5397     // In error-recovery cases it's possible to get here even if we failed to
5398     // synthesize the __begin and __end variables.
5399     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5400       return ESR_Failed;
5401 
5402     // Create the __begin and __end iterators.
5403     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5404     if (ESR != ESR_Succeeded) {
5405       if (ESR != ESR_Failed && !Scope.destroy())
5406         return ESR_Failed;
5407       return ESR;
5408     }
5409     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5410     if (ESR != ESR_Succeeded) {
5411       if (ESR != ESR_Failed && !Scope.destroy())
5412         return ESR_Failed;
5413       return ESR;
5414     }
5415 
5416     while (true) {
5417       // Condition: __begin != __end.
5418       {
5419         if (FS->getCond()->isValueDependent()) {
5420           EvaluateDependentExpr(FS->getCond(), Info);
5421           // We don't know whether to keep going or terminate the loop.
5422           return ESR_Failed;
5423         }
5424         bool Continue = true;
5425         FullExpressionRAII CondExpr(Info);
5426         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5427           return ESR_Failed;
5428         if (!Continue)
5429           break;
5430       }
5431 
5432       // User's variable declaration, initialized by *__begin.
5433       BlockScopeRAII InnerScope(Info);
5434       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5435       if (ESR != ESR_Succeeded) {
5436         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5437           return ESR_Failed;
5438         return ESR;
5439       }
5440 
5441       // Loop body.
5442       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5443       if (ESR != ESR_Continue) {
5444         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5445           return ESR_Failed;
5446         return ESR;
5447       }
5448       if (FS->getInc()->isValueDependent()) {
5449         if (!EvaluateDependentExpr(FS->getInc(), Info))
5450           return ESR_Failed;
5451       } else {
5452         // Increment: ++__begin
5453         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5454           return ESR_Failed;
5455       }
5456 
5457       if (!InnerScope.destroy())
5458         return ESR_Failed;
5459     }
5460 
5461     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5462   }
5463 
5464   case Stmt::SwitchStmtClass:
5465     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5466 
5467   case Stmt::ContinueStmtClass:
5468     return ESR_Continue;
5469 
5470   case Stmt::BreakStmtClass:
5471     return ESR_Break;
5472 
5473   case Stmt::LabelStmtClass:
5474     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5475 
5476   case Stmt::AttributedStmtClass:
5477     // As a general principle, C++11 attributes can be ignored without
5478     // any semantic impact.
5479     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5480                         Case);
5481 
5482   case Stmt::CaseStmtClass:
5483   case Stmt::DefaultStmtClass:
5484     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5485   case Stmt::CXXTryStmtClass:
5486     // Evaluate try blocks by evaluating all sub statements.
5487     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5488   }
5489 }
5490 
5491 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5492 /// default constructor. If so, we'll fold it whether or not it's marked as
5493 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5494 /// so we need special handling.
5495 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5496                                            const CXXConstructorDecl *CD,
5497                                            bool IsValueInitialization) {
5498   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5499     return false;
5500 
5501   // Value-initialization does not call a trivial default constructor, so such a
5502   // call is a core constant expression whether or not the constructor is
5503   // constexpr.
5504   if (!CD->isConstexpr() && !IsValueInitialization) {
5505     if (Info.getLangOpts().CPlusPlus11) {
5506       // FIXME: If DiagDecl is an implicitly-declared special member function,
5507       // we should be much more explicit about why it's not constexpr.
5508       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5509         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5510       Info.Note(CD->getLocation(), diag::note_declared_at);
5511     } else {
5512       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5513     }
5514   }
5515   return true;
5516 }
5517 
5518 /// CheckConstexprFunction - Check that a function can be called in a constant
5519 /// expression.
5520 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5521                                    const FunctionDecl *Declaration,
5522                                    const FunctionDecl *Definition,
5523                                    const Stmt *Body) {
5524   // Potential constant expressions can contain calls to declared, but not yet
5525   // defined, constexpr functions.
5526   if (Info.checkingPotentialConstantExpression() && !Definition &&
5527       Declaration->isConstexpr())
5528     return false;
5529 
5530   // Bail out if the function declaration itself is invalid.  We will
5531   // have produced a relevant diagnostic while parsing it, so just
5532   // note the problematic sub-expression.
5533   if (Declaration->isInvalidDecl()) {
5534     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5535     return false;
5536   }
5537 
5538   // DR1872: An instantiated virtual constexpr function can't be called in a
5539   // constant expression (prior to C++20). We can still constant-fold such a
5540   // call.
5541   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5542       cast<CXXMethodDecl>(Declaration)->isVirtual())
5543     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5544 
5545   if (Definition && Definition->isInvalidDecl()) {
5546     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5547     return false;
5548   }
5549 
5550   // Can we evaluate this function call?
5551   if (Definition && Definition->isConstexpr() && Body)
5552     return true;
5553 
5554   if (Info.getLangOpts().CPlusPlus11) {
5555     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5556 
5557     // If this function is not constexpr because it is an inherited
5558     // non-constexpr constructor, diagnose that directly.
5559     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5560     if (CD && CD->isInheritingConstructor()) {
5561       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5562       if (!Inherited->isConstexpr())
5563         DiagDecl = CD = Inherited;
5564     }
5565 
5566     // FIXME: If DiagDecl is an implicitly-declared special member function
5567     // or an inheriting constructor, we should be much more explicit about why
5568     // it's not constexpr.
5569     if (CD && CD->isInheritingConstructor())
5570       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5571         << CD->getInheritedConstructor().getConstructor()->getParent();
5572     else
5573       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5574         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5575     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5576   } else {
5577     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5578   }
5579   return false;
5580 }
5581 
5582 namespace {
5583 struct CheckDynamicTypeHandler {
5584   AccessKinds AccessKind;
5585   typedef bool result_type;
5586   bool failed() { return false; }
5587   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5588   bool found(APSInt &Value, QualType SubobjType) { return true; }
5589   bool found(APFloat &Value, QualType SubobjType) { return true; }
5590 };
5591 } // end anonymous namespace
5592 
5593 /// Check that we can access the notional vptr of an object / determine its
5594 /// dynamic type.
5595 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5596                              AccessKinds AK, bool Polymorphic) {
5597   if (This.Designator.Invalid)
5598     return false;
5599 
5600   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5601 
5602   if (!Obj)
5603     return false;
5604 
5605   if (!Obj.Value) {
5606     // The object is not usable in constant expressions, so we can't inspect
5607     // its value to see if it's in-lifetime or what the active union members
5608     // are. We can still check for a one-past-the-end lvalue.
5609     if (This.Designator.isOnePastTheEnd() ||
5610         This.Designator.isMostDerivedAnUnsizedArray()) {
5611       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5612                          ? diag::note_constexpr_access_past_end
5613                          : diag::note_constexpr_access_unsized_array)
5614           << AK;
5615       return false;
5616     } else if (Polymorphic) {
5617       // Conservatively refuse to perform a polymorphic operation if we would
5618       // not be able to read a notional 'vptr' value.
5619       APValue Val;
5620       This.moveInto(Val);
5621       QualType StarThisType =
5622           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5623       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5624           << AK << Val.getAsString(Info.Ctx, StarThisType);
5625       return false;
5626     }
5627     return true;
5628   }
5629 
5630   CheckDynamicTypeHandler Handler{AK};
5631   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5632 }
5633 
5634 /// Check that the pointee of the 'this' pointer in a member function call is
5635 /// either within its lifetime or in its period of construction or destruction.
5636 static bool
5637 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5638                                      const LValue &This,
5639                                      const CXXMethodDecl *NamedMember) {
5640   return checkDynamicType(
5641       Info, E, This,
5642       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5643 }
5644 
5645 struct DynamicType {
5646   /// The dynamic class type of the object.
5647   const CXXRecordDecl *Type;
5648   /// The corresponding path length in the lvalue.
5649   unsigned PathLength;
5650 };
5651 
5652 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5653                                              unsigned PathLength) {
5654   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5655       Designator.Entries.size() && "invalid path length");
5656   return (PathLength == Designator.MostDerivedPathLength)
5657              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5658              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5659 }
5660 
5661 /// Determine the dynamic type of an object.
5662 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5663                                                 LValue &This, AccessKinds AK) {
5664   // If we don't have an lvalue denoting an object of class type, there is no
5665   // meaningful dynamic type. (We consider objects of non-class type to have no
5666   // dynamic type.)
5667   if (!checkDynamicType(Info, E, This, AK, true))
5668     return None;
5669 
5670   // Refuse to compute a dynamic type in the presence of virtual bases. This
5671   // shouldn't happen other than in constant-folding situations, since literal
5672   // types can't have virtual bases.
5673   //
5674   // Note that consumers of DynamicType assume that the type has no virtual
5675   // bases, and will need modifications if this restriction is relaxed.
5676   const CXXRecordDecl *Class =
5677       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5678   if (!Class || Class->getNumVBases()) {
5679     Info.FFDiag(E);
5680     return None;
5681   }
5682 
5683   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5684   // binary search here instead. But the overwhelmingly common case is that
5685   // we're not in the middle of a constructor, so it probably doesn't matter
5686   // in practice.
5687   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5688   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5689        PathLength <= Path.size(); ++PathLength) {
5690     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5691                                       Path.slice(0, PathLength))) {
5692     case ConstructionPhase::Bases:
5693     case ConstructionPhase::DestroyingBases:
5694       // We're constructing or destroying a base class. This is not the dynamic
5695       // type.
5696       break;
5697 
5698     case ConstructionPhase::None:
5699     case ConstructionPhase::AfterBases:
5700     case ConstructionPhase::AfterFields:
5701     case ConstructionPhase::Destroying:
5702       // We've finished constructing the base classes and not yet started
5703       // destroying them again, so this is the dynamic type.
5704       return DynamicType{getBaseClassType(This.Designator, PathLength),
5705                          PathLength};
5706     }
5707   }
5708 
5709   // CWG issue 1517: we're constructing a base class of the object described by
5710   // 'This', so that object has not yet begun its period of construction and
5711   // any polymorphic operation on it results in undefined behavior.
5712   Info.FFDiag(E);
5713   return None;
5714 }
5715 
5716 /// Perform virtual dispatch.
5717 static const CXXMethodDecl *HandleVirtualDispatch(
5718     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5719     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5720   Optional<DynamicType> DynType = ComputeDynamicType(
5721       Info, E, This,
5722       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5723   if (!DynType)
5724     return nullptr;
5725 
5726   // Find the final overrider. It must be declared in one of the classes on the
5727   // path from the dynamic type to the static type.
5728   // FIXME: If we ever allow literal types to have virtual base classes, that
5729   // won't be true.
5730   const CXXMethodDecl *Callee = Found;
5731   unsigned PathLength = DynType->PathLength;
5732   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5733     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5734     const CXXMethodDecl *Overrider =
5735         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5736     if (Overrider) {
5737       Callee = Overrider;
5738       break;
5739     }
5740   }
5741 
5742   // C++2a [class.abstract]p6:
5743   //   the effect of making a virtual call to a pure virtual function [...] is
5744   //   undefined
5745   if (Callee->isPure()) {
5746     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5747     Info.Note(Callee->getLocation(), diag::note_declared_at);
5748     return nullptr;
5749   }
5750 
5751   // If necessary, walk the rest of the path to determine the sequence of
5752   // covariant adjustment steps to apply.
5753   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5754                                        Found->getReturnType())) {
5755     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5756     for (unsigned CovariantPathLength = PathLength + 1;
5757          CovariantPathLength != This.Designator.Entries.size();
5758          ++CovariantPathLength) {
5759       const CXXRecordDecl *NextClass =
5760           getBaseClassType(This.Designator, CovariantPathLength);
5761       const CXXMethodDecl *Next =
5762           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5763       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5764                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5765         CovariantAdjustmentPath.push_back(Next->getReturnType());
5766     }
5767     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5768                                          CovariantAdjustmentPath.back()))
5769       CovariantAdjustmentPath.push_back(Found->getReturnType());
5770   }
5771 
5772   // Perform 'this' adjustment.
5773   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5774     return nullptr;
5775 
5776   return Callee;
5777 }
5778 
5779 /// Perform the adjustment from a value returned by a virtual function to
5780 /// a value of the statically expected type, which may be a pointer or
5781 /// reference to a base class of the returned type.
5782 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5783                                             APValue &Result,
5784                                             ArrayRef<QualType> Path) {
5785   assert(Result.isLValue() &&
5786          "unexpected kind of APValue for covariant return");
5787   if (Result.isNullPointer())
5788     return true;
5789 
5790   LValue LVal;
5791   LVal.setFrom(Info.Ctx, Result);
5792 
5793   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5794   for (unsigned I = 1; I != Path.size(); ++I) {
5795     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5796     assert(OldClass && NewClass && "unexpected kind of covariant return");
5797     if (OldClass != NewClass &&
5798         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5799       return false;
5800     OldClass = NewClass;
5801   }
5802 
5803   LVal.moveInto(Result);
5804   return true;
5805 }
5806 
5807 /// Determine whether \p Base, which is known to be a direct base class of
5808 /// \p Derived, is a public base class.
5809 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5810                               const CXXRecordDecl *Base) {
5811   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5812     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5813     if (BaseClass && declaresSameEntity(BaseClass, Base))
5814       return BaseSpec.getAccessSpecifier() == AS_public;
5815   }
5816   llvm_unreachable("Base is not a direct base of Derived");
5817 }
5818 
5819 /// Apply the given dynamic cast operation on the provided lvalue.
5820 ///
5821 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5822 /// to find a suitable target subobject.
5823 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5824                               LValue &Ptr) {
5825   // We can't do anything with a non-symbolic pointer value.
5826   SubobjectDesignator &D = Ptr.Designator;
5827   if (D.Invalid)
5828     return false;
5829 
5830   // C++ [expr.dynamic.cast]p6:
5831   //   If v is a null pointer value, the result is a null pointer value.
5832   if (Ptr.isNullPointer() && !E->isGLValue())
5833     return true;
5834 
5835   // For all the other cases, we need the pointer to point to an object within
5836   // its lifetime / period of construction / destruction, and we need to know
5837   // its dynamic type.
5838   Optional<DynamicType> DynType =
5839       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5840   if (!DynType)
5841     return false;
5842 
5843   // C++ [expr.dynamic.cast]p7:
5844   //   If T is "pointer to cv void", then the result is a pointer to the most
5845   //   derived object
5846   if (E->getType()->isVoidPointerType())
5847     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5848 
5849   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5850   assert(C && "dynamic_cast target is not void pointer nor class");
5851   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5852 
5853   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5854     // C++ [expr.dynamic.cast]p9:
5855     if (!E->isGLValue()) {
5856       //   The value of a failed cast to pointer type is the null pointer value
5857       //   of the required result type.
5858       Ptr.setNull(Info.Ctx, E->getType());
5859       return true;
5860     }
5861 
5862     //   A failed cast to reference type throws [...] std::bad_cast.
5863     unsigned DiagKind;
5864     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5865                    DynType->Type->isDerivedFrom(C)))
5866       DiagKind = 0;
5867     else if (!Paths || Paths->begin() == Paths->end())
5868       DiagKind = 1;
5869     else if (Paths->isAmbiguous(CQT))
5870       DiagKind = 2;
5871     else {
5872       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5873       DiagKind = 3;
5874     }
5875     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5876         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5877         << Info.Ctx.getRecordType(DynType->Type)
5878         << E->getType().getUnqualifiedType();
5879     return false;
5880   };
5881 
5882   // Runtime check, phase 1:
5883   //   Walk from the base subobject towards the derived object looking for the
5884   //   target type.
5885   for (int PathLength = Ptr.Designator.Entries.size();
5886        PathLength >= (int)DynType->PathLength; --PathLength) {
5887     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5888     if (declaresSameEntity(Class, C))
5889       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5890     // We can only walk across public inheritance edges.
5891     if (PathLength > (int)DynType->PathLength &&
5892         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5893                            Class))
5894       return RuntimeCheckFailed(nullptr);
5895   }
5896 
5897   // Runtime check, phase 2:
5898   //   Search the dynamic type for an unambiguous public base of type C.
5899   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5900                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5901   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5902       Paths.front().Access == AS_public) {
5903     // Downcast to the dynamic type...
5904     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5905       return false;
5906     // ... then upcast to the chosen base class subobject.
5907     for (CXXBasePathElement &Elem : Paths.front())
5908       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5909         return false;
5910     return true;
5911   }
5912 
5913   // Otherwise, the runtime check fails.
5914   return RuntimeCheckFailed(&Paths);
5915 }
5916 
5917 namespace {
5918 struct StartLifetimeOfUnionMemberHandler {
5919   EvalInfo &Info;
5920   const Expr *LHSExpr;
5921   const FieldDecl *Field;
5922   bool DuringInit;
5923   bool Failed = false;
5924   static const AccessKinds AccessKind = AK_Assign;
5925 
5926   typedef bool result_type;
5927   bool failed() { return Failed; }
5928   bool found(APValue &Subobj, QualType SubobjType) {
5929     // We are supposed to perform no initialization but begin the lifetime of
5930     // the object. We interpret that as meaning to do what default
5931     // initialization of the object would do if all constructors involved were
5932     // trivial:
5933     //  * All base, non-variant member, and array element subobjects' lifetimes
5934     //    begin
5935     //  * No variant members' lifetimes begin
5936     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5937     assert(SubobjType->isUnionType());
5938     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5939       // This union member is already active. If it's also in-lifetime, there's
5940       // nothing to do.
5941       if (Subobj.getUnionValue().hasValue())
5942         return true;
5943     } else if (DuringInit) {
5944       // We're currently in the process of initializing a different union
5945       // member.  If we carried on, that initialization would attempt to
5946       // store to an inactive union member, resulting in undefined behavior.
5947       Info.FFDiag(LHSExpr,
5948                   diag::note_constexpr_union_member_change_during_init);
5949       return false;
5950     }
5951     APValue Result;
5952     Failed = !getDefaultInitValue(Field->getType(), Result);
5953     Subobj.setUnion(Field, Result);
5954     return true;
5955   }
5956   bool found(APSInt &Value, QualType SubobjType) {
5957     llvm_unreachable("wrong value kind for union object");
5958   }
5959   bool found(APFloat &Value, QualType SubobjType) {
5960     llvm_unreachable("wrong value kind for union object");
5961   }
5962 };
5963 } // end anonymous namespace
5964 
5965 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5966 
5967 /// Handle a builtin simple-assignment or a call to a trivial assignment
5968 /// operator whose left-hand side might involve a union member access. If it
5969 /// does, implicitly start the lifetime of any accessed union elements per
5970 /// C++20 [class.union]5.
5971 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5972                                           const LValue &LHS) {
5973   if (LHS.InvalidBase || LHS.Designator.Invalid)
5974     return false;
5975 
5976   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5977   // C++ [class.union]p5:
5978   //   define the set S(E) of subexpressions of E as follows:
5979   unsigned PathLength = LHS.Designator.Entries.size();
5980   for (const Expr *E = LHSExpr; E != nullptr;) {
5981     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5982     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5983       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5984       // Note that we can't implicitly start the lifetime of a reference,
5985       // so we don't need to proceed any further if we reach one.
5986       if (!FD || FD->getType()->isReferenceType())
5987         break;
5988 
5989       //    ... and also contains A.B if B names a union member ...
5990       if (FD->getParent()->isUnion()) {
5991         //    ... of a non-class, non-array type, or of a class type with a
5992         //    trivial default constructor that is not deleted, or an array of
5993         //    such types.
5994         auto *RD =
5995             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5996         if (!RD || RD->hasTrivialDefaultConstructor())
5997           UnionPathLengths.push_back({PathLength - 1, FD});
5998       }
5999 
6000       E = ME->getBase();
6001       --PathLength;
6002       assert(declaresSameEntity(FD,
6003                                 LHS.Designator.Entries[PathLength]
6004                                     .getAsBaseOrMember().getPointer()));
6005 
6006       //   -- If E is of the form A[B] and is interpreted as a built-in array
6007       //      subscripting operator, S(E) is [S(the array operand, if any)].
6008     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6009       // Step over an ArrayToPointerDecay implicit cast.
6010       auto *Base = ASE->getBase()->IgnoreImplicit();
6011       if (!Base->getType()->isArrayType())
6012         break;
6013 
6014       E = Base;
6015       --PathLength;
6016 
6017     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6018       // Step over a derived-to-base conversion.
6019       E = ICE->getSubExpr();
6020       if (ICE->getCastKind() == CK_NoOp)
6021         continue;
6022       if (ICE->getCastKind() != CK_DerivedToBase &&
6023           ICE->getCastKind() != CK_UncheckedDerivedToBase)
6024         break;
6025       // Walk path backwards as we walk up from the base to the derived class.
6026       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6027         --PathLength;
6028         (void)Elt;
6029         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6030                                   LHS.Designator.Entries[PathLength]
6031                                       .getAsBaseOrMember().getPointer()));
6032       }
6033 
6034     //   -- Otherwise, S(E) is empty.
6035     } else {
6036       break;
6037     }
6038   }
6039 
6040   // Common case: no unions' lifetimes are started.
6041   if (UnionPathLengths.empty())
6042     return true;
6043 
6044   //   if modification of X [would access an inactive union member], an object
6045   //   of the type of X is implicitly created
6046   CompleteObject Obj =
6047       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6048   if (!Obj)
6049     return false;
6050   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6051            llvm::reverse(UnionPathLengths)) {
6052     // Form a designator for the union object.
6053     SubobjectDesignator D = LHS.Designator;
6054     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6055 
6056     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6057                       ConstructionPhase::AfterBases;
6058     StartLifetimeOfUnionMemberHandler StartLifetime{
6059         Info, LHSExpr, LengthAndField.second, DuringInit};
6060     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6061       return false;
6062   }
6063 
6064   return true;
6065 }
6066 
6067 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6068                             CallRef Call, EvalInfo &Info,
6069                             bool NonNull = false) {
6070   LValue LV;
6071   // Create the parameter slot and register its destruction. For a vararg
6072   // argument, create a temporary.
6073   // FIXME: For calling conventions that destroy parameters in the callee,
6074   // should we consider performing destruction when the function returns
6075   // instead?
6076   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6077                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6078                                                        ScopeKind::Call, LV);
6079   if (!EvaluateInPlace(V, Info, LV, Arg))
6080     return false;
6081 
6082   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6083   // undefined behavior, so is non-constant.
6084   if (NonNull && V.isLValue() && V.isNullPointer()) {
6085     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6086     return false;
6087   }
6088 
6089   return true;
6090 }
6091 
6092 /// Evaluate the arguments to a function call.
6093 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6094                          EvalInfo &Info, const FunctionDecl *Callee,
6095                          bool RightToLeft = false) {
6096   bool Success = true;
6097   llvm::SmallBitVector ForbiddenNullArgs;
6098   if (Callee->hasAttr<NonNullAttr>()) {
6099     ForbiddenNullArgs.resize(Args.size());
6100     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6101       if (!Attr->args_size()) {
6102         ForbiddenNullArgs.set();
6103         break;
6104       } else
6105         for (auto Idx : Attr->args()) {
6106           unsigned ASTIdx = Idx.getASTIndex();
6107           if (ASTIdx >= Args.size())
6108             continue;
6109           ForbiddenNullArgs[ASTIdx] = true;
6110         }
6111     }
6112   }
6113   for (unsigned I = 0; I < Args.size(); I++) {
6114     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6115     const ParmVarDecl *PVD =
6116         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6117     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6118     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6119       // If we're checking for a potential constant expression, evaluate all
6120       // initializers even if some of them fail.
6121       if (!Info.noteFailure())
6122         return false;
6123       Success = false;
6124     }
6125   }
6126   return Success;
6127 }
6128 
6129 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6130 /// constructor or assignment operator.
6131 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6132                               const Expr *E, APValue &Result,
6133                               bool CopyObjectRepresentation) {
6134   // Find the reference argument.
6135   CallStackFrame *Frame = Info.CurrentCall;
6136   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6137   if (!RefValue) {
6138     Info.FFDiag(E);
6139     return false;
6140   }
6141 
6142   // Copy out the contents of the RHS object.
6143   LValue RefLValue;
6144   RefLValue.setFrom(Info.Ctx, *RefValue);
6145   return handleLValueToRValueConversion(
6146       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6147       CopyObjectRepresentation);
6148 }
6149 
6150 /// Evaluate a function call.
6151 static bool HandleFunctionCall(SourceLocation CallLoc,
6152                                const FunctionDecl *Callee, const LValue *This,
6153                                ArrayRef<const Expr *> Args, CallRef Call,
6154                                const Stmt *Body, EvalInfo &Info,
6155                                APValue &Result, const LValue *ResultSlot) {
6156   if (!Info.CheckCallLimit(CallLoc))
6157     return false;
6158 
6159   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6160 
6161   // For a trivial copy or move assignment, perform an APValue copy. This is
6162   // essential for unions, where the operations performed by the assignment
6163   // operator cannot be represented as statements.
6164   //
6165   // Skip this for non-union classes with no fields; in that case, the defaulted
6166   // copy/move does not actually read the object.
6167   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6168   if (MD && MD->isDefaulted() &&
6169       (MD->getParent()->isUnion() ||
6170        (MD->isTrivial() &&
6171         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6172     assert(This &&
6173            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6174     APValue RHSValue;
6175     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6176                            MD->getParent()->isUnion()))
6177       return false;
6178     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6179                           RHSValue))
6180       return false;
6181     This->moveInto(Result);
6182     return true;
6183   } else if (MD && isLambdaCallOperator(MD)) {
6184     // We're in a lambda; determine the lambda capture field maps unless we're
6185     // just constexpr checking a lambda's call operator. constexpr checking is
6186     // done before the captures have been added to the closure object (unless
6187     // we're inferring constexpr-ness), so we don't have access to them in this
6188     // case. But since we don't need the captures to constexpr check, we can
6189     // just ignore them.
6190     if (!Info.checkingPotentialConstantExpression())
6191       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6192                                         Frame.LambdaThisCaptureField);
6193   }
6194 
6195   StmtResult Ret = {Result, ResultSlot};
6196   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6197   if (ESR == ESR_Succeeded) {
6198     if (Callee->getReturnType()->isVoidType())
6199       return true;
6200     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6201   }
6202   return ESR == ESR_Returned;
6203 }
6204 
6205 /// Evaluate a constructor call.
6206 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6207                                   CallRef Call,
6208                                   const CXXConstructorDecl *Definition,
6209                                   EvalInfo &Info, APValue &Result) {
6210   SourceLocation CallLoc = E->getExprLoc();
6211   if (!Info.CheckCallLimit(CallLoc))
6212     return false;
6213 
6214   const CXXRecordDecl *RD = Definition->getParent();
6215   if (RD->getNumVBases()) {
6216     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6217     return false;
6218   }
6219 
6220   EvalInfo::EvaluatingConstructorRAII EvalObj(
6221       Info,
6222       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6223       RD->getNumBases());
6224   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6225 
6226   // FIXME: Creating an APValue just to hold a nonexistent return value is
6227   // wasteful.
6228   APValue RetVal;
6229   StmtResult Ret = {RetVal, nullptr};
6230 
6231   // If it's a delegating constructor, delegate.
6232   if (Definition->isDelegatingConstructor()) {
6233     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6234     if ((*I)->getInit()->isValueDependent()) {
6235       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6236         return false;
6237     } else {
6238       FullExpressionRAII InitScope(Info);
6239       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6240           !InitScope.destroy())
6241         return false;
6242     }
6243     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6244   }
6245 
6246   // For a trivial copy or move constructor, perform an APValue copy. This is
6247   // essential for unions (or classes with anonymous union members), where the
6248   // operations performed by the constructor cannot be represented by
6249   // ctor-initializers.
6250   //
6251   // Skip this for empty non-union classes; we should not perform an
6252   // lvalue-to-rvalue conversion on them because their copy constructor does not
6253   // actually read them.
6254   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6255       (Definition->getParent()->isUnion() ||
6256        (Definition->isTrivial() &&
6257         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6258     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6259                              Definition->getParent()->isUnion());
6260   }
6261 
6262   // Reserve space for the struct members.
6263   if (!Result.hasValue()) {
6264     if (!RD->isUnion())
6265       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6266                        std::distance(RD->field_begin(), RD->field_end()));
6267     else
6268       // A union starts with no active member.
6269       Result = APValue((const FieldDecl*)nullptr);
6270   }
6271 
6272   if (RD->isInvalidDecl()) return false;
6273   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6274 
6275   // A scope for temporaries lifetime-extended by reference members.
6276   BlockScopeRAII LifetimeExtendedScope(Info);
6277 
6278   bool Success = true;
6279   unsigned BasesSeen = 0;
6280 #ifndef NDEBUG
6281   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6282 #endif
6283   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6284   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6285     // We might be initializing the same field again if this is an indirect
6286     // field initialization.
6287     if (FieldIt == RD->field_end() ||
6288         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6289       assert(Indirect && "fields out of order?");
6290       return;
6291     }
6292 
6293     // Default-initialize any fields with no explicit initializer.
6294     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6295       assert(FieldIt != RD->field_end() && "missing field?");
6296       if (!FieldIt->isUnnamedBitfield())
6297         Success &= getDefaultInitValue(
6298             FieldIt->getType(),
6299             Result.getStructField(FieldIt->getFieldIndex()));
6300     }
6301     ++FieldIt;
6302   };
6303   for (const auto *I : Definition->inits()) {
6304     LValue Subobject = This;
6305     LValue SubobjectParent = This;
6306     APValue *Value = &Result;
6307 
6308     // Determine the subobject to initialize.
6309     FieldDecl *FD = nullptr;
6310     if (I->isBaseInitializer()) {
6311       QualType BaseType(I->getBaseClass(), 0);
6312 #ifndef NDEBUG
6313       // Non-virtual base classes are initialized in the order in the class
6314       // definition. We have already checked for virtual base classes.
6315       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6316       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6317              "base class initializers not in expected order");
6318       ++BaseIt;
6319 #endif
6320       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6321                                   BaseType->getAsCXXRecordDecl(), &Layout))
6322         return false;
6323       Value = &Result.getStructBase(BasesSeen++);
6324     } else if ((FD = I->getMember())) {
6325       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6326         return false;
6327       if (RD->isUnion()) {
6328         Result = APValue(FD);
6329         Value = &Result.getUnionValue();
6330       } else {
6331         SkipToField(FD, false);
6332         Value = &Result.getStructField(FD->getFieldIndex());
6333       }
6334     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6335       // Walk the indirect field decl's chain to find the object to initialize,
6336       // and make sure we've initialized every step along it.
6337       auto IndirectFieldChain = IFD->chain();
6338       for (auto *C : IndirectFieldChain) {
6339         FD = cast<FieldDecl>(C);
6340         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6341         // Switch the union field if it differs. This happens if we had
6342         // preceding zero-initialization, and we're now initializing a union
6343         // subobject other than the first.
6344         // FIXME: In this case, the values of the other subobjects are
6345         // specified, since zero-initialization sets all padding bits to zero.
6346         if (!Value->hasValue() ||
6347             (Value->isUnion() && Value->getUnionField() != FD)) {
6348           if (CD->isUnion())
6349             *Value = APValue(FD);
6350           else
6351             // FIXME: This immediately starts the lifetime of all members of
6352             // an anonymous struct. It would be preferable to strictly start
6353             // member lifetime in initialization order.
6354             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6355         }
6356         // Store Subobject as its parent before updating it for the last element
6357         // in the chain.
6358         if (C == IndirectFieldChain.back())
6359           SubobjectParent = Subobject;
6360         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6361           return false;
6362         if (CD->isUnion())
6363           Value = &Value->getUnionValue();
6364         else {
6365           if (C == IndirectFieldChain.front() && !RD->isUnion())
6366             SkipToField(FD, true);
6367           Value = &Value->getStructField(FD->getFieldIndex());
6368         }
6369       }
6370     } else {
6371       llvm_unreachable("unknown base initializer kind");
6372     }
6373 
6374     // Need to override This for implicit field initializers as in this case
6375     // This refers to innermost anonymous struct/union containing initializer,
6376     // not to currently constructed class.
6377     const Expr *Init = I->getInit();
6378     if (Init->isValueDependent()) {
6379       if (!EvaluateDependentExpr(Init, Info))
6380         return false;
6381     } else {
6382       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6383                                     isa<CXXDefaultInitExpr>(Init));
6384       FullExpressionRAII InitScope(Info);
6385       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6386           (FD && FD->isBitField() &&
6387            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6388         // If we're checking for a potential constant expression, evaluate all
6389         // initializers even if some of them fail.
6390         if (!Info.noteFailure())
6391           return false;
6392         Success = false;
6393       }
6394     }
6395 
6396     // This is the point at which the dynamic type of the object becomes this
6397     // class type.
6398     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6399       EvalObj.finishedConstructingBases();
6400   }
6401 
6402   // Default-initialize any remaining fields.
6403   if (!RD->isUnion()) {
6404     for (; FieldIt != RD->field_end(); ++FieldIt) {
6405       if (!FieldIt->isUnnamedBitfield())
6406         Success &= getDefaultInitValue(
6407             FieldIt->getType(),
6408             Result.getStructField(FieldIt->getFieldIndex()));
6409     }
6410   }
6411 
6412   EvalObj.finishedConstructingFields();
6413 
6414   return Success &&
6415          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6416          LifetimeExtendedScope.destroy();
6417 }
6418 
6419 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6420                                   ArrayRef<const Expr*> Args,
6421                                   const CXXConstructorDecl *Definition,
6422                                   EvalInfo &Info, APValue &Result) {
6423   CallScopeRAII CallScope(Info);
6424   CallRef Call = Info.CurrentCall->createCall(Definition);
6425   if (!EvaluateArgs(Args, Call, Info, Definition))
6426     return false;
6427 
6428   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6429          CallScope.destroy();
6430 }
6431 
6432 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6433                                   const LValue &This, APValue &Value,
6434                                   QualType T) {
6435   // Objects can only be destroyed while they're within their lifetimes.
6436   // FIXME: We have no representation for whether an object of type nullptr_t
6437   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6438   // as indeterminate instead?
6439   if (Value.isAbsent() && !T->isNullPtrType()) {
6440     APValue Printable;
6441     This.moveInto(Printable);
6442     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6443       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6444     return false;
6445   }
6446 
6447   // Invent an expression for location purposes.
6448   // FIXME: We shouldn't need to do this.
6449   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6450 
6451   // For arrays, destroy elements right-to-left.
6452   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6453     uint64_t Size = CAT->getSize().getZExtValue();
6454     QualType ElemT = CAT->getElementType();
6455 
6456     LValue ElemLV = This;
6457     ElemLV.addArray(Info, &LocE, CAT);
6458     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6459       return false;
6460 
6461     // Ensure that we have actual array elements available to destroy; the
6462     // destructors might mutate the value, so we can't run them on the array
6463     // filler.
6464     if (Size && Size > Value.getArrayInitializedElts())
6465       expandArray(Value, Value.getArraySize() - 1);
6466 
6467     for (; Size != 0; --Size) {
6468       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6469       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6470           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6471         return false;
6472     }
6473 
6474     // End the lifetime of this array now.
6475     Value = APValue();
6476     return true;
6477   }
6478 
6479   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6480   if (!RD) {
6481     if (T.isDestructedType()) {
6482       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6483       return false;
6484     }
6485 
6486     Value = APValue();
6487     return true;
6488   }
6489 
6490   if (RD->getNumVBases()) {
6491     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6492     return false;
6493   }
6494 
6495   const CXXDestructorDecl *DD = RD->getDestructor();
6496   if (!DD && !RD->hasTrivialDestructor()) {
6497     Info.FFDiag(CallLoc);
6498     return false;
6499   }
6500 
6501   if (!DD || DD->isTrivial() ||
6502       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6503     // A trivial destructor just ends the lifetime of the object. Check for
6504     // this case before checking for a body, because we might not bother
6505     // building a body for a trivial destructor. Note that it doesn't matter
6506     // whether the destructor is constexpr in this case; all trivial
6507     // destructors are constexpr.
6508     //
6509     // If an anonymous union would be destroyed, some enclosing destructor must
6510     // have been explicitly defined, and the anonymous union destruction should
6511     // have no effect.
6512     Value = APValue();
6513     return true;
6514   }
6515 
6516   if (!Info.CheckCallLimit(CallLoc))
6517     return false;
6518 
6519   const FunctionDecl *Definition = nullptr;
6520   const Stmt *Body = DD->getBody(Definition);
6521 
6522   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6523     return false;
6524 
6525   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6526 
6527   // We're now in the period of destruction of this object.
6528   unsigned BasesLeft = RD->getNumBases();
6529   EvalInfo::EvaluatingDestructorRAII EvalObj(
6530       Info,
6531       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6532   if (!EvalObj.DidInsert) {
6533     // C++2a [class.dtor]p19:
6534     //   the behavior is undefined if the destructor is invoked for an object
6535     //   whose lifetime has ended
6536     // (Note that formally the lifetime ends when the period of destruction
6537     // begins, even though certain uses of the object remain valid until the
6538     // period of destruction ends.)
6539     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6540     return false;
6541   }
6542 
6543   // FIXME: Creating an APValue just to hold a nonexistent return value is
6544   // wasteful.
6545   APValue RetVal;
6546   StmtResult Ret = {RetVal, nullptr};
6547   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6548     return false;
6549 
6550   // A union destructor does not implicitly destroy its members.
6551   if (RD->isUnion())
6552     return true;
6553 
6554   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6555 
6556   // We don't have a good way to iterate fields in reverse, so collect all the
6557   // fields first and then walk them backwards.
6558   SmallVector<FieldDecl*, 16> Fields(RD->fields());
6559   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6560     if (FD->isUnnamedBitfield())
6561       continue;
6562 
6563     LValue Subobject = This;
6564     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6565       return false;
6566 
6567     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6568     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6569                                FD->getType()))
6570       return false;
6571   }
6572 
6573   if (BasesLeft != 0)
6574     EvalObj.startedDestroyingBases();
6575 
6576   // Destroy base classes in reverse order.
6577   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6578     --BasesLeft;
6579 
6580     QualType BaseType = Base.getType();
6581     LValue Subobject = This;
6582     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6583                                 BaseType->getAsCXXRecordDecl(), &Layout))
6584       return false;
6585 
6586     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6587     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6588                                BaseType))
6589       return false;
6590   }
6591   assert(BasesLeft == 0 && "NumBases was wrong?");
6592 
6593   // The period of destruction ends now. The object is gone.
6594   Value = APValue();
6595   return true;
6596 }
6597 
6598 namespace {
6599 struct DestroyObjectHandler {
6600   EvalInfo &Info;
6601   const Expr *E;
6602   const LValue &This;
6603   const AccessKinds AccessKind;
6604 
6605   typedef bool result_type;
6606   bool failed() { return false; }
6607   bool found(APValue &Subobj, QualType SubobjType) {
6608     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6609                                  SubobjType);
6610   }
6611   bool found(APSInt &Value, QualType SubobjType) {
6612     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6613     return false;
6614   }
6615   bool found(APFloat &Value, QualType SubobjType) {
6616     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6617     return false;
6618   }
6619 };
6620 }
6621 
6622 /// Perform a destructor or pseudo-destructor call on the given object, which
6623 /// might in general not be a complete object.
6624 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6625                               const LValue &This, QualType ThisType) {
6626   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6627   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6628   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6629 }
6630 
6631 /// Destroy and end the lifetime of the given complete object.
6632 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6633                               APValue::LValueBase LVBase, APValue &Value,
6634                               QualType T) {
6635   // If we've had an unmodeled side-effect, we can't rely on mutable state
6636   // (such as the object we're about to destroy) being correct.
6637   if (Info.EvalStatus.HasSideEffects)
6638     return false;
6639 
6640   LValue LV;
6641   LV.set({LVBase});
6642   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6643 }
6644 
6645 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6646 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6647                                   LValue &Result) {
6648   if (Info.checkingPotentialConstantExpression() ||
6649       Info.SpeculativeEvaluationDepth)
6650     return false;
6651 
6652   // This is permitted only within a call to std::allocator<T>::allocate.
6653   auto Caller = Info.getStdAllocatorCaller("allocate");
6654   if (!Caller) {
6655     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6656                                      ? diag::note_constexpr_new_untyped
6657                                      : diag::note_constexpr_new);
6658     return false;
6659   }
6660 
6661   QualType ElemType = Caller.ElemType;
6662   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6663     Info.FFDiag(E->getExprLoc(),
6664                 diag::note_constexpr_new_not_complete_object_type)
6665         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6666     return false;
6667   }
6668 
6669   APSInt ByteSize;
6670   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6671     return false;
6672   bool IsNothrow = false;
6673   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6674     EvaluateIgnoredValue(Info, E->getArg(I));
6675     IsNothrow |= E->getType()->isNothrowT();
6676   }
6677 
6678   CharUnits ElemSize;
6679   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6680     return false;
6681   APInt Size, Remainder;
6682   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6683   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6684   if (Remainder != 0) {
6685     // This likely indicates a bug in the implementation of 'std::allocator'.
6686     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6687         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6688     return false;
6689   }
6690 
6691   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6692     if (IsNothrow) {
6693       Result.setNull(Info.Ctx, E->getType());
6694       return true;
6695     }
6696 
6697     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6698     return false;
6699   }
6700 
6701   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6702                                                      ArrayType::Normal, 0);
6703   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6704   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6705   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6706   return true;
6707 }
6708 
6709 static bool hasVirtualDestructor(QualType T) {
6710   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6711     if (CXXDestructorDecl *DD = RD->getDestructor())
6712       return DD->isVirtual();
6713   return false;
6714 }
6715 
6716 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6717   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6718     if (CXXDestructorDecl *DD = RD->getDestructor())
6719       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6720   return nullptr;
6721 }
6722 
6723 /// Check that the given object is a suitable pointer to a heap allocation that
6724 /// still exists and is of the right kind for the purpose of a deletion.
6725 ///
6726 /// On success, returns the heap allocation to deallocate. On failure, produces
6727 /// a diagnostic and returns None.
6728 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6729                                             const LValue &Pointer,
6730                                             DynAlloc::Kind DeallocKind) {
6731   auto PointerAsString = [&] {
6732     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6733   };
6734 
6735   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6736   if (!DA) {
6737     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6738         << PointerAsString();
6739     if (Pointer.Base)
6740       NoteLValueLocation(Info, Pointer.Base);
6741     return None;
6742   }
6743 
6744   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6745   if (!Alloc) {
6746     Info.FFDiag(E, diag::note_constexpr_double_delete);
6747     return None;
6748   }
6749 
6750   QualType AllocType = Pointer.Base.getDynamicAllocType();
6751   if (DeallocKind != (*Alloc)->getKind()) {
6752     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6753         << DeallocKind << (*Alloc)->getKind() << AllocType;
6754     NoteLValueLocation(Info, Pointer.Base);
6755     return None;
6756   }
6757 
6758   bool Subobject = false;
6759   if (DeallocKind == DynAlloc::New) {
6760     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6761                 Pointer.Designator.isOnePastTheEnd();
6762   } else {
6763     Subobject = Pointer.Designator.Entries.size() != 1 ||
6764                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6765   }
6766   if (Subobject) {
6767     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6768         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6769     return None;
6770   }
6771 
6772   return Alloc;
6773 }
6774 
6775 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6776 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6777   if (Info.checkingPotentialConstantExpression() ||
6778       Info.SpeculativeEvaluationDepth)
6779     return false;
6780 
6781   // This is permitted only within a call to std::allocator<T>::deallocate.
6782   if (!Info.getStdAllocatorCaller("deallocate")) {
6783     Info.FFDiag(E->getExprLoc());
6784     return true;
6785   }
6786 
6787   LValue Pointer;
6788   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6789     return false;
6790   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6791     EvaluateIgnoredValue(Info, E->getArg(I));
6792 
6793   if (Pointer.Designator.Invalid)
6794     return false;
6795 
6796   // Deleting a null pointer would have no effect, but it's not permitted by
6797   // std::allocator<T>::deallocate's contract.
6798   if (Pointer.isNullPointer()) {
6799     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6800     return true;
6801   }
6802 
6803   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6804     return false;
6805 
6806   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6807   return true;
6808 }
6809 
6810 //===----------------------------------------------------------------------===//
6811 // Generic Evaluation
6812 //===----------------------------------------------------------------------===//
6813 namespace {
6814 
6815 class BitCastBuffer {
6816   // FIXME: We're going to need bit-level granularity when we support
6817   // bit-fields.
6818   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6819   // we don't support a host or target where that is the case. Still, we should
6820   // use a more generic type in case we ever do.
6821   SmallVector<Optional<unsigned char>, 32> Bytes;
6822 
6823   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6824                 "Need at least 8 bit unsigned char");
6825 
6826   bool TargetIsLittleEndian;
6827 
6828 public:
6829   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6830       : Bytes(Width.getQuantity()),
6831         TargetIsLittleEndian(TargetIsLittleEndian) {}
6832 
6833   LLVM_NODISCARD
6834   bool readObject(CharUnits Offset, CharUnits Width,
6835                   SmallVectorImpl<unsigned char> &Output) const {
6836     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6837       // If a byte of an integer is uninitialized, then the whole integer is
6838       // uninitialized.
6839       if (!Bytes[I.getQuantity()])
6840         return false;
6841       Output.push_back(*Bytes[I.getQuantity()]);
6842     }
6843     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6844       std::reverse(Output.begin(), Output.end());
6845     return true;
6846   }
6847 
6848   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6849     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6850       std::reverse(Input.begin(), Input.end());
6851 
6852     size_t Index = 0;
6853     for (unsigned char Byte : Input) {
6854       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6855       Bytes[Offset.getQuantity() + Index] = Byte;
6856       ++Index;
6857     }
6858   }
6859 
6860   size_t size() { return Bytes.size(); }
6861 };
6862 
6863 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6864 /// target would represent the value at runtime.
6865 class APValueToBufferConverter {
6866   EvalInfo &Info;
6867   BitCastBuffer Buffer;
6868   const CastExpr *BCE;
6869 
6870   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6871                            const CastExpr *BCE)
6872       : Info(Info),
6873         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6874         BCE(BCE) {}
6875 
6876   bool visit(const APValue &Val, QualType Ty) {
6877     return visit(Val, Ty, CharUnits::fromQuantity(0));
6878   }
6879 
6880   // Write out Val with type Ty into Buffer starting at Offset.
6881   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6882     assert((size_t)Offset.getQuantity() <= Buffer.size());
6883 
6884     // As a special case, nullptr_t has an indeterminate value.
6885     if (Ty->isNullPtrType())
6886       return true;
6887 
6888     // Dig through Src to find the byte at SrcOffset.
6889     switch (Val.getKind()) {
6890     case APValue::Indeterminate:
6891     case APValue::None:
6892       return true;
6893 
6894     case APValue::Int:
6895       return visitInt(Val.getInt(), Ty, Offset);
6896     case APValue::Float:
6897       return visitFloat(Val.getFloat(), Ty, Offset);
6898     case APValue::Array:
6899       return visitArray(Val, Ty, Offset);
6900     case APValue::Struct:
6901       return visitRecord(Val, Ty, Offset);
6902 
6903     case APValue::ComplexInt:
6904     case APValue::ComplexFloat:
6905     case APValue::Vector:
6906     case APValue::FixedPoint:
6907       // FIXME: We should support these.
6908 
6909     case APValue::Union:
6910     case APValue::MemberPointer:
6911     case APValue::AddrLabelDiff: {
6912       Info.FFDiag(BCE->getBeginLoc(),
6913                   diag::note_constexpr_bit_cast_unsupported_type)
6914           << Ty;
6915       return false;
6916     }
6917 
6918     case APValue::LValue:
6919       llvm_unreachable("LValue subobject in bit_cast?");
6920     }
6921     llvm_unreachable("Unhandled APValue::ValueKind");
6922   }
6923 
6924   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6925     const RecordDecl *RD = Ty->getAsRecordDecl();
6926     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6927 
6928     // Visit the base classes.
6929     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6930       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6931         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6932         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6933 
6934         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6935                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6936           return false;
6937       }
6938     }
6939 
6940     // Visit the fields.
6941     unsigned FieldIdx = 0;
6942     for (FieldDecl *FD : RD->fields()) {
6943       if (FD->isBitField()) {
6944         Info.FFDiag(BCE->getBeginLoc(),
6945                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6946         return false;
6947       }
6948 
6949       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6950 
6951       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6952              "only bit-fields can have sub-char alignment");
6953       CharUnits FieldOffset =
6954           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6955       QualType FieldTy = FD->getType();
6956       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6957         return false;
6958       ++FieldIdx;
6959     }
6960 
6961     return true;
6962   }
6963 
6964   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6965     const auto *CAT =
6966         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6967     if (!CAT)
6968       return false;
6969 
6970     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6971     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6972     unsigned ArraySize = Val.getArraySize();
6973     // First, initialize the initialized elements.
6974     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6975       const APValue &SubObj = Val.getArrayInitializedElt(I);
6976       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6977         return false;
6978     }
6979 
6980     // Next, initialize the rest of the array using the filler.
6981     if (Val.hasArrayFiller()) {
6982       const APValue &Filler = Val.getArrayFiller();
6983       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6984         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6985           return false;
6986       }
6987     }
6988 
6989     return true;
6990   }
6991 
6992   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6993     APSInt AdjustedVal = Val;
6994     unsigned Width = AdjustedVal.getBitWidth();
6995     if (Ty->isBooleanType()) {
6996       Width = Info.Ctx.getTypeSize(Ty);
6997       AdjustedVal = AdjustedVal.extend(Width);
6998     }
6999 
7000     SmallVector<unsigned char, 8> Bytes(Width / 8);
7001     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7002     Buffer.writeObject(Offset, Bytes);
7003     return true;
7004   }
7005 
7006   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7007     APSInt AsInt(Val.bitcastToAPInt());
7008     return visitInt(AsInt, Ty, Offset);
7009   }
7010 
7011 public:
7012   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
7013                                          const CastExpr *BCE) {
7014     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7015     APValueToBufferConverter Converter(Info, DstSize, BCE);
7016     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7017       return None;
7018     return Converter.Buffer;
7019   }
7020 };
7021 
7022 /// Write an BitCastBuffer into an APValue.
7023 class BufferToAPValueConverter {
7024   EvalInfo &Info;
7025   const BitCastBuffer &Buffer;
7026   const CastExpr *BCE;
7027 
7028   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7029                            const CastExpr *BCE)
7030       : Info(Info), Buffer(Buffer), BCE(BCE) {}
7031 
7032   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7033   // with an invalid type, so anything left is a deficiency on our part (FIXME).
7034   // Ideally this will be unreachable.
7035   llvm::NoneType unsupportedType(QualType Ty) {
7036     Info.FFDiag(BCE->getBeginLoc(),
7037                 diag::note_constexpr_bit_cast_unsupported_type)
7038         << Ty;
7039     return None;
7040   }
7041 
7042   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
7043     Info.FFDiag(BCE->getBeginLoc(),
7044                 diag::note_constexpr_bit_cast_unrepresentable_value)
7045         << Ty << toString(Val, /*Radix=*/10);
7046     return None;
7047   }
7048 
7049   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7050                           const EnumType *EnumSugar = nullptr) {
7051     if (T->isNullPtrType()) {
7052       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7053       return APValue((Expr *)nullptr,
7054                      /*Offset=*/CharUnits::fromQuantity(NullValue),
7055                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7056     }
7057 
7058     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7059 
7060     // Work around floating point types that contain unused padding bytes. This
7061     // is really just `long double` on x86, which is the only fundamental type
7062     // with padding bytes.
7063     if (T->isRealFloatingType()) {
7064       const llvm::fltSemantics &Semantics =
7065           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7066       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7067       assert(NumBits % 8 == 0);
7068       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7069       if (NumBytes != SizeOf)
7070         SizeOf = NumBytes;
7071     }
7072 
7073     SmallVector<uint8_t, 8> Bytes;
7074     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7075       // If this is std::byte or unsigned char, then its okay to store an
7076       // indeterminate value.
7077       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7078       bool IsUChar =
7079           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7080                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7081       if (!IsStdByte && !IsUChar) {
7082         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7083         Info.FFDiag(BCE->getExprLoc(),
7084                     diag::note_constexpr_bit_cast_indet_dest)
7085             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7086         return None;
7087       }
7088 
7089       return APValue::IndeterminateValue();
7090     }
7091 
7092     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7093     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7094 
7095     if (T->isIntegralOrEnumerationType()) {
7096       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7097 
7098       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7099       if (IntWidth != Val.getBitWidth()) {
7100         APSInt Truncated = Val.trunc(IntWidth);
7101         if (Truncated.extend(Val.getBitWidth()) != Val)
7102           return unrepresentableValue(QualType(T, 0), Val);
7103         Val = Truncated;
7104       }
7105 
7106       return APValue(Val);
7107     }
7108 
7109     if (T->isRealFloatingType()) {
7110       const llvm::fltSemantics &Semantics =
7111           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7112       return APValue(APFloat(Semantics, Val));
7113     }
7114 
7115     return unsupportedType(QualType(T, 0));
7116   }
7117 
7118   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7119     const RecordDecl *RD = RTy->getAsRecordDecl();
7120     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7121 
7122     unsigned NumBases = 0;
7123     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7124       NumBases = CXXRD->getNumBases();
7125 
7126     APValue ResultVal(APValue::UninitStruct(), NumBases,
7127                       std::distance(RD->field_begin(), RD->field_end()));
7128 
7129     // Visit the base classes.
7130     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7131       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7132         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7133         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7134         if (BaseDecl->isEmpty() ||
7135             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7136           continue;
7137 
7138         Optional<APValue> SubObj = visitType(
7139             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7140         if (!SubObj)
7141           return None;
7142         ResultVal.getStructBase(I) = *SubObj;
7143       }
7144     }
7145 
7146     // Visit the fields.
7147     unsigned FieldIdx = 0;
7148     for (FieldDecl *FD : RD->fields()) {
7149       // FIXME: We don't currently support bit-fields. A lot of the logic for
7150       // this is in CodeGen, so we need to factor it around.
7151       if (FD->isBitField()) {
7152         Info.FFDiag(BCE->getBeginLoc(),
7153                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7154         return None;
7155       }
7156 
7157       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7158       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7159 
7160       CharUnits FieldOffset =
7161           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7162           Offset;
7163       QualType FieldTy = FD->getType();
7164       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7165       if (!SubObj)
7166         return None;
7167       ResultVal.getStructField(FieldIdx) = *SubObj;
7168       ++FieldIdx;
7169     }
7170 
7171     return ResultVal;
7172   }
7173 
7174   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7175     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7176     assert(!RepresentationType.isNull() &&
7177            "enum forward decl should be caught by Sema");
7178     const auto *AsBuiltin =
7179         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7180     // Recurse into the underlying type. Treat std::byte transparently as
7181     // unsigned char.
7182     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7183   }
7184 
7185   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7186     size_t Size = Ty->getSize().getLimitedValue();
7187     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7188 
7189     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7190     for (size_t I = 0; I != Size; ++I) {
7191       Optional<APValue> ElementValue =
7192           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7193       if (!ElementValue)
7194         return None;
7195       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7196     }
7197 
7198     return ArrayValue;
7199   }
7200 
7201   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7202     return unsupportedType(QualType(Ty, 0));
7203   }
7204 
7205   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7206     QualType Can = Ty.getCanonicalType();
7207 
7208     switch (Can->getTypeClass()) {
7209 #define TYPE(Class, Base)                                                      \
7210   case Type::Class:                                                            \
7211     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7212 #define ABSTRACT_TYPE(Class, Base)
7213 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7214   case Type::Class:                                                            \
7215     llvm_unreachable("non-canonical type should be impossible!");
7216 #define DEPENDENT_TYPE(Class, Base)                                            \
7217   case Type::Class:                                                            \
7218     llvm_unreachable(                                                          \
7219         "dependent types aren't supported in the constant evaluator!");
7220 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7221   case Type::Class:                                                            \
7222     llvm_unreachable("either dependent or not canonical!");
7223 #include "clang/AST/TypeNodes.inc"
7224     }
7225     llvm_unreachable("Unhandled Type::TypeClass");
7226   }
7227 
7228 public:
7229   // Pull out a full value of type DstType.
7230   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7231                                    const CastExpr *BCE) {
7232     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7233     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7234   }
7235 };
7236 
7237 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7238                                                  QualType Ty, EvalInfo *Info,
7239                                                  const ASTContext &Ctx,
7240                                                  bool CheckingDest) {
7241   Ty = Ty.getCanonicalType();
7242 
7243   auto diag = [&](int Reason) {
7244     if (Info)
7245       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7246           << CheckingDest << (Reason == 4) << Reason;
7247     return false;
7248   };
7249   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7250     if (Info)
7251       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7252           << NoteTy << Construct << Ty;
7253     return false;
7254   };
7255 
7256   if (Ty->isUnionType())
7257     return diag(0);
7258   if (Ty->isPointerType())
7259     return diag(1);
7260   if (Ty->isMemberPointerType())
7261     return diag(2);
7262   if (Ty.isVolatileQualified())
7263     return diag(3);
7264 
7265   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7266     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7267       for (CXXBaseSpecifier &BS : CXXRD->bases())
7268         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7269                                                   CheckingDest))
7270           return note(1, BS.getType(), BS.getBeginLoc());
7271     }
7272     for (FieldDecl *FD : Record->fields()) {
7273       if (FD->getType()->isReferenceType())
7274         return diag(4);
7275       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7276                                                 CheckingDest))
7277         return note(0, FD->getType(), FD->getBeginLoc());
7278     }
7279   }
7280 
7281   if (Ty->isArrayType() &&
7282       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7283                                             Info, Ctx, CheckingDest))
7284     return false;
7285 
7286   return true;
7287 }
7288 
7289 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7290                                              const ASTContext &Ctx,
7291                                              const CastExpr *BCE) {
7292   bool DestOK = checkBitCastConstexprEligibilityType(
7293       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7294   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7295                                 BCE->getBeginLoc(),
7296                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7297   return SourceOK;
7298 }
7299 
7300 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7301                                         APValue &SourceValue,
7302                                         const CastExpr *BCE) {
7303   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7304          "no host or target supports non 8-bit chars");
7305   assert(SourceValue.isLValue() &&
7306          "LValueToRValueBitcast requires an lvalue operand!");
7307 
7308   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7309     return false;
7310 
7311   LValue SourceLValue;
7312   APValue SourceRValue;
7313   SourceLValue.setFrom(Info.Ctx, SourceValue);
7314   if (!handleLValueToRValueConversion(
7315           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7316           SourceRValue, /*WantObjectRepresentation=*/true))
7317     return false;
7318 
7319   // Read out SourceValue into a char buffer.
7320   Optional<BitCastBuffer> Buffer =
7321       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7322   if (!Buffer)
7323     return false;
7324 
7325   // Write out the buffer into a new APValue.
7326   Optional<APValue> MaybeDestValue =
7327       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7328   if (!MaybeDestValue)
7329     return false;
7330 
7331   DestValue = std::move(*MaybeDestValue);
7332   return true;
7333 }
7334 
7335 template <class Derived>
7336 class ExprEvaluatorBase
7337   : public ConstStmtVisitor<Derived, bool> {
7338 private:
7339   Derived &getDerived() { return static_cast<Derived&>(*this); }
7340   bool DerivedSuccess(const APValue &V, const Expr *E) {
7341     return getDerived().Success(V, E);
7342   }
7343   bool DerivedZeroInitialization(const Expr *E) {
7344     return getDerived().ZeroInitialization(E);
7345   }
7346 
7347   // Check whether a conditional operator with a non-constant condition is a
7348   // potential constant expression. If neither arm is a potential constant
7349   // expression, then the conditional operator is not either.
7350   template<typename ConditionalOperator>
7351   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7352     assert(Info.checkingPotentialConstantExpression());
7353 
7354     // Speculatively evaluate both arms.
7355     SmallVector<PartialDiagnosticAt, 8> Diag;
7356     {
7357       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7358       StmtVisitorTy::Visit(E->getFalseExpr());
7359       if (Diag.empty())
7360         return;
7361     }
7362 
7363     {
7364       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7365       Diag.clear();
7366       StmtVisitorTy::Visit(E->getTrueExpr());
7367       if (Diag.empty())
7368         return;
7369     }
7370 
7371     Error(E, diag::note_constexpr_conditional_never_const);
7372   }
7373 
7374 
7375   template<typename ConditionalOperator>
7376   bool HandleConditionalOperator(const ConditionalOperator *E) {
7377     bool BoolResult;
7378     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7379       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7380         CheckPotentialConstantConditional(E);
7381         return false;
7382       }
7383       if (Info.noteFailure()) {
7384         StmtVisitorTy::Visit(E->getTrueExpr());
7385         StmtVisitorTy::Visit(E->getFalseExpr());
7386       }
7387       return false;
7388     }
7389 
7390     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7391     return StmtVisitorTy::Visit(EvalExpr);
7392   }
7393 
7394 protected:
7395   EvalInfo &Info;
7396   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7397   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7398 
7399   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7400     return Info.CCEDiag(E, D);
7401   }
7402 
7403   bool ZeroInitialization(const Expr *E) { return Error(E); }
7404 
7405 public:
7406   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7407 
7408   EvalInfo &getEvalInfo() { return Info; }
7409 
7410   /// Report an evaluation error. This should only be called when an error is
7411   /// first discovered. When propagating an error, just return false.
7412   bool Error(const Expr *E, diag::kind D) {
7413     Info.FFDiag(E, D);
7414     return false;
7415   }
7416   bool Error(const Expr *E) {
7417     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7418   }
7419 
7420   bool VisitStmt(const Stmt *) {
7421     llvm_unreachable("Expression evaluator should not be called on stmts");
7422   }
7423   bool VisitExpr(const Expr *E) {
7424     return Error(E);
7425   }
7426 
7427   bool VisitConstantExpr(const ConstantExpr *E) {
7428     if (E->hasAPValueResult())
7429       return DerivedSuccess(E->getAPValueResult(), E);
7430 
7431     return StmtVisitorTy::Visit(E->getSubExpr());
7432   }
7433 
7434   bool VisitParenExpr(const ParenExpr *E)
7435     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7436   bool VisitUnaryExtension(const UnaryOperator *E)
7437     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7438   bool VisitUnaryPlus(const UnaryOperator *E)
7439     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7440   bool VisitChooseExpr(const ChooseExpr *E)
7441     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7442   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7443     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7444   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7445     { return StmtVisitorTy::Visit(E->getReplacement()); }
7446   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7447     TempVersionRAII RAII(*Info.CurrentCall);
7448     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7449     return StmtVisitorTy::Visit(E->getExpr());
7450   }
7451   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7452     TempVersionRAII RAII(*Info.CurrentCall);
7453     // The initializer may not have been parsed yet, or might be erroneous.
7454     if (!E->getExpr())
7455       return Error(E);
7456     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7457     return StmtVisitorTy::Visit(E->getExpr());
7458   }
7459 
7460   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7461     FullExpressionRAII Scope(Info);
7462     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7463   }
7464 
7465   // Temporaries are registered when created, so we don't care about
7466   // CXXBindTemporaryExpr.
7467   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7468     return StmtVisitorTy::Visit(E->getSubExpr());
7469   }
7470 
7471   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7472     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7473     return static_cast<Derived*>(this)->VisitCastExpr(E);
7474   }
7475   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7476     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7477       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7478     return static_cast<Derived*>(this)->VisitCastExpr(E);
7479   }
7480   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7481     return static_cast<Derived*>(this)->VisitCastExpr(E);
7482   }
7483 
7484   bool VisitBinaryOperator(const BinaryOperator *E) {
7485     switch (E->getOpcode()) {
7486     default:
7487       return Error(E);
7488 
7489     case BO_Comma:
7490       VisitIgnoredValue(E->getLHS());
7491       return StmtVisitorTy::Visit(E->getRHS());
7492 
7493     case BO_PtrMemD:
7494     case BO_PtrMemI: {
7495       LValue Obj;
7496       if (!HandleMemberPointerAccess(Info, E, Obj))
7497         return false;
7498       APValue Result;
7499       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7500         return false;
7501       return DerivedSuccess(Result, E);
7502     }
7503     }
7504   }
7505 
7506   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7507     return StmtVisitorTy::Visit(E->getSemanticForm());
7508   }
7509 
7510   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7511     // Evaluate and cache the common expression. We treat it as a temporary,
7512     // even though it's not quite the same thing.
7513     LValue CommonLV;
7514     if (!Evaluate(Info.CurrentCall->createTemporary(
7515                       E->getOpaqueValue(),
7516                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7517                       ScopeKind::FullExpression, CommonLV),
7518                   Info, E->getCommon()))
7519       return false;
7520 
7521     return HandleConditionalOperator(E);
7522   }
7523 
7524   bool VisitConditionalOperator(const ConditionalOperator *E) {
7525     bool IsBcpCall = false;
7526     // If the condition (ignoring parens) is a __builtin_constant_p call,
7527     // the result is a constant expression if it can be folded without
7528     // side-effects. This is an important GNU extension. See GCC PR38377
7529     // for discussion.
7530     if (const CallExpr *CallCE =
7531           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7532       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7533         IsBcpCall = true;
7534 
7535     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7536     // constant expression; we can't check whether it's potentially foldable.
7537     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7538     // it would return 'false' in this mode.
7539     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7540       return false;
7541 
7542     FoldConstant Fold(Info, IsBcpCall);
7543     if (!HandleConditionalOperator(E)) {
7544       Fold.keepDiagnostics();
7545       return false;
7546     }
7547 
7548     return true;
7549   }
7550 
7551   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7552     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7553       return DerivedSuccess(*Value, E);
7554 
7555     const Expr *Source = E->getSourceExpr();
7556     if (!Source)
7557       return Error(E);
7558     if (Source == E) {
7559       assert(0 && "OpaqueValueExpr recursively refers to itself");
7560       return Error(E);
7561     }
7562     return StmtVisitorTy::Visit(Source);
7563   }
7564 
7565   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7566     for (const Expr *SemE : E->semantics()) {
7567       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7568         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7569         // result expression: there could be two different LValues that would
7570         // refer to the same object in that case, and we can't model that.
7571         if (SemE == E->getResultExpr())
7572           return Error(E);
7573 
7574         // Unique OVEs get evaluated if and when we encounter them when
7575         // emitting the rest of the semantic form, rather than eagerly.
7576         if (OVE->isUnique())
7577           continue;
7578 
7579         LValue LV;
7580         if (!Evaluate(Info.CurrentCall->createTemporary(
7581                           OVE, getStorageType(Info.Ctx, OVE),
7582                           ScopeKind::FullExpression, LV),
7583                       Info, OVE->getSourceExpr()))
7584           return false;
7585       } else if (SemE == E->getResultExpr()) {
7586         if (!StmtVisitorTy::Visit(SemE))
7587           return false;
7588       } else {
7589         if (!EvaluateIgnoredValue(Info, SemE))
7590           return false;
7591       }
7592     }
7593     return true;
7594   }
7595 
7596   bool VisitCallExpr(const CallExpr *E) {
7597     APValue Result;
7598     if (!handleCallExpr(E, Result, nullptr))
7599       return false;
7600     return DerivedSuccess(Result, E);
7601   }
7602 
7603   bool handleCallExpr(const CallExpr *E, APValue &Result,
7604                      const LValue *ResultSlot) {
7605     CallScopeRAII CallScope(Info);
7606 
7607     const Expr *Callee = E->getCallee()->IgnoreParens();
7608     QualType CalleeType = Callee->getType();
7609 
7610     const FunctionDecl *FD = nullptr;
7611     LValue *This = nullptr, ThisVal;
7612     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7613     bool HasQualifier = false;
7614 
7615     CallRef Call;
7616 
7617     // Extract function decl and 'this' pointer from the callee.
7618     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7619       const CXXMethodDecl *Member = nullptr;
7620       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7621         // Explicit bound member calls, such as x.f() or p->g();
7622         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7623           return false;
7624         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7625         if (!Member)
7626           return Error(Callee);
7627         This = &ThisVal;
7628         HasQualifier = ME->hasQualifier();
7629       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7630         // Indirect bound member calls ('.*' or '->*').
7631         const ValueDecl *D =
7632             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7633         if (!D)
7634           return false;
7635         Member = dyn_cast<CXXMethodDecl>(D);
7636         if (!Member)
7637           return Error(Callee);
7638         This = &ThisVal;
7639       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7640         if (!Info.getLangOpts().CPlusPlus20)
7641           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7642         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7643                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7644       } else
7645         return Error(Callee);
7646       FD = Member;
7647     } else if (CalleeType->isFunctionPointerType()) {
7648       LValue CalleeLV;
7649       if (!EvaluatePointer(Callee, CalleeLV, Info))
7650         return false;
7651 
7652       if (!CalleeLV.getLValueOffset().isZero())
7653         return Error(Callee);
7654       FD = dyn_cast_or_null<FunctionDecl>(
7655           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7656       if (!FD)
7657         return Error(Callee);
7658       // Don't call function pointers which have been cast to some other type.
7659       // Per DR (no number yet), the caller and callee can differ in noexcept.
7660       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7661         CalleeType->getPointeeType(), FD->getType())) {
7662         return Error(E);
7663       }
7664 
7665       // For an (overloaded) assignment expression, evaluate the RHS before the
7666       // LHS.
7667       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7668       if (OCE && OCE->isAssignmentOp()) {
7669         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7670         Call = Info.CurrentCall->createCall(FD);
7671         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7672                           Info, FD, /*RightToLeft=*/true))
7673           return false;
7674       }
7675 
7676       // Overloaded operator calls to member functions are represented as normal
7677       // calls with '*this' as the first argument.
7678       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7679       if (MD && !MD->isStatic()) {
7680         // FIXME: When selecting an implicit conversion for an overloaded
7681         // operator delete, we sometimes try to evaluate calls to conversion
7682         // operators without a 'this' parameter!
7683         if (Args.empty())
7684           return Error(E);
7685 
7686         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7687           return false;
7688         This = &ThisVal;
7689 
7690         // If this is syntactically a simple assignment using a trivial
7691         // assignment operator, start the lifetimes of union members as needed,
7692         // per C++20 [class.union]5.
7693         if (Info.getLangOpts().CPlusPlus20 && OCE &&
7694             OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7695             !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7696           return false;
7697 
7698         Args = Args.slice(1);
7699       } else if (MD && MD->isLambdaStaticInvoker()) {
7700         // Map the static invoker for the lambda back to the call operator.
7701         // Conveniently, we don't have to slice out the 'this' argument (as is
7702         // being done for the non-static case), since a static member function
7703         // doesn't have an implicit argument passed in.
7704         const CXXRecordDecl *ClosureClass = MD->getParent();
7705         assert(
7706             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7707             "Number of captures must be zero for conversion to function-ptr");
7708 
7709         const CXXMethodDecl *LambdaCallOp =
7710             ClosureClass->getLambdaCallOperator();
7711 
7712         // Set 'FD', the function that will be called below, to the call
7713         // operator.  If the closure object represents a generic lambda, find
7714         // the corresponding specialization of the call operator.
7715 
7716         if (ClosureClass->isGenericLambda()) {
7717           assert(MD->isFunctionTemplateSpecialization() &&
7718                  "A generic lambda's static-invoker function must be a "
7719                  "template specialization");
7720           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7721           FunctionTemplateDecl *CallOpTemplate =
7722               LambdaCallOp->getDescribedFunctionTemplate();
7723           void *InsertPos = nullptr;
7724           FunctionDecl *CorrespondingCallOpSpecialization =
7725               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7726           assert(CorrespondingCallOpSpecialization &&
7727                  "We must always have a function call operator specialization "
7728                  "that corresponds to our static invoker specialization");
7729           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7730         } else
7731           FD = LambdaCallOp;
7732       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7733         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7734             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7735           LValue Ptr;
7736           if (!HandleOperatorNewCall(Info, E, Ptr))
7737             return false;
7738           Ptr.moveInto(Result);
7739           return CallScope.destroy();
7740         } else {
7741           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7742         }
7743       }
7744     } else
7745       return Error(E);
7746 
7747     // Evaluate the arguments now if we've not already done so.
7748     if (!Call) {
7749       Call = Info.CurrentCall->createCall(FD);
7750       if (!EvaluateArgs(Args, Call, Info, FD))
7751         return false;
7752     }
7753 
7754     SmallVector<QualType, 4> CovariantAdjustmentPath;
7755     if (This) {
7756       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7757       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7758         // Perform virtual dispatch, if necessary.
7759         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7760                                    CovariantAdjustmentPath);
7761         if (!FD)
7762           return false;
7763       } else {
7764         // Check that the 'this' pointer points to an object of the right type.
7765         // FIXME: If this is an assignment operator call, we may need to change
7766         // the active union member before we check this.
7767         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7768           return false;
7769       }
7770     }
7771 
7772     // Destructor calls are different enough that they have their own codepath.
7773     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7774       assert(This && "no 'this' pointer for destructor call");
7775       return HandleDestruction(Info, E, *This,
7776                                Info.Ctx.getRecordType(DD->getParent())) &&
7777              CallScope.destroy();
7778     }
7779 
7780     const FunctionDecl *Definition = nullptr;
7781     Stmt *Body = FD->getBody(Definition);
7782 
7783     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7784         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7785                             Body, Info, Result, ResultSlot))
7786       return false;
7787 
7788     if (!CovariantAdjustmentPath.empty() &&
7789         !HandleCovariantReturnAdjustment(Info, E, Result,
7790                                          CovariantAdjustmentPath))
7791       return false;
7792 
7793     return CallScope.destroy();
7794   }
7795 
7796   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7797     return StmtVisitorTy::Visit(E->getInitializer());
7798   }
7799   bool VisitInitListExpr(const InitListExpr *E) {
7800     if (E->getNumInits() == 0)
7801       return DerivedZeroInitialization(E);
7802     if (E->getNumInits() == 1)
7803       return StmtVisitorTy::Visit(E->getInit(0));
7804     return Error(E);
7805   }
7806   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7807     return DerivedZeroInitialization(E);
7808   }
7809   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7810     return DerivedZeroInitialization(E);
7811   }
7812   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7813     return DerivedZeroInitialization(E);
7814   }
7815 
7816   /// A member expression where the object is a prvalue is itself a prvalue.
7817   bool VisitMemberExpr(const MemberExpr *E) {
7818     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7819            "missing temporary materialization conversion");
7820     assert(!E->isArrow() && "missing call to bound member function?");
7821 
7822     APValue Val;
7823     if (!Evaluate(Val, Info, E->getBase()))
7824       return false;
7825 
7826     QualType BaseTy = E->getBase()->getType();
7827 
7828     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7829     if (!FD) return Error(E);
7830     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7831     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7832            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7833 
7834     // Note: there is no lvalue base here. But this case should only ever
7835     // happen in C or in C++98, where we cannot be evaluating a constexpr
7836     // constructor, which is the only case the base matters.
7837     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7838     SubobjectDesignator Designator(BaseTy);
7839     Designator.addDeclUnchecked(FD);
7840 
7841     APValue Result;
7842     return extractSubobject(Info, E, Obj, Designator, Result) &&
7843            DerivedSuccess(Result, E);
7844   }
7845 
7846   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7847     APValue Val;
7848     if (!Evaluate(Val, Info, E->getBase()))
7849       return false;
7850 
7851     if (Val.isVector()) {
7852       SmallVector<uint32_t, 4> Indices;
7853       E->getEncodedElementAccess(Indices);
7854       if (Indices.size() == 1) {
7855         // Return scalar.
7856         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7857       } else {
7858         // Construct new APValue vector.
7859         SmallVector<APValue, 4> Elts;
7860         for (unsigned I = 0; I < Indices.size(); ++I) {
7861           Elts.push_back(Val.getVectorElt(Indices[I]));
7862         }
7863         APValue VecResult(Elts.data(), Indices.size());
7864         return DerivedSuccess(VecResult, E);
7865       }
7866     }
7867 
7868     return false;
7869   }
7870 
7871   bool VisitCastExpr(const CastExpr *E) {
7872     switch (E->getCastKind()) {
7873     default:
7874       break;
7875 
7876     case CK_AtomicToNonAtomic: {
7877       APValue AtomicVal;
7878       // This does not need to be done in place even for class/array types:
7879       // atomic-to-non-atomic conversion implies copying the object
7880       // representation.
7881       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7882         return false;
7883       return DerivedSuccess(AtomicVal, E);
7884     }
7885 
7886     case CK_NoOp:
7887     case CK_UserDefinedConversion:
7888       return StmtVisitorTy::Visit(E->getSubExpr());
7889 
7890     case CK_LValueToRValue: {
7891       LValue LVal;
7892       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7893         return false;
7894       APValue RVal;
7895       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7896       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7897                                           LVal, RVal))
7898         return false;
7899       return DerivedSuccess(RVal, E);
7900     }
7901     case CK_LValueToRValueBitCast: {
7902       APValue DestValue, SourceValue;
7903       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7904         return false;
7905       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7906         return false;
7907       return DerivedSuccess(DestValue, E);
7908     }
7909 
7910     case CK_AddressSpaceConversion: {
7911       APValue Value;
7912       if (!Evaluate(Value, Info, E->getSubExpr()))
7913         return false;
7914       return DerivedSuccess(Value, E);
7915     }
7916     }
7917 
7918     return Error(E);
7919   }
7920 
7921   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7922     return VisitUnaryPostIncDec(UO);
7923   }
7924   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7925     return VisitUnaryPostIncDec(UO);
7926   }
7927   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7928     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7929       return Error(UO);
7930 
7931     LValue LVal;
7932     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7933       return false;
7934     APValue RVal;
7935     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7936                       UO->isIncrementOp(), &RVal))
7937       return false;
7938     return DerivedSuccess(RVal, UO);
7939   }
7940 
7941   bool VisitStmtExpr(const StmtExpr *E) {
7942     // We will have checked the full-expressions inside the statement expression
7943     // when they were completed, and don't need to check them again now.
7944     llvm::SaveAndRestore<bool> NotCheckingForUB(
7945         Info.CheckingForUndefinedBehavior, false);
7946 
7947     const CompoundStmt *CS = E->getSubStmt();
7948     if (CS->body_empty())
7949       return true;
7950 
7951     BlockScopeRAII Scope(Info);
7952     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7953                                            BE = CS->body_end();
7954          /**/; ++BI) {
7955       if (BI + 1 == BE) {
7956         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7957         if (!FinalExpr) {
7958           Info.FFDiag((*BI)->getBeginLoc(),
7959                       diag::note_constexpr_stmt_expr_unsupported);
7960           return false;
7961         }
7962         return this->Visit(FinalExpr) && Scope.destroy();
7963       }
7964 
7965       APValue ReturnValue;
7966       StmtResult Result = { ReturnValue, nullptr };
7967       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7968       if (ESR != ESR_Succeeded) {
7969         // FIXME: If the statement-expression terminated due to 'return',
7970         // 'break', or 'continue', it would be nice to propagate that to
7971         // the outer statement evaluation rather than bailing out.
7972         if (ESR != ESR_Failed)
7973           Info.FFDiag((*BI)->getBeginLoc(),
7974                       diag::note_constexpr_stmt_expr_unsupported);
7975         return false;
7976       }
7977     }
7978 
7979     llvm_unreachable("Return from function from the loop above.");
7980   }
7981 
7982   /// Visit a value which is evaluated, but whose value is ignored.
7983   void VisitIgnoredValue(const Expr *E) {
7984     EvaluateIgnoredValue(Info, E);
7985   }
7986 
7987   /// Potentially visit a MemberExpr's base expression.
7988   void VisitIgnoredBaseExpression(const Expr *E) {
7989     // While MSVC doesn't evaluate the base expression, it does diagnose the
7990     // presence of side-effecting behavior.
7991     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7992       return;
7993     VisitIgnoredValue(E);
7994   }
7995 };
7996 
7997 } // namespace
7998 
7999 //===----------------------------------------------------------------------===//
8000 // Common base class for lvalue and temporary evaluation.
8001 //===----------------------------------------------------------------------===//
8002 namespace {
8003 template<class Derived>
8004 class LValueExprEvaluatorBase
8005   : public ExprEvaluatorBase<Derived> {
8006 protected:
8007   LValue &Result;
8008   bool InvalidBaseOK;
8009   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8010   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8011 
8012   bool Success(APValue::LValueBase B) {
8013     Result.set(B);
8014     return true;
8015   }
8016 
8017   bool evaluatePointer(const Expr *E, LValue &Result) {
8018     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8019   }
8020 
8021 public:
8022   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8023       : ExprEvaluatorBaseTy(Info), Result(Result),
8024         InvalidBaseOK(InvalidBaseOK) {}
8025 
8026   bool Success(const APValue &V, const Expr *E) {
8027     Result.setFrom(this->Info.Ctx, V);
8028     return true;
8029   }
8030 
8031   bool VisitMemberExpr(const MemberExpr *E) {
8032     // Handle non-static data members.
8033     QualType BaseTy;
8034     bool EvalOK;
8035     if (E->isArrow()) {
8036       EvalOK = evaluatePointer(E->getBase(), Result);
8037       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8038     } else if (E->getBase()->isPRValue()) {
8039       assert(E->getBase()->getType()->isRecordType());
8040       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8041       BaseTy = E->getBase()->getType();
8042     } else {
8043       EvalOK = this->Visit(E->getBase());
8044       BaseTy = E->getBase()->getType();
8045     }
8046     if (!EvalOK) {
8047       if (!InvalidBaseOK)
8048         return false;
8049       Result.setInvalid(E);
8050       return true;
8051     }
8052 
8053     const ValueDecl *MD = E->getMemberDecl();
8054     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8055       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8056              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8057       (void)BaseTy;
8058       if (!HandleLValueMember(this->Info, E, Result, FD))
8059         return false;
8060     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8061       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8062         return false;
8063     } else
8064       return this->Error(E);
8065 
8066     if (MD->getType()->isReferenceType()) {
8067       APValue RefValue;
8068       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8069                                           RefValue))
8070         return false;
8071       return Success(RefValue, E);
8072     }
8073     return true;
8074   }
8075 
8076   bool VisitBinaryOperator(const BinaryOperator *E) {
8077     switch (E->getOpcode()) {
8078     default:
8079       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8080 
8081     case BO_PtrMemD:
8082     case BO_PtrMemI:
8083       return HandleMemberPointerAccess(this->Info, E, Result);
8084     }
8085   }
8086 
8087   bool VisitCastExpr(const CastExpr *E) {
8088     switch (E->getCastKind()) {
8089     default:
8090       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8091 
8092     case CK_DerivedToBase:
8093     case CK_UncheckedDerivedToBase:
8094       if (!this->Visit(E->getSubExpr()))
8095         return false;
8096 
8097       // Now figure out the necessary offset to add to the base LV to get from
8098       // the derived class to the base class.
8099       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8100                                   Result);
8101     }
8102   }
8103 };
8104 }
8105 
8106 //===----------------------------------------------------------------------===//
8107 // LValue Evaluation
8108 //
8109 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8110 // function designators (in C), decl references to void objects (in C), and
8111 // temporaries (if building with -Wno-address-of-temporary).
8112 //
8113 // LValue evaluation produces values comprising a base expression of one of the
8114 // following types:
8115 // - Declarations
8116 //  * VarDecl
8117 //  * FunctionDecl
8118 // - Literals
8119 //  * CompoundLiteralExpr in C (and in global scope in C++)
8120 //  * StringLiteral
8121 //  * PredefinedExpr
8122 //  * ObjCStringLiteralExpr
8123 //  * ObjCEncodeExpr
8124 //  * AddrLabelExpr
8125 //  * BlockExpr
8126 //  * CallExpr for a MakeStringConstant builtin
8127 // - typeid(T) expressions, as TypeInfoLValues
8128 // - Locals and temporaries
8129 //  * MaterializeTemporaryExpr
8130 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8131 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8132 //    from the AST (FIXME).
8133 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8134 //    CallIndex, for a lifetime-extended temporary.
8135 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8136 //    immediate invocation.
8137 // plus an offset in bytes.
8138 //===----------------------------------------------------------------------===//
8139 namespace {
8140 class LValueExprEvaluator
8141   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8142 public:
8143   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8144     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8145 
8146   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8147   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8148 
8149   bool VisitCallExpr(const CallExpr *E);
8150   bool VisitDeclRefExpr(const DeclRefExpr *E);
8151   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8152   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8153   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8154   bool VisitMemberExpr(const MemberExpr *E);
8155   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8156   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8157   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8158   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8159   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8160   bool VisitUnaryDeref(const UnaryOperator *E);
8161   bool VisitUnaryReal(const UnaryOperator *E);
8162   bool VisitUnaryImag(const UnaryOperator *E);
8163   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8164     return VisitUnaryPreIncDec(UO);
8165   }
8166   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8167     return VisitUnaryPreIncDec(UO);
8168   }
8169   bool VisitBinAssign(const BinaryOperator *BO);
8170   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8171 
8172   bool VisitCastExpr(const CastExpr *E) {
8173     switch (E->getCastKind()) {
8174     default:
8175       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8176 
8177     case CK_LValueBitCast:
8178       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8179       if (!Visit(E->getSubExpr()))
8180         return false;
8181       Result.Designator.setInvalid();
8182       return true;
8183 
8184     case CK_BaseToDerived:
8185       if (!Visit(E->getSubExpr()))
8186         return false;
8187       return HandleBaseToDerivedCast(Info, E, Result);
8188 
8189     case CK_Dynamic:
8190       if (!Visit(E->getSubExpr()))
8191         return false;
8192       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8193     }
8194   }
8195 };
8196 } // end anonymous namespace
8197 
8198 /// Evaluate an expression as an lvalue. This can be legitimately called on
8199 /// expressions which are not glvalues, in three cases:
8200 ///  * function designators in C, and
8201 ///  * "extern void" objects
8202 ///  * @selector() expressions in Objective-C
8203 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8204                            bool InvalidBaseOK) {
8205   assert(!E->isValueDependent());
8206   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8207          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8208   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8209 }
8210 
8211 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8212   const NamedDecl *D = E->getDecl();
8213   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8214           UnnamedGlobalConstantDecl>(D))
8215     return Success(cast<ValueDecl>(D));
8216   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8217     return VisitVarDecl(E, VD);
8218   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8219     return Visit(BD->getBinding());
8220   return Error(E);
8221 }
8222 
8223 
8224 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8225 
8226   // If we are within a lambda's call operator, check whether the 'VD' referred
8227   // to within 'E' actually represents a lambda-capture that maps to a
8228   // data-member/field within the closure object, and if so, evaluate to the
8229   // field or what the field refers to.
8230   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8231       isa<DeclRefExpr>(E) &&
8232       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8233     // We don't always have a complete capture-map when checking or inferring if
8234     // the function call operator meets the requirements of a constexpr function
8235     // - but we don't need to evaluate the captures to determine constexprness
8236     // (dcl.constexpr C++17).
8237     if (Info.checkingPotentialConstantExpression())
8238       return false;
8239 
8240     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8241       // Start with 'Result' referring to the complete closure object...
8242       Result = *Info.CurrentCall->This;
8243       // ... then update it to refer to the field of the closure object
8244       // that represents the capture.
8245       if (!HandleLValueMember(Info, E, Result, FD))
8246         return false;
8247       // And if the field is of reference type, update 'Result' to refer to what
8248       // the field refers to.
8249       if (FD->getType()->isReferenceType()) {
8250         APValue RVal;
8251         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8252                                             RVal))
8253           return false;
8254         Result.setFrom(Info.Ctx, RVal);
8255       }
8256       return true;
8257     }
8258   }
8259 
8260   CallStackFrame *Frame = nullptr;
8261   unsigned Version = 0;
8262   if (VD->hasLocalStorage()) {
8263     // Only if a local variable was declared in the function currently being
8264     // evaluated, do we expect to be able to find its value in the current
8265     // frame. (Otherwise it was likely declared in an enclosing context and
8266     // could either have a valid evaluatable value (for e.g. a constexpr
8267     // variable) or be ill-formed (and trigger an appropriate evaluation
8268     // diagnostic)).
8269     CallStackFrame *CurrFrame = Info.CurrentCall;
8270     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8271       // Function parameters are stored in some caller's frame. (Usually the
8272       // immediate caller, but for an inherited constructor they may be more
8273       // distant.)
8274       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8275         if (CurrFrame->Arguments) {
8276           VD = CurrFrame->Arguments.getOrigParam(PVD);
8277           Frame =
8278               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8279           Version = CurrFrame->Arguments.Version;
8280         }
8281       } else {
8282         Frame = CurrFrame;
8283         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8284       }
8285     }
8286   }
8287 
8288   if (!VD->getType()->isReferenceType()) {
8289     if (Frame) {
8290       Result.set({VD, Frame->Index, Version});
8291       return true;
8292     }
8293     return Success(VD);
8294   }
8295 
8296   if (!Info.getLangOpts().CPlusPlus11) {
8297     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8298         << VD << VD->getType();
8299     Info.Note(VD->getLocation(), diag::note_declared_at);
8300   }
8301 
8302   APValue *V;
8303   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8304     return false;
8305   if (!V->hasValue()) {
8306     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8307     // adjust the diagnostic to say that.
8308     if (!Info.checkingPotentialConstantExpression())
8309       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8310     return false;
8311   }
8312   return Success(*V, E);
8313 }
8314 
8315 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8316   switch (E->getBuiltinCallee()) {
8317   case Builtin::BIas_const:
8318   case Builtin::BIforward:
8319   case Builtin::BImove:
8320   case Builtin::BImove_if_noexcept:
8321     if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8322       return Visit(E->getArg(0));
8323     break;
8324   }
8325 
8326   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8327 }
8328 
8329 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8330     const MaterializeTemporaryExpr *E) {
8331   // Walk through the expression to find the materialized temporary itself.
8332   SmallVector<const Expr *, 2> CommaLHSs;
8333   SmallVector<SubobjectAdjustment, 2> Adjustments;
8334   const Expr *Inner =
8335       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8336 
8337   // If we passed any comma operators, evaluate their LHSs.
8338   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8339     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8340       return false;
8341 
8342   // A materialized temporary with static storage duration can appear within the
8343   // result of a constant expression evaluation, so we need to preserve its
8344   // value for use outside this evaluation.
8345   APValue *Value;
8346   if (E->getStorageDuration() == SD_Static) {
8347     // FIXME: What about SD_Thread?
8348     Value = E->getOrCreateValue(true);
8349     *Value = APValue();
8350     Result.set(E);
8351   } else {
8352     Value = &Info.CurrentCall->createTemporary(
8353         E, E->getType(),
8354         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8355                                                      : ScopeKind::Block,
8356         Result);
8357   }
8358 
8359   QualType Type = Inner->getType();
8360 
8361   // Materialize the temporary itself.
8362   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8363     *Value = APValue();
8364     return false;
8365   }
8366 
8367   // Adjust our lvalue to refer to the desired subobject.
8368   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8369     --I;
8370     switch (Adjustments[I].Kind) {
8371     case SubobjectAdjustment::DerivedToBaseAdjustment:
8372       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8373                                 Type, Result))
8374         return false;
8375       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8376       break;
8377 
8378     case SubobjectAdjustment::FieldAdjustment:
8379       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8380         return false;
8381       Type = Adjustments[I].Field->getType();
8382       break;
8383 
8384     case SubobjectAdjustment::MemberPointerAdjustment:
8385       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8386                                      Adjustments[I].Ptr.RHS))
8387         return false;
8388       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8389       break;
8390     }
8391   }
8392 
8393   return true;
8394 }
8395 
8396 bool
8397 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8398   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8399          "lvalue compound literal in c++?");
8400   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8401   // only see this when folding in C, so there's no standard to follow here.
8402   return Success(E);
8403 }
8404 
8405 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8406   TypeInfoLValue TypeInfo;
8407 
8408   if (!E->isPotentiallyEvaluated()) {
8409     if (E->isTypeOperand())
8410       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8411     else
8412       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8413   } else {
8414     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8415       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8416         << E->getExprOperand()->getType()
8417         << E->getExprOperand()->getSourceRange();
8418     }
8419 
8420     if (!Visit(E->getExprOperand()))
8421       return false;
8422 
8423     Optional<DynamicType> DynType =
8424         ComputeDynamicType(Info, E, Result, AK_TypeId);
8425     if (!DynType)
8426       return false;
8427 
8428     TypeInfo =
8429         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8430   }
8431 
8432   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8433 }
8434 
8435 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8436   return Success(E->getGuidDecl());
8437 }
8438 
8439 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8440   // Handle static data members.
8441   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8442     VisitIgnoredBaseExpression(E->getBase());
8443     return VisitVarDecl(E, VD);
8444   }
8445 
8446   // Handle static member functions.
8447   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8448     if (MD->isStatic()) {
8449       VisitIgnoredBaseExpression(E->getBase());
8450       return Success(MD);
8451     }
8452   }
8453 
8454   // Handle non-static data members.
8455   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8456 }
8457 
8458 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8459   // FIXME: Deal with vectors as array subscript bases.
8460   if (E->getBase()->getType()->isVectorType() ||
8461       E->getBase()->getType()->isVLSTBuiltinType())
8462     return Error(E);
8463 
8464   APSInt Index;
8465   bool Success = true;
8466 
8467   // C++17's rules require us to evaluate the LHS first, regardless of which
8468   // side is the base.
8469   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8470     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8471                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8472       if (!Info.noteFailure())
8473         return false;
8474       Success = false;
8475     }
8476   }
8477 
8478   return Success &&
8479          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8480 }
8481 
8482 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8483   return evaluatePointer(E->getSubExpr(), Result);
8484 }
8485 
8486 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8487   if (!Visit(E->getSubExpr()))
8488     return false;
8489   // __real is a no-op on scalar lvalues.
8490   if (E->getSubExpr()->getType()->isAnyComplexType())
8491     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8492   return true;
8493 }
8494 
8495 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8496   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8497          "lvalue __imag__ on scalar?");
8498   if (!Visit(E->getSubExpr()))
8499     return false;
8500   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8501   return true;
8502 }
8503 
8504 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8505   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8506     return Error(UO);
8507 
8508   if (!this->Visit(UO->getSubExpr()))
8509     return false;
8510 
8511   return handleIncDec(
8512       this->Info, UO, Result, UO->getSubExpr()->getType(),
8513       UO->isIncrementOp(), nullptr);
8514 }
8515 
8516 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8517     const CompoundAssignOperator *CAO) {
8518   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8519     return Error(CAO);
8520 
8521   bool Success = true;
8522 
8523   // C++17 onwards require that we evaluate the RHS first.
8524   APValue RHS;
8525   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8526     if (!Info.noteFailure())
8527       return false;
8528     Success = false;
8529   }
8530 
8531   // The overall lvalue result is the result of evaluating the LHS.
8532   if (!this->Visit(CAO->getLHS()) || !Success)
8533     return false;
8534 
8535   return handleCompoundAssignment(
8536       this->Info, CAO,
8537       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8538       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8539 }
8540 
8541 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8542   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8543     return Error(E);
8544 
8545   bool Success = true;
8546 
8547   // C++17 onwards require that we evaluate the RHS first.
8548   APValue NewVal;
8549   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8550     if (!Info.noteFailure())
8551       return false;
8552     Success = false;
8553   }
8554 
8555   if (!this->Visit(E->getLHS()) || !Success)
8556     return false;
8557 
8558   if (Info.getLangOpts().CPlusPlus20 &&
8559       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8560     return false;
8561 
8562   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8563                           NewVal);
8564 }
8565 
8566 //===----------------------------------------------------------------------===//
8567 // Pointer Evaluation
8568 //===----------------------------------------------------------------------===//
8569 
8570 /// Attempts to compute the number of bytes available at the pointer
8571 /// returned by a function with the alloc_size attribute. Returns true if we
8572 /// were successful. Places an unsigned number into `Result`.
8573 ///
8574 /// This expects the given CallExpr to be a call to a function with an
8575 /// alloc_size attribute.
8576 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8577                                             const CallExpr *Call,
8578                                             llvm::APInt &Result) {
8579   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8580 
8581   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8582   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8583   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8584   if (Call->getNumArgs() <= SizeArgNo)
8585     return false;
8586 
8587   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8588     Expr::EvalResult ExprResult;
8589     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8590       return false;
8591     Into = ExprResult.Val.getInt();
8592     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8593       return false;
8594     Into = Into.zext(BitsInSizeT);
8595     return true;
8596   };
8597 
8598   APSInt SizeOfElem;
8599   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8600     return false;
8601 
8602   if (!AllocSize->getNumElemsParam().isValid()) {
8603     Result = std::move(SizeOfElem);
8604     return true;
8605   }
8606 
8607   APSInt NumberOfElems;
8608   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8609   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8610     return false;
8611 
8612   bool Overflow;
8613   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8614   if (Overflow)
8615     return false;
8616 
8617   Result = std::move(BytesAvailable);
8618   return true;
8619 }
8620 
8621 /// Convenience function. LVal's base must be a call to an alloc_size
8622 /// function.
8623 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8624                                             const LValue &LVal,
8625                                             llvm::APInt &Result) {
8626   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8627          "Can't get the size of a non alloc_size function");
8628   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8629   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8630   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8631 }
8632 
8633 /// Attempts to evaluate the given LValueBase as the result of a call to
8634 /// a function with the alloc_size attribute. If it was possible to do so, this
8635 /// function will return true, make Result's Base point to said function call,
8636 /// and mark Result's Base as invalid.
8637 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8638                                       LValue &Result) {
8639   if (Base.isNull())
8640     return false;
8641 
8642   // Because we do no form of static analysis, we only support const variables.
8643   //
8644   // Additionally, we can't support parameters, nor can we support static
8645   // variables (in the latter case, use-before-assign isn't UB; in the former,
8646   // we have no clue what they'll be assigned to).
8647   const auto *VD =
8648       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8649   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8650     return false;
8651 
8652   const Expr *Init = VD->getAnyInitializer();
8653   if (!Init || Init->getType().isNull())
8654     return false;
8655 
8656   const Expr *E = Init->IgnoreParens();
8657   if (!tryUnwrapAllocSizeCall(E))
8658     return false;
8659 
8660   // Store E instead of E unwrapped so that the type of the LValue's base is
8661   // what the user wanted.
8662   Result.setInvalid(E);
8663 
8664   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8665   Result.addUnsizedArray(Info, E, Pointee);
8666   return true;
8667 }
8668 
8669 namespace {
8670 class PointerExprEvaluator
8671   : public ExprEvaluatorBase<PointerExprEvaluator> {
8672   LValue &Result;
8673   bool InvalidBaseOK;
8674 
8675   bool Success(const Expr *E) {
8676     Result.set(E);
8677     return true;
8678   }
8679 
8680   bool evaluateLValue(const Expr *E, LValue &Result) {
8681     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8682   }
8683 
8684   bool evaluatePointer(const Expr *E, LValue &Result) {
8685     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8686   }
8687 
8688   bool visitNonBuiltinCallExpr(const CallExpr *E);
8689 public:
8690 
8691   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8692       : ExprEvaluatorBaseTy(info), Result(Result),
8693         InvalidBaseOK(InvalidBaseOK) {}
8694 
8695   bool Success(const APValue &V, const Expr *E) {
8696     Result.setFrom(Info.Ctx, V);
8697     return true;
8698   }
8699   bool ZeroInitialization(const Expr *E) {
8700     Result.setNull(Info.Ctx, E->getType());
8701     return true;
8702   }
8703 
8704   bool VisitBinaryOperator(const BinaryOperator *E);
8705   bool VisitCastExpr(const CastExpr* E);
8706   bool VisitUnaryAddrOf(const UnaryOperator *E);
8707   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8708       { return Success(E); }
8709   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8710     if (E->isExpressibleAsConstantInitializer())
8711       return Success(E);
8712     if (Info.noteFailure())
8713       EvaluateIgnoredValue(Info, E->getSubExpr());
8714     return Error(E);
8715   }
8716   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8717       { return Success(E); }
8718   bool VisitCallExpr(const CallExpr *E);
8719   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8720   bool VisitBlockExpr(const BlockExpr *E) {
8721     if (!E->getBlockDecl()->hasCaptures())
8722       return Success(E);
8723     return Error(E);
8724   }
8725   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8726     // Can't look at 'this' when checking a potential constant expression.
8727     if (Info.checkingPotentialConstantExpression())
8728       return false;
8729     if (!Info.CurrentCall->This) {
8730       if (Info.getLangOpts().CPlusPlus11)
8731         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8732       else
8733         Info.FFDiag(E);
8734       return false;
8735     }
8736     Result = *Info.CurrentCall->This;
8737     // If we are inside a lambda's call operator, the 'this' expression refers
8738     // to the enclosing '*this' object (either by value or reference) which is
8739     // either copied into the closure object's field that represents the '*this'
8740     // or refers to '*this'.
8741     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8742       // Ensure we actually have captured 'this'. (an error will have
8743       // been previously reported if not).
8744       if (!Info.CurrentCall->LambdaThisCaptureField)
8745         return false;
8746 
8747       // Update 'Result' to refer to the data member/field of the closure object
8748       // that represents the '*this' capture.
8749       if (!HandleLValueMember(Info, E, Result,
8750                              Info.CurrentCall->LambdaThisCaptureField))
8751         return false;
8752       // If we captured '*this' by reference, replace the field with its referent.
8753       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8754               ->isPointerType()) {
8755         APValue RVal;
8756         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8757                                             RVal))
8758           return false;
8759 
8760         Result.setFrom(Info.Ctx, RVal);
8761       }
8762     }
8763     return true;
8764   }
8765 
8766   bool VisitCXXNewExpr(const CXXNewExpr *E);
8767 
8768   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8769     assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8770     APValue LValResult = E->EvaluateInContext(
8771         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8772     Result.setFrom(Info.Ctx, LValResult);
8773     return true;
8774   }
8775 
8776   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8777     std::string ResultStr = E->ComputeName(Info.Ctx);
8778 
8779     QualType CharTy = Info.Ctx.CharTy.withConst();
8780     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8781                ResultStr.size() + 1);
8782     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8783                                                      ArrayType::Normal, 0);
8784 
8785     StringLiteral *SL =
8786         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8787                               /*Pascal*/ false, ArrayTy, E->getLocation());
8788 
8789     evaluateLValue(SL, Result);
8790     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8791     return true;
8792   }
8793 
8794   // FIXME: Missing: @protocol, @selector
8795 };
8796 } // end anonymous namespace
8797 
8798 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8799                             bool InvalidBaseOK) {
8800   assert(!E->isValueDependent());
8801   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8802   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8803 }
8804 
8805 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8806   if (E->getOpcode() != BO_Add &&
8807       E->getOpcode() != BO_Sub)
8808     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8809 
8810   const Expr *PExp = E->getLHS();
8811   const Expr *IExp = E->getRHS();
8812   if (IExp->getType()->isPointerType())
8813     std::swap(PExp, IExp);
8814 
8815   bool EvalPtrOK = evaluatePointer(PExp, Result);
8816   if (!EvalPtrOK && !Info.noteFailure())
8817     return false;
8818 
8819   llvm::APSInt Offset;
8820   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8821     return false;
8822 
8823   if (E->getOpcode() == BO_Sub)
8824     negateAsSigned(Offset);
8825 
8826   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8827   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8828 }
8829 
8830 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8831   return evaluateLValue(E->getSubExpr(), Result);
8832 }
8833 
8834 // Is the provided decl 'std::source_location::current'?
8835 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8836   if (!FD)
8837     return false;
8838   const IdentifierInfo *FnII = FD->getIdentifier();
8839   if (!FnII || !FnII->isStr("current"))
8840     return false;
8841 
8842   const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8843   if (!RD)
8844     return false;
8845 
8846   const IdentifierInfo *ClassII = RD->getIdentifier();
8847   return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8848 }
8849 
8850 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8851   const Expr *SubExpr = E->getSubExpr();
8852 
8853   switch (E->getCastKind()) {
8854   default:
8855     break;
8856   case CK_BitCast:
8857   case CK_CPointerToObjCPointerCast:
8858   case CK_BlockPointerToObjCPointerCast:
8859   case CK_AnyPointerToBlockPointerCast:
8860   case CK_AddressSpaceConversion:
8861     if (!Visit(SubExpr))
8862       return false;
8863     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8864     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8865     // also static_casts, but we disallow them as a resolution to DR1312.
8866     if (!E->getType()->isVoidPointerType()) {
8867       // In some circumstances, we permit casting from void* to cv1 T*, when the
8868       // actual pointee object is actually a cv2 T.
8869       bool VoidPtrCastMaybeOK =
8870           !Result.InvalidBase && !Result.Designator.Invalid &&
8871           !Result.IsNullPtr &&
8872           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8873                                           E->getType()->getPointeeType());
8874       // 1. We'll allow it in std::allocator::allocate, and anything which that
8875       //    calls.
8876       // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8877       //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8878       //    We'll allow it in the body of std::source_location::current.  GCC's
8879       //    implementation had a parameter of type `void*`, and casts from
8880       //    that back to `const __impl*` in its body.
8881       if (VoidPtrCastMaybeOK &&
8882           (Info.getStdAllocatorCaller("allocate") ||
8883            IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8884         // Permitted.
8885       } else {
8886         Result.Designator.setInvalid();
8887         if (SubExpr->getType()->isVoidPointerType())
8888           CCEDiag(E, diag::note_constexpr_invalid_cast)
8889             << 3 << SubExpr->getType();
8890         else
8891           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8892       }
8893     }
8894     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8895       ZeroInitialization(E);
8896     return true;
8897 
8898   case CK_DerivedToBase:
8899   case CK_UncheckedDerivedToBase:
8900     if (!evaluatePointer(E->getSubExpr(), Result))
8901       return false;
8902     if (!Result.Base && Result.Offset.isZero())
8903       return true;
8904 
8905     // Now figure out the necessary offset to add to the base LV to get from
8906     // the derived class to the base class.
8907     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8908                                   castAs<PointerType>()->getPointeeType(),
8909                                 Result);
8910 
8911   case CK_BaseToDerived:
8912     if (!Visit(E->getSubExpr()))
8913       return false;
8914     if (!Result.Base && Result.Offset.isZero())
8915       return true;
8916     return HandleBaseToDerivedCast(Info, E, Result);
8917 
8918   case CK_Dynamic:
8919     if (!Visit(E->getSubExpr()))
8920       return false;
8921     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8922 
8923   case CK_NullToPointer:
8924     VisitIgnoredValue(E->getSubExpr());
8925     return ZeroInitialization(E);
8926 
8927   case CK_IntegralToPointer: {
8928     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8929 
8930     APValue Value;
8931     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8932       break;
8933 
8934     if (Value.isInt()) {
8935       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8936       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8937       Result.Base = (Expr*)nullptr;
8938       Result.InvalidBase = false;
8939       Result.Offset = CharUnits::fromQuantity(N);
8940       Result.Designator.setInvalid();
8941       Result.IsNullPtr = false;
8942       return true;
8943     } else {
8944       // Cast is of an lvalue, no need to change value.
8945       Result.setFrom(Info.Ctx, Value);
8946       return true;
8947     }
8948   }
8949 
8950   case CK_ArrayToPointerDecay: {
8951     if (SubExpr->isGLValue()) {
8952       if (!evaluateLValue(SubExpr, Result))
8953         return false;
8954     } else {
8955       APValue &Value = Info.CurrentCall->createTemporary(
8956           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8957       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8958         return false;
8959     }
8960     // The result is a pointer to the first element of the array.
8961     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8962     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8963       Result.addArray(Info, E, CAT);
8964     else
8965       Result.addUnsizedArray(Info, E, AT->getElementType());
8966     return true;
8967   }
8968 
8969   case CK_FunctionToPointerDecay:
8970     return evaluateLValue(SubExpr, Result);
8971 
8972   case CK_LValueToRValue: {
8973     LValue LVal;
8974     if (!evaluateLValue(E->getSubExpr(), LVal))
8975       return false;
8976 
8977     APValue RVal;
8978     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8979     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8980                                         LVal, RVal))
8981       return InvalidBaseOK &&
8982              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8983     return Success(RVal, E);
8984   }
8985   }
8986 
8987   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8988 }
8989 
8990 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8991                                 UnaryExprOrTypeTrait ExprKind) {
8992   // C++ [expr.alignof]p3:
8993   //     When alignof is applied to a reference type, the result is the
8994   //     alignment of the referenced type.
8995   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8996     T = Ref->getPointeeType();
8997 
8998   if (T.getQualifiers().hasUnaligned())
8999     return CharUnits::One();
9000 
9001   const bool AlignOfReturnsPreferred =
9002       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9003 
9004   // __alignof is defined to return the preferred alignment.
9005   // Before 8, clang returned the preferred alignment for alignof and _Alignof
9006   // as well.
9007   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9008     return Info.Ctx.toCharUnitsFromBits(
9009       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9010   // alignof and _Alignof are defined to return the ABI alignment.
9011   else if (ExprKind == UETT_AlignOf)
9012     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9013   else
9014     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9015 }
9016 
9017 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9018                                 UnaryExprOrTypeTrait ExprKind) {
9019   E = E->IgnoreParens();
9020 
9021   // The kinds of expressions that we have special-case logic here for
9022   // should be kept up to date with the special checks for those
9023   // expressions in Sema.
9024 
9025   // alignof decl is always accepted, even if it doesn't make sense: we default
9026   // to 1 in those cases.
9027   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9028     return Info.Ctx.getDeclAlign(DRE->getDecl(),
9029                                  /*RefAsPointee*/true);
9030 
9031   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9032     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9033                                  /*RefAsPointee*/true);
9034 
9035   return GetAlignOfType(Info, E->getType(), ExprKind);
9036 }
9037 
9038 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9039   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9040     return Info.Ctx.getDeclAlign(VD);
9041   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9042     return GetAlignOfExpr(Info, E, UETT_AlignOf);
9043   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9044 }
9045 
9046 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9047 /// __builtin_is_aligned and __builtin_assume_aligned.
9048 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9049                                  EvalInfo &Info, APSInt &Alignment) {
9050   if (!EvaluateInteger(E, Alignment, Info))
9051     return false;
9052   if (Alignment < 0 || !Alignment.isPowerOf2()) {
9053     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9054     return false;
9055   }
9056   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9057   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9058   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9059     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9060         << MaxValue << ForType << Alignment;
9061     return false;
9062   }
9063   // Ensure both alignment and source value have the same bit width so that we
9064   // don't assert when computing the resulting value.
9065   APSInt ExtAlignment =
9066       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9067   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9068          "Alignment should not be changed by ext/trunc");
9069   Alignment = ExtAlignment;
9070   assert(Alignment.getBitWidth() == SrcWidth);
9071   return true;
9072 }
9073 
9074 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9075 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9076   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9077     return true;
9078 
9079   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9080     return false;
9081 
9082   Result.setInvalid(E);
9083   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9084   Result.addUnsizedArray(Info, E, PointeeTy);
9085   return true;
9086 }
9087 
9088 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9089   if (IsConstantCall(E))
9090     return Success(E);
9091 
9092   if (unsigned BuiltinOp = E->getBuiltinCallee())
9093     return VisitBuiltinCallExpr(E, BuiltinOp);
9094 
9095   return visitNonBuiltinCallExpr(E);
9096 }
9097 
9098 // Determine if T is a character type for which we guarantee that
9099 // sizeof(T) == 1.
9100 static bool isOneByteCharacterType(QualType T) {
9101   return T->isCharType() || T->isChar8Type();
9102 }
9103 
9104 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9105                                                 unsigned BuiltinOp) {
9106   switch (BuiltinOp) {
9107   case Builtin::BIaddressof:
9108   case Builtin::BI__addressof:
9109   case Builtin::BI__builtin_addressof:
9110     return evaluateLValue(E->getArg(0), Result);
9111   case Builtin::BI__builtin_assume_aligned: {
9112     // We need to be very careful here because: if the pointer does not have the
9113     // asserted alignment, then the behavior is undefined, and undefined
9114     // behavior is non-constant.
9115     if (!evaluatePointer(E->getArg(0), Result))
9116       return false;
9117 
9118     LValue OffsetResult(Result);
9119     APSInt Alignment;
9120     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9121                               Alignment))
9122       return false;
9123     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9124 
9125     if (E->getNumArgs() > 2) {
9126       APSInt Offset;
9127       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9128         return false;
9129 
9130       int64_t AdditionalOffset = -Offset.getZExtValue();
9131       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9132     }
9133 
9134     // If there is a base object, then it must have the correct alignment.
9135     if (OffsetResult.Base) {
9136       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9137 
9138       if (BaseAlignment < Align) {
9139         Result.Designator.setInvalid();
9140         // FIXME: Add support to Diagnostic for long / long long.
9141         CCEDiag(E->getArg(0),
9142                 diag::note_constexpr_baa_insufficient_alignment) << 0
9143           << (unsigned)BaseAlignment.getQuantity()
9144           << (unsigned)Align.getQuantity();
9145         return false;
9146       }
9147     }
9148 
9149     // The offset must also have the correct alignment.
9150     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9151       Result.Designator.setInvalid();
9152 
9153       (OffsetResult.Base
9154            ? CCEDiag(E->getArg(0),
9155                      diag::note_constexpr_baa_insufficient_alignment) << 1
9156            : CCEDiag(E->getArg(0),
9157                      diag::note_constexpr_baa_value_insufficient_alignment))
9158         << (int)OffsetResult.Offset.getQuantity()
9159         << (unsigned)Align.getQuantity();
9160       return false;
9161     }
9162 
9163     return true;
9164   }
9165   case Builtin::BI__builtin_align_up:
9166   case Builtin::BI__builtin_align_down: {
9167     if (!evaluatePointer(E->getArg(0), Result))
9168       return false;
9169     APSInt Alignment;
9170     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9171                               Alignment))
9172       return false;
9173     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9174     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9175     // For align_up/align_down, we can return the same value if the alignment
9176     // is known to be greater or equal to the requested value.
9177     if (PtrAlign.getQuantity() >= Alignment)
9178       return true;
9179 
9180     // The alignment could be greater than the minimum at run-time, so we cannot
9181     // infer much about the resulting pointer value. One case is possible:
9182     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9183     // can infer the correct index if the requested alignment is smaller than
9184     // the base alignment so we can perform the computation on the offset.
9185     if (BaseAlignment.getQuantity() >= Alignment) {
9186       assert(Alignment.getBitWidth() <= 64 &&
9187              "Cannot handle > 64-bit address-space");
9188       uint64_t Alignment64 = Alignment.getZExtValue();
9189       CharUnits NewOffset = CharUnits::fromQuantity(
9190           BuiltinOp == Builtin::BI__builtin_align_down
9191               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9192               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9193       Result.adjustOffset(NewOffset - Result.Offset);
9194       // TODO: diagnose out-of-bounds values/only allow for arrays?
9195       return true;
9196     }
9197     // Otherwise, we cannot constant-evaluate the result.
9198     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9199         << Alignment;
9200     return false;
9201   }
9202   case Builtin::BI__builtin_operator_new:
9203     return HandleOperatorNewCall(Info, E, Result);
9204   case Builtin::BI__builtin_launder:
9205     return evaluatePointer(E->getArg(0), Result);
9206   case Builtin::BIstrchr:
9207   case Builtin::BIwcschr:
9208   case Builtin::BImemchr:
9209   case Builtin::BIwmemchr:
9210     if (Info.getLangOpts().CPlusPlus11)
9211       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9212         << /*isConstexpr*/0 << /*isConstructor*/0
9213         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9214     else
9215       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9216     LLVM_FALLTHROUGH;
9217   case Builtin::BI__builtin_strchr:
9218   case Builtin::BI__builtin_wcschr:
9219   case Builtin::BI__builtin_memchr:
9220   case Builtin::BI__builtin_char_memchr:
9221   case Builtin::BI__builtin_wmemchr: {
9222     if (!Visit(E->getArg(0)))
9223       return false;
9224     APSInt Desired;
9225     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9226       return false;
9227     uint64_t MaxLength = uint64_t(-1);
9228     if (BuiltinOp != Builtin::BIstrchr &&
9229         BuiltinOp != Builtin::BIwcschr &&
9230         BuiltinOp != Builtin::BI__builtin_strchr &&
9231         BuiltinOp != Builtin::BI__builtin_wcschr) {
9232       APSInt N;
9233       if (!EvaluateInteger(E->getArg(2), N, Info))
9234         return false;
9235       MaxLength = N.getExtValue();
9236     }
9237     // We cannot find the value if there are no candidates to match against.
9238     if (MaxLength == 0u)
9239       return ZeroInitialization(E);
9240     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9241         Result.Designator.Invalid)
9242       return false;
9243     QualType CharTy = Result.Designator.getType(Info.Ctx);
9244     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9245                      BuiltinOp == Builtin::BI__builtin_memchr;
9246     assert(IsRawByte ||
9247            Info.Ctx.hasSameUnqualifiedType(
9248                CharTy, E->getArg(0)->getType()->getPointeeType()));
9249     // Pointers to const void may point to objects of incomplete type.
9250     if (IsRawByte && CharTy->isIncompleteType()) {
9251       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9252       return false;
9253     }
9254     // Give up on byte-oriented matching against multibyte elements.
9255     // FIXME: We can compare the bytes in the correct order.
9256     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9257       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9258           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9259           << CharTy;
9260       return false;
9261     }
9262     // Figure out what value we're actually looking for (after converting to
9263     // the corresponding unsigned type if necessary).
9264     uint64_t DesiredVal;
9265     bool StopAtNull = false;
9266     switch (BuiltinOp) {
9267     case Builtin::BIstrchr:
9268     case Builtin::BI__builtin_strchr:
9269       // strchr compares directly to the passed integer, and therefore
9270       // always fails if given an int that is not a char.
9271       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9272                                                   E->getArg(1)->getType(),
9273                                                   Desired),
9274                                Desired))
9275         return ZeroInitialization(E);
9276       StopAtNull = true;
9277       LLVM_FALLTHROUGH;
9278     case Builtin::BImemchr:
9279     case Builtin::BI__builtin_memchr:
9280     case Builtin::BI__builtin_char_memchr:
9281       // memchr compares by converting both sides to unsigned char. That's also
9282       // correct for strchr if we get this far (to cope with plain char being
9283       // unsigned in the strchr case).
9284       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9285       break;
9286 
9287     case Builtin::BIwcschr:
9288     case Builtin::BI__builtin_wcschr:
9289       StopAtNull = true;
9290       LLVM_FALLTHROUGH;
9291     case Builtin::BIwmemchr:
9292     case Builtin::BI__builtin_wmemchr:
9293       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9294       DesiredVal = Desired.getZExtValue();
9295       break;
9296     }
9297 
9298     for (; MaxLength; --MaxLength) {
9299       APValue Char;
9300       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9301           !Char.isInt())
9302         return false;
9303       if (Char.getInt().getZExtValue() == DesiredVal)
9304         return true;
9305       if (StopAtNull && !Char.getInt())
9306         break;
9307       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9308         return false;
9309     }
9310     // Not found: return nullptr.
9311     return ZeroInitialization(E);
9312   }
9313 
9314   case Builtin::BImemcpy:
9315   case Builtin::BImemmove:
9316   case Builtin::BIwmemcpy:
9317   case Builtin::BIwmemmove:
9318     if (Info.getLangOpts().CPlusPlus11)
9319       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9320         << /*isConstexpr*/0 << /*isConstructor*/0
9321         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9322     else
9323       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9324     LLVM_FALLTHROUGH;
9325   case Builtin::BI__builtin_memcpy:
9326   case Builtin::BI__builtin_memmove:
9327   case Builtin::BI__builtin_wmemcpy:
9328   case Builtin::BI__builtin_wmemmove: {
9329     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9330                  BuiltinOp == Builtin::BIwmemmove ||
9331                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9332                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9333     bool Move = BuiltinOp == Builtin::BImemmove ||
9334                 BuiltinOp == Builtin::BIwmemmove ||
9335                 BuiltinOp == Builtin::BI__builtin_memmove ||
9336                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9337 
9338     // The result of mem* is the first argument.
9339     if (!Visit(E->getArg(0)))
9340       return false;
9341     LValue Dest = Result;
9342 
9343     LValue Src;
9344     if (!EvaluatePointer(E->getArg(1), Src, Info))
9345       return false;
9346 
9347     APSInt N;
9348     if (!EvaluateInteger(E->getArg(2), N, Info))
9349       return false;
9350     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9351 
9352     // If the size is zero, we treat this as always being a valid no-op.
9353     // (Even if one of the src and dest pointers is null.)
9354     if (!N)
9355       return true;
9356 
9357     // Otherwise, if either of the operands is null, we can't proceed. Don't
9358     // try to determine the type of the copied objects, because there aren't
9359     // any.
9360     if (!Src.Base || !Dest.Base) {
9361       APValue Val;
9362       (!Src.Base ? Src : Dest).moveInto(Val);
9363       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9364           << Move << WChar << !!Src.Base
9365           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9366       return false;
9367     }
9368     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9369       return false;
9370 
9371     // We require that Src and Dest are both pointers to arrays of
9372     // trivially-copyable type. (For the wide version, the designator will be
9373     // invalid if the designated object is not a wchar_t.)
9374     QualType T = Dest.Designator.getType(Info.Ctx);
9375     QualType SrcT = Src.Designator.getType(Info.Ctx);
9376     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9377       // FIXME: Consider using our bit_cast implementation to support this.
9378       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9379       return false;
9380     }
9381     if (T->isIncompleteType()) {
9382       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9383       return false;
9384     }
9385     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9386       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9387       return false;
9388     }
9389 
9390     // Figure out how many T's we're copying.
9391     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9392     if (!WChar) {
9393       uint64_t Remainder;
9394       llvm::APInt OrigN = N;
9395       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9396       if (Remainder) {
9397         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9398             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9399             << (unsigned)TSize;
9400         return false;
9401       }
9402     }
9403 
9404     // Check that the copying will remain within the arrays, just so that we
9405     // can give a more meaningful diagnostic. This implicitly also checks that
9406     // N fits into 64 bits.
9407     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9408     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9409     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9410       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9411           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9412           << toString(N, 10, /*Signed*/false);
9413       return false;
9414     }
9415     uint64_t NElems = N.getZExtValue();
9416     uint64_t NBytes = NElems * TSize;
9417 
9418     // Check for overlap.
9419     int Direction = 1;
9420     if (HasSameBase(Src, Dest)) {
9421       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9422       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9423       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9424         // Dest is inside the source region.
9425         if (!Move) {
9426           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9427           return false;
9428         }
9429         // For memmove and friends, copy backwards.
9430         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9431             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9432           return false;
9433         Direction = -1;
9434       } else if (!Move && SrcOffset >= DestOffset &&
9435                  SrcOffset - DestOffset < NBytes) {
9436         // Src is inside the destination region for memcpy: invalid.
9437         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9438         return false;
9439       }
9440     }
9441 
9442     while (true) {
9443       APValue Val;
9444       // FIXME: Set WantObjectRepresentation to true if we're copying a
9445       // char-like type?
9446       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9447           !handleAssignment(Info, E, Dest, T, Val))
9448         return false;
9449       // Do not iterate past the last element; if we're copying backwards, that
9450       // might take us off the start of the array.
9451       if (--NElems == 0)
9452         return true;
9453       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9454           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9455         return false;
9456     }
9457   }
9458 
9459   default:
9460     break;
9461   }
9462 
9463   return visitNonBuiltinCallExpr(E);
9464 }
9465 
9466 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9467                                      APValue &Result, const InitListExpr *ILE,
9468                                      QualType AllocType);
9469 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9470                                           APValue &Result,
9471                                           const CXXConstructExpr *CCE,
9472                                           QualType AllocType);
9473 
9474 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9475   if (!Info.getLangOpts().CPlusPlus20)
9476     Info.CCEDiag(E, diag::note_constexpr_new);
9477 
9478   // We cannot speculatively evaluate a delete expression.
9479   if (Info.SpeculativeEvaluationDepth)
9480     return false;
9481 
9482   FunctionDecl *OperatorNew = E->getOperatorNew();
9483 
9484   bool IsNothrow = false;
9485   bool IsPlacement = false;
9486   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9487       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9488     // FIXME Support array placement new.
9489     assert(E->getNumPlacementArgs() == 1);
9490     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9491       return false;
9492     if (Result.Designator.Invalid)
9493       return false;
9494     IsPlacement = true;
9495   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9496     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9497         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9498     return false;
9499   } else if (E->getNumPlacementArgs()) {
9500     // The only new-placement list we support is of the form (std::nothrow).
9501     //
9502     // FIXME: There is no restriction on this, but it's not clear that any
9503     // other form makes any sense. We get here for cases such as:
9504     //
9505     //   new (std::align_val_t{N}) X(int)
9506     //
9507     // (which should presumably be valid only if N is a multiple of
9508     // alignof(int), and in any case can't be deallocated unless N is
9509     // alignof(X) and X has new-extended alignment).
9510     if (E->getNumPlacementArgs() != 1 ||
9511         !E->getPlacementArg(0)->getType()->isNothrowT())
9512       return Error(E, diag::note_constexpr_new_placement);
9513 
9514     LValue Nothrow;
9515     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9516       return false;
9517     IsNothrow = true;
9518   }
9519 
9520   const Expr *Init = E->getInitializer();
9521   const InitListExpr *ResizedArrayILE = nullptr;
9522   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9523   bool ValueInit = false;
9524 
9525   QualType AllocType = E->getAllocatedType();
9526   if (Optional<const Expr *> ArraySize = E->getArraySize()) {
9527     const Expr *Stripped = *ArraySize;
9528     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9529          Stripped = ICE->getSubExpr())
9530       if (ICE->getCastKind() != CK_NoOp &&
9531           ICE->getCastKind() != CK_IntegralCast)
9532         break;
9533 
9534     llvm::APSInt ArrayBound;
9535     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9536       return false;
9537 
9538     // C++ [expr.new]p9:
9539     //   The expression is erroneous if:
9540     //   -- [...] its value before converting to size_t [or] applying the
9541     //      second standard conversion sequence is less than zero
9542     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9543       if (IsNothrow)
9544         return ZeroInitialization(E);
9545 
9546       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9547           << ArrayBound << (*ArraySize)->getSourceRange();
9548       return false;
9549     }
9550 
9551     //   -- its value is such that the size of the allocated object would
9552     //      exceed the implementation-defined limit
9553     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9554                                                 ArrayBound) >
9555         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9556       if (IsNothrow)
9557         return ZeroInitialization(E);
9558 
9559       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9560         << ArrayBound << (*ArraySize)->getSourceRange();
9561       return false;
9562     }
9563 
9564     //   -- the new-initializer is a braced-init-list and the number of
9565     //      array elements for which initializers are provided [...]
9566     //      exceeds the number of elements to initialize
9567     if (!Init) {
9568       // No initialization is performed.
9569     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9570                isa<ImplicitValueInitExpr>(Init)) {
9571       ValueInit = true;
9572     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9573       ResizedArrayCCE = CCE;
9574     } else {
9575       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9576       assert(CAT && "unexpected type for array initializer");
9577 
9578       unsigned Bits =
9579           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9580       llvm::APInt InitBound = CAT->getSize().zext(Bits);
9581       llvm::APInt AllocBound = ArrayBound.zext(Bits);
9582       if (InitBound.ugt(AllocBound)) {
9583         if (IsNothrow)
9584           return ZeroInitialization(E);
9585 
9586         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9587             << toString(AllocBound, 10, /*Signed=*/false)
9588             << toString(InitBound, 10, /*Signed=*/false)
9589             << (*ArraySize)->getSourceRange();
9590         return false;
9591       }
9592 
9593       // If the sizes differ, we must have an initializer list, and we need
9594       // special handling for this case when we initialize.
9595       if (InitBound != AllocBound)
9596         ResizedArrayILE = cast<InitListExpr>(Init);
9597     }
9598 
9599     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9600                                               ArrayType::Normal, 0);
9601   } else {
9602     assert(!AllocType->isArrayType() &&
9603            "array allocation with non-array new");
9604   }
9605 
9606   APValue *Val;
9607   if (IsPlacement) {
9608     AccessKinds AK = AK_Construct;
9609     struct FindObjectHandler {
9610       EvalInfo &Info;
9611       const Expr *E;
9612       QualType AllocType;
9613       const AccessKinds AccessKind;
9614       APValue *Value;
9615 
9616       typedef bool result_type;
9617       bool failed() { return false; }
9618       bool found(APValue &Subobj, QualType SubobjType) {
9619         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9620         // old name of the object to be used to name the new object.
9621         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9622           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9623             SubobjType << AllocType;
9624           return false;
9625         }
9626         Value = &Subobj;
9627         return true;
9628       }
9629       bool found(APSInt &Value, QualType SubobjType) {
9630         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9631         return false;
9632       }
9633       bool found(APFloat &Value, QualType SubobjType) {
9634         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9635         return false;
9636       }
9637     } Handler = {Info, E, AllocType, AK, nullptr};
9638 
9639     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9640     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9641       return false;
9642 
9643     Val = Handler.Value;
9644 
9645     // [basic.life]p1:
9646     //   The lifetime of an object o of type T ends when [...] the storage
9647     //   which the object occupies is [...] reused by an object that is not
9648     //   nested within o (6.6.2).
9649     *Val = APValue();
9650   } else {
9651     // Perform the allocation and obtain a pointer to the resulting object.
9652     Val = Info.createHeapAlloc(E, AllocType, Result);
9653     if (!Val)
9654       return false;
9655   }
9656 
9657   if (ValueInit) {
9658     ImplicitValueInitExpr VIE(AllocType);
9659     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9660       return false;
9661   } else if (ResizedArrayILE) {
9662     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9663                                   AllocType))
9664       return false;
9665   } else if (ResizedArrayCCE) {
9666     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9667                                        AllocType))
9668       return false;
9669   } else if (Init) {
9670     if (!EvaluateInPlace(*Val, Info, Result, Init))
9671       return false;
9672   } else if (!getDefaultInitValue(AllocType, *Val)) {
9673     return false;
9674   }
9675 
9676   // Array new returns a pointer to the first element, not a pointer to the
9677   // array.
9678   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9679     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9680 
9681   return true;
9682 }
9683 //===----------------------------------------------------------------------===//
9684 // Member Pointer Evaluation
9685 //===----------------------------------------------------------------------===//
9686 
9687 namespace {
9688 class MemberPointerExprEvaluator
9689   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9690   MemberPtr &Result;
9691 
9692   bool Success(const ValueDecl *D) {
9693     Result = MemberPtr(D);
9694     return true;
9695   }
9696 public:
9697 
9698   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9699     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9700 
9701   bool Success(const APValue &V, const Expr *E) {
9702     Result.setFrom(V);
9703     return true;
9704   }
9705   bool ZeroInitialization(const Expr *E) {
9706     return Success((const ValueDecl*)nullptr);
9707   }
9708 
9709   bool VisitCastExpr(const CastExpr *E);
9710   bool VisitUnaryAddrOf(const UnaryOperator *E);
9711 };
9712 } // end anonymous namespace
9713 
9714 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9715                                   EvalInfo &Info) {
9716   assert(!E->isValueDependent());
9717   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9718   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9719 }
9720 
9721 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9722   switch (E->getCastKind()) {
9723   default:
9724     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9725 
9726   case CK_NullToMemberPointer:
9727     VisitIgnoredValue(E->getSubExpr());
9728     return ZeroInitialization(E);
9729 
9730   case CK_BaseToDerivedMemberPointer: {
9731     if (!Visit(E->getSubExpr()))
9732       return false;
9733     if (E->path_empty())
9734       return true;
9735     // Base-to-derived member pointer casts store the path in derived-to-base
9736     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9737     // the wrong end of the derived->base arc, so stagger the path by one class.
9738     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9739     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9740          PathI != PathE; ++PathI) {
9741       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9742       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9743       if (!Result.castToDerived(Derived))
9744         return Error(E);
9745     }
9746     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9747     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9748       return Error(E);
9749     return true;
9750   }
9751 
9752   case CK_DerivedToBaseMemberPointer:
9753     if (!Visit(E->getSubExpr()))
9754       return false;
9755     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9756          PathE = E->path_end(); PathI != PathE; ++PathI) {
9757       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9758       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9759       if (!Result.castToBase(Base))
9760         return Error(E);
9761     }
9762     return true;
9763   }
9764 }
9765 
9766 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9767   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9768   // member can be formed.
9769   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9770 }
9771 
9772 //===----------------------------------------------------------------------===//
9773 // Record Evaluation
9774 //===----------------------------------------------------------------------===//
9775 
9776 namespace {
9777   class RecordExprEvaluator
9778   : public ExprEvaluatorBase<RecordExprEvaluator> {
9779     const LValue &This;
9780     APValue &Result;
9781   public:
9782 
9783     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9784       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9785 
9786     bool Success(const APValue &V, const Expr *E) {
9787       Result = V;
9788       return true;
9789     }
9790     bool ZeroInitialization(const Expr *E) {
9791       return ZeroInitialization(E, E->getType());
9792     }
9793     bool ZeroInitialization(const Expr *E, QualType T);
9794 
9795     bool VisitCallExpr(const CallExpr *E) {
9796       return handleCallExpr(E, Result, &This);
9797     }
9798     bool VisitCastExpr(const CastExpr *E);
9799     bool VisitInitListExpr(const InitListExpr *E);
9800     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9801       return VisitCXXConstructExpr(E, E->getType());
9802     }
9803     bool VisitLambdaExpr(const LambdaExpr *E);
9804     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9805     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9806     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9807     bool VisitBinCmp(const BinaryOperator *E);
9808   };
9809 }
9810 
9811 /// Perform zero-initialization on an object of non-union class type.
9812 /// C++11 [dcl.init]p5:
9813 ///  To zero-initialize an object or reference of type T means:
9814 ///    [...]
9815 ///    -- if T is a (possibly cv-qualified) non-union class type,
9816 ///       each non-static data member and each base-class subobject is
9817 ///       zero-initialized
9818 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9819                                           const RecordDecl *RD,
9820                                           const LValue &This, APValue &Result) {
9821   assert(!RD->isUnion() && "Expected non-union class type");
9822   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9823   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9824                    std::distance(RD->field_begin(), RD->field_end()));
9825 
9826   if (RD->isInvalidDecl()) return false;
9827   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9828 
9829   if (CD) {
9830     unsigned Index = 0;
9831     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9832            End = CD->bases_end(); I != End; ++I, ++Index) {
9833       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9834       LValue Subobject = This;
9835       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9836         return false;
9837       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9838                                          Result.getStructBase(Index)))
9839         return false;
9840     }
9841   }
9842 
9843   for (const auto *I : RD->fields()) {
9844     // -- if T is a reference type, no initialization is performed.
9845     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9846       continue;
9847 
9848     LValue Subobject = This;
9849     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9850       return false;
9851 
9852     ImplicitValueInitExpr VIE(I->getType());
9853     if (!EvaluateInPlace(
9854           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9855       return false;
9856   }
9857 
9858   return true;
9859 }
9860 
9861 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9862   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9863   if (RD->isInvalidDecl()) return false;
9864   if (RD->isUnion()) {
9865     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9866     // object's first non-static named data member is zero-initialized
9867     RecordDecl::field_iterator I = RD->field_begin();
9868     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9869       ++I;
9870     if (I == RD->field_end()) {
9871       Result = APValue((const FieldDecl*)nullptr);
9872       return true;
9873     }
9874 
9875     LValue Subobject = This;
9876     if (!HandleLValueMember(Info, E, Subobject, *I))
9877       return false;
9878     Result = APValue(*I);
9879     ImplicitValueInitExpr VIE(I->getType());
9880     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9881   }
9882 
9883   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9884     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9885     return false;
9886   }
9887 
9888   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9889 }
9890 
9891 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9892   switch (E->getCastKind()) {
9893   default:
9894     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9895 
9896   case CK_ConstructorConversion:
9897     return Visit(E->getSubExpr());
9898 
9899   case CK_DerivedToBase:
9900   case CK_UncheckedDerivedToBase: {
9901     APValue DerivedObject;
9902     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9903       return false;
9904     if (!DerivedObject.isStruct())
9905       return Error(E->getSubExpr());
9906 
9907     // Derived-to-base rvalue conversion: just slice off the derived part.
9908     APValue *Value = &DerivedObject;
9909     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9910     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9911          PathE = E->path_end(); PathI != PathE; ++PathI) {
9912       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9913       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9914       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9915       RD = Base;
9916     }
9917     Result = *Value;
9918     return true;
9919   }
9920   }
9921 }
9922 
9923 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9924   if (E->isTransparent())
9925     return Visit(E->getInit(0));
9926 
9927   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9928   if (RD->isInvalidDecl()) return false;
9929   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9930   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9931 
9932   EvalInfo::EvaluatingConstructorRAII EvalObj(
9933       Info,
9934       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9935       CXXRD && CXXRD->getNumBases());
9936 
9937   if (RD->isUnion()) {
9938     const FieldDecl *Field = E->getInitializedFieldInUnion();
9939     Result = APValue(Field);
9940     if (!Field)
9941       return true;
9942 
9943     // If the initializer list for a union does not contain any elements, the
9944     // first element of the union is value-initialized.
9945     // FIXME: The element should be initialized from an initializer list.
9946     //        Is this difference ever observable for initializer lists which
9947     //        we don't build?
9948     ImplicitValueInitExpr VIE(Field->getType());
9949     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9950 
9951     LValue Subobject = This;
9952     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9953       return false;
9954 
9955     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9956     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9957                                   isa<CXXDefaultInitExpr>(InitExpr));
9958 
9959     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9960       if (Field->isBitField())
9961         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9962                                      Field);
9963       return true;
9964     }
9965 
9966     return false;
9967   }
9968 
9969   if (!Result.hasValue())
9970     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9971                      std::distance(RD->field_begin(), RD->field_end()));
9972   unsigned ElementNo = 0;
9973   bool Success = true;
9974 
9975   // Initialize base classes.
9976   if (CXXRD && CXXRD->getNumBases()) {
9977     for (const auto &Base : CXXRD->bases()) {
9978       assert(ElementNo < E->getNumInits() && "missing init for base class");
9979       const Expr *Init = E->getInit(ElementNo);
9980 
9981       LValue Subobject = This;
9982       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9983         return false;
9984 
9985       APValue &FieldVal = Result.getStructBase(ElementNo);
9986       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9987         if (!Info.noteFailure())
9988           return false;
9989         Success = false;
9990       }
9991       ++ElementNo;
9992     }
9993 
9994     EvalObj.finishedConstructingBases();
9995   }
9996 
9997   // Initialize members.
9998   for (const auto *Field : RD->fields()) {
9999     // Anonymous bit-fields are not considered members of the class for
10000     // purposes of aggregate initialization.
10001     if (Field->isUnnamedBitfield())
10002       continue;
10003 
10004     LValue Subobject = This;
10005 
10006     bool HaveInit = ElementNo < E->getNumInits();
10007 
10008     // FIXME: Diagnostics here should point to the end of the initializer
10009     // list, not the start.
10010     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
10011                             Subobject, Field, &Layout))
10012       return false;
10013 
10014     // Perform an implicit value-initialization for members beyond the end of
10015     // the initializer list.
10016     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10017     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
10018 
10019     if (Field->getType()->isIncompleteArrayType()) {
10020       if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10021         if (!CAT->getSize().isZero()) {
10022           // Bail out for now. This might sort of "work", but the rest of the
10023           // code isn't really prepared to handle it.
10024           Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10025           return false;
10026         }
10027       }
10028     }
10029 
10030     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10031     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10032                                   isa<CXXDefaultInitExpr>(Init));
10033 
10034     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10035     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10036         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10037                                                        FieldVal, Field))) {
10038       if (!Info.noteFailure())
10039         return false;
10040       Success = false;
10041     }
10042   }
10043 
10044   EvalObj.finishedConstructingFields();
10045 
10046   return Success;
10047 }
10048 
10049 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10050                                                 QualType T) {
10051   // Note that E's type is not necessarily the type of our class here; we might
10052   // be initializing an array element instead.
10053   const CXXConstructorDecl *FD = E->getConstructor();
10054   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10055 
10056   bool ZeroInit = E->requiresZeroInitialization();
10057   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10058     // If we've already performed zero-initialization, we're already done.
10059     if (Result.hasValue())
10060       return true;
10061 
10062     if (ZeroInit)
10063       return ZeroInitialization(E, T);
10064 
10065     return getDefaultInitValue(T, Result);
10066   }
10067 
10068   const FunctionDecl *Definition = nullptr;
10069   auto Body = FD->getBody(Definition);
10070 
10071   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10072     return false;
10073 
10074   // Avoid materializing a temporary for an elidable copy/move constructor.
10075   if (E->isElidable() && !ZeroInit) {
10076     // FIXME: This only handles the simplest case, where the source object
10077     //        is passed directly as the first argument to the constructor.
10078     //        This should also handle stepping though implicit casts and
10079     //        and conversion sequences which involve two steps, with a
10080     //        conversion operator followed by a converting constructor.
10081     const Expr *SrcObj = E->getArg(0);
10082     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10083     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10084     if (const MaterializeTemporaryExpr *ME =
10085             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10086       return Visit(ME->getSubExpr());
10087   }
10088 
10089   if (ZeroInit && !ZeroInitialization(E, T))
10090     return false;
10091 
10092   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
10093   return HandleConstructorCall(E, This, Args,
10094                                cast<CXXConstructorDecl>(Definition), Info,
10095                                Result);
10096 }
10097 
10098 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10099     const CXXInheritedCtorInitExpr *E) {
10100   if (!Info.CurrentCall) {
10101     assert(Info.checkingPotentialConstantExpression());
10102     return false;
10103   }
10104 
10105   const CXXConstructorDecl *FD = E->getConstructor();
10106   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10107     return false;
10108 
10109   const FunctionDecl *Definition = nullptr;
10110   auto Body = FD->getBody(Definition);
10111 
10112   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10113     return false;
10114 
10115   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10116                                cast<CXXConstructorDecl>(Definition), Info,
10117                                Result);
10118 }
10119 
10120 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10121     const CXXStdInitializerListExpr *E) {
10122   const ConstantArrayType *ArrayType =
10123       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10124 
10125   LValue Array;
10126   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10127     return false;
10128 
10129   // Get a pointer to the first element of the array.
10130   Array.addArray(Info, E, ArrayType);
10131 
10132   auto InvalidType = [&] {
10133     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10134       << E->getType();
10135     return false;
10136   };
10137 
10138   // FIXME: Perform the checks on the field types in SemaInit.
10139   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10140   RecordDecl::field_iterator Field = Record->field_begin();
10141   if (Field == Record->field_end())
10142     return InvalidType();
10143 
10144   // Start pointer.
10145   if (!Field->getType()->isPointerType() ||
10146       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10147                             ArrayType->getElementType()))
10148     return InvalidType();
10149 
10150   // FIXME: What if the initializer_list type has base classes, etc?
10151   Result = APValue(APValue::UninitStruct(), 0, 2);
10152   Array.moveInto(Result.getStructField(0));
10153 
10154   if (++Field == Record->field_end())
10155     return InvalidType();
10156 
10157   if (Field->getType()->isPointerType() &&
10158       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10159                            ArrayType->getElementType())) {
10160     // End pointer.
10161     if (!HandleLValueArrayAdjustment(Info, E, Array,
10162                                      ArrayType->getElementType(),
10163                                      ArrayType->getSize().getZExtValue()))
10164       return false;
10165     Array.moveInto(Result.getStructField(1));
10166   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10167     // Length.
10168     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10169   else
10170     return InvalidType();
10171 
10172   if (++Field != Record->field_end())
10173     return InvalidType();
10174 
10175   return true;
10176 }
10177 
10178 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10179   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10180   if (ClosureClass->isInvalidDecl())
10181     return false;
10182 
10183   const size_t NumFields =
10184       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10185 
10186   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10187                                             E->capture_init_end()) &&
10188          "The number of lambda capture initializers should equal the number of "
10189          "fields within the closure type");
10190 
10191   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10192   // Iterate through all the lambda's closure object's fields and initialize
10193   // them.
10194   auto *CaptureInitIt = E->capture_init_begin();
10195   bool Success = true;
10196   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10197   for (const auto *Field : ClosureClass->fields()) {
10198     assert(CaptureInitIt != E->capture_init_end());
10199     // Get the initializer for this field
10200     Expr *const CurFieldInit = *CaptureInitIt++;
10201 
10202     // If there is no initializer, either this is a VLA or an error has
10203     // occurred.
10204     if (!CurFieldInit)
10205       return Error(E);
10206 
10207     LValue Subobject = This;
10208 
10209     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10210       return false;
10211 
10212     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10213     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10214       if (!Info.keepEvaluatingAfterFailure())
10215         return false;
10216       Success = false;
10217     }
10218   }
10219   return Success;
10220 }
10221 
10222 static bool EvaluateRecord(const Expr *E, const LValue &This,
10223                            APValue &Result, EvalInfo &Info) {
10224   assert(!E->isValueDependent());
10225   assert(E->isPRValue() && E->getType()->isRecordType() &&
10226          "can't evaluate expression as a record rvalue");
10227   return RecordExprEvaluator(Info, This, Result).Visit(E);
10228 }
10229 
10230 //===----------------------------------------------------------------------===//
10231 // Temporary Evaluation
10232 //
10233 // Temporaries are represented in the AST as rvalues, but generally behave like
10234 // lvalues. The full-object of which the temporary is a subobject is implicitly
10235 // materialized so that a reference can bind to it.
10236 //===----------------------------------------------------------------------===//
10237 namespace {
10238 class TemporaryExprEvaluator
10239   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10240 public:
10241   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10242     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10243 
10244   /// Visit an expression which constructs the value of this temporary.
10245   bool VisitConstructExpr(const Expr *E) {
10246     APValue &Value = Info.CurrentCall->createTemporary(
10247         E, E->getType(), ScopeKind::FullExpression, Result);
10248     return EvaluateInPlace(Value, Info, Result, E);
10249   }
10250 
10251   bool VisitCastExpr(const CastExpr *E) {
10252     switch (E->getCastKind()) {
10253     default:
10254       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10255 
10256     case CK_ConstructorConversion:
10257       return VisitConstructExpr(E->getSubExpr());
10258     }
10259   }
10260   bool VisitInitListExpr(const InitListExpr *E) {
10261     return VisitConstructExpr(E);
10262   }
10263   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10264     return VisitConstructExpr(E);
10265   }
10266   bool VisitCallExpr(const CallExpr *E) {
10267     return VisitConstructExpr(E);
10268   }
10269   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10270     return VisitConstructExpr(E);
10271   }
10272   bool VisitLambdaExpr(const LambdaExpr *E) {
10273     return VisitConstructExpr(E);
10274   }
10275 };
10276 } // end anonymous namespace
10277 
10278 /// Evaluate an expression of record type as a temporary.
10279 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10280   assert(!E->isValueDependent());
10281   assert(E->isPRValue() && E->getType()->isRecordType());
10282   return TemporaryExprEvaluator(Info, Result).Visit(E);
10283 }
10284 
10285 //===----------------------------------------------------------------------===//
10286 // Vector Evaluation
10287 //===----------------------------------------------------------------------===//
10288 
10289 namespace {
10290   class VectorExprEvaluator
10291   : public ExprEvaluatorBase<VectorExprEvaluator> {
10292     APValue &Result;
10293   public:
10294 
10295     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10296       : ExprEvaluatorBaseTy(info), Result(Result) {}
10297 
10298     bool Success(ArrayRef<APValue> V, const Expr *E) {
10299       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10300       // FIXME: remove this APValue copy.
10301       Result = APValue(V.data(), V.size());
10302       return true;
10303     }
10304     bool Success(const APValue &V, const Expr *E) {
10305       assert(V.isVector());
10306       Result = V;
10307       return true;
10308     }
10309     bool ZeroInitialization(const Expr *E);
10310 
10311     bool VisitUnaryReal(const UnaryOperator *E)
10312       { return Visit(E->getSubExpr()); }
10313     bool VisitCastExpr(const CastExpr* E);
10314     bool VisitInitListExpr(const InitListExpr *E);
10315     bool VisitUnaryImag(const UnaryOperator *E);
10316     bool VisitBinaryOperator(const BinaryOperator *E);
10317     bool VisitUnaryOperator(const UnaryOperator *E);
10318     // FIXME: Missing: conditional operator (for GNU
10319     //                 conditional select), shufflevector, ExtVectorElementExpr
10320   };
10321 } // end anonymous namespace
10322 
10323 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10324   assert(E->isPRValue() && E->getType()->isVectorType() &&
10325          "not a vector prvalue");
10326   return VectorExprEvaluator(Info, Result).Visit(E);
10327 }
10328 
10329 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10330   const VectorType *VTy = E->getType()->castAs<VectorType>();
10331   unsigned NElts = VTy->getNumElements();
10332 
10333   const Expr *SE = E->getSubExpr();
10334   QualType SETy = SE->getType();
10335 
10336   switch (E->getCastKind()) {
10337   case CK_VectorSplat: {
10338     APValue Val = APValue();
10339     if (SETy->isIntegerType()) {
10340       APSInt IntResult;
10341       if (!EvaluateInteger(SE, IntResult, Info))
10342         return false;
10343       Val = APValue(std::move(IntResult));
10344     } else if (SETy->isRealFloatingType()) {
10345       APFloat FloatResult(0.0);
10346       if (!EvaluateFloat(SE, FloatResult, Info))
10347         return false;
10348       Val = APValue(std::move(FloatResult));
10349     } else {
10350       return Error(E);
10351     }
10352 
10353     // Splat and create vector APValue.
10354     SmallVector<APValue, 4> Elts(NElts, Val);
10355     return Success(Elts, E);
10356   }
10357   case CK_BitCast: {
10358     // Evaluate the operand into an APInt we can extract from.
10359     llvm::APInt SValInt;
10360     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10361       return false;
10362     // Extract the elements
10363     QualType EltTy = VTy->getElementType();
10364     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10365     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10366     SmallVector<APValue, 4> Elts;
10367     if (EltTy->isRealFloatingType()) {
10368       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10369       unsigned FloatEltSize = EltSize;
10370       if (&Sem == &APFloat::x87DoubleExtended())
10371         FloatEltSize = 80;
10372       for (unsigned i = 0; i < NElts; i++) {
10373         llvm::APInt Elt;
10374         if (BigEndian)
10375           Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10376         else
10377           Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10378         Elts.push_back(APValue(APFloat(Sem, Elt)));
10379       }
10380     } else if (EltTy->isIntegerType()) {
10381       for (unsigned i = 0; i < NElts; i++) {
10382         llvm::APInt Elt;
10383         if (BigEndian)
10384           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10385         else
10386           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10387         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10388       }
10389     } else {
10390       return Error(E);
10391     }
10392     return Success(Elts, E);
10393   }
10394   default:
10395     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10396   }
10397 }
10398 
10399 bool
10400 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10401   const VectorType *VT = E->getType()->castAs<VectorType>();
10402   unsigned NumInits = E->getNumInits();
10403   unsigned NumElements = VT->getNumElements();
10404 
10405   QualType EltTy = VT->getElementType();
10406   SmallVector<APValue, 4> Elements;
10407 
10408   // The number of initializers can be less than the number of
10409   // vector elements. For OpenCL, this can be due to nested vector
10410   // initialization. For GCC compatibility, missing trailing elements
10411   // should be initialized with zeroes.
10412   unsigned CountInits = 0, CountElts = 0;
10413   while (CountElts < NumElements) {
10414     // Handle nested vector initialization.
10415     if (CountInits < NumInits
10416         && E->getInit(CountInits)->getType()->isVectorType()) {
10417       APValue v;
10418       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10419         return Error(E);
10420       unsigned vlen = v.getVectorLength();
10421       for (unsigned j = 0; j < vlen; j++)
10422         Elements.push_back(v.getVectorElt(j));
10423       CountElts += vlen;
10424     } else if (EltTy->isIntegerType()) {
10425       llvm::APSInt sInt(32);
10426       if (CountInits < NumInits) {
10427         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10428           return false;
10429       } else // trailing integer zero.
10430         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10431       Elements.push_back(APValue(sInt));
10432       CountElts++;
10433     } else {
10434       llvm::APFloat f(0.0);
10435       if (CountInits < NumInits) {
10436         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10437           return false;
10438       } else // trailing float zero.
10439         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10440       Elements.push_back(APValue(f));
10441       CountElts++;
10442     }
10443     CountInits++;
10444   }
10445   return Success(Elements, E);
10446 }
10447 
10448 bool
10449 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10450   const auto *VT = E->getType()->castAs<VectorType>();
10451   QualType EltTy = VT->getElementType();
10452   APValue ZeroElement;
10453   if (EltTy->isIntegerType())
10454     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10455   else
10456     ZeroElement =
10457         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10458 
10459   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10460   return Success(Elements, E);
10461 }
10462 
10463 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10464   VisitIgnoredValue(E->getSubExpr());
10465   return ZeroInitialization(E);
10466 }
10467 
10468 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10469   BinaryOperatorKind Op = E->getOpcode();
10470   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10471          "Operation not supported on vector types");
10472 
10473   if (Op == BO_Comma)
10474     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10475 
10476   Expr *LHS = E->getLHS();
10477   Expr *RHS = E->getRHS();
10478 
10479   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10480          "Must both be vector types");
10481   // Checking JUST the types are the same would be fine, except shifts don't
10482   // need to have their types be the same (since you always shift by an int).
10483   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10484              E->getType()->castAs<VectorType>()->getNumElements() &&
10485          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10486              E->getType()->castAs<VectorType>()->getNumElements() &&
10487          "All operands must be the same size.");
10488 
10489   APValue LHSValue;
10490   APValue RHSValue;
10491   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10492   if (!LHSOK && !Info.noteFailure())
10493     return false;
10494   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10495     return false;
10496 
10497   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10498     return false;
10499 
10500   return Success(LHSValue, E);
10501 }
10502 
10503 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10504                                                          QualType ResultTy,
10505                                                          UnaryOperatorKind Op,
10506                                                          APValue Elt) {
10507   switch (Op) {
10508   case UO_Plus:
10509     // Nothing to do here.
10510     return Elt;
10511   case UO_Minus:
10512     if (Elt.getKind() == APValue::Int) {
10513       Elt.getInt().negate();
10514     } else {
10515       assert(Elt.getKind() == APValue::Float &&
10516              "Vector can only be int or float type");
10517       Elt.getFloat().changeSign();
10518     }
10519     return Elt;
10520   case UO_Not:
10521     // This is only valid for integral types anyway, so we don't have to handle
10522     // float here.
10523     assert(Elt.getKind() == APValue::Int &&
10524            "Vector operator ~ can only be int");
10525     Elt.getInt().flipAllBits();
10526     return Elt;
10527   case UO_LNot: {
10528     if (Elt.getKind() == APValue::Int) {
10529       Elt.getInt() = !Elt.getInt();
10530       // operator ! on vectors returns -1 for 'truth', so negate it.
10531       Elt.getInt().negate();
10532       return Elt;
10533     }
10534     assert(Elt.getKind() == APValue::Float &&
10535            "Vector can only be int or float type");
10536     // Float types result in an int of the same size, but -1 for true, or 0 for
10537     // false.
10538     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10539                      ResultTy->isUnsignedIntegerType()};
10540     if (Elt.getFloat().isZero())
10541       EltResult.setAllBits();
10542     else
10543       EltResult.clearAllBits();
10544 
10545     return APValue{EltResult};
10546   }
10547   default:
10548     // FIXME: Implement the rest of the unary operators.
10549     return llvm::None;
10550   }
10551 }
10552 
10553 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10554   Expr *SubExpr = E->getSubExpr();
10555   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10556   // This result element type differs in the case of negating a floating point
10557   // vector, since the result type is the a vector of the equivilant sized
10558   // integer.
10559   const QualType ResultEltTy = VD->getElementType();
10560   UnaryOperatorKind Op = E->getOpcode();
10561 
10562   APValue SubExprValue;
10563   if (!Evaluate(SubExprValue, Info, SubExpr))
10564     return false;
10565 
10566   // FIXME: This vector evaluator someday needs to be changed to be LValue
10567   // aware/keep LValue information around, rather than dealing with just vector
10568   // types directly. Until then, we cannot handle cases where the operand to
10569   // these unary operators is an LValue. The only case I've been able to see
10570   // cause this is operator++ assigning to a member expression (only valid in
10571   // altivec compilations) in C mode, so this shouldn't limit us too much.
10572   if (SubExprValue.isLValue())
10573     return false;
10574 
10575   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10576          "Vector length doesn't match type?");
10577 
10578   SmallVector<APValue, 4> ResultElements;
10579   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10580     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10581         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10582     if (!Elt)
10583       return false;
10584     ResultElements.push_back(*Elt);
10585   }
10586   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10587 }
10588 
10589 //===----------------------------------------------------------------------===//
10590 // Array Evaluation
10591 //===----------------------------------------------------------------------===//
10592 
10593 namespace {
10594   class ArrayExprEvaluator
10595   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10596     const LValue &This;
10597     APValue &Result;
10598   public:
10599 
10600     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10601       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10602 
10603     bool Success(const APValue &V, const Expr *E) {
10604       assert(V.isArray() && "expected array");
10605       Result = V;
10606       return true;
10607     }
10608 
10609     bool ZeroInitialization(const Expr *E) {
10610       const ConstantArrayType *CAT =
10611           Info.Ctx.getAsConstantArrayType(E->getType());
10612       if (!CAT) {
10613         if (E->getType()->isIncompleteArrayType()) {
10614           // We can be asked to zero-initialize a flexible array member; this
10615           // is represented as an ImplicitValueInitExpr of incomplete array
10616           // type. In this case, the array has zero elements.
10617           Result = APValue(APValue::UninitArray(), 0, 0);
10618           return true;
10619         }
10620         // FIXME: We could handle VLAs here.
10621         return Error(E);
10622       }
10623 
10624       Result = APValue(APValue::UninitArray(), 0,
10625                        CAT->getSize().getZExtValue());
10626       if (!Result.hasArrayFiller())
10627         return true;
10628 
10629       // Zero-initialize all elements.
10630       LValue Subobject = This;
10631       Subobject.addArray(Info, E, CAT);
10632       ImplicitValueInitExpr VIE(CAT->getElementType());
10633       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10634     }
10635 
10636     bool VisitCallExpr(const CallExpr *E) {
10637       return handleCallExpr(E, Result, &This);
10638     }
10639     bool VisitInitListExpr(const InitListExpr *E,
10640                            QualType AllocType = QualType());
10641     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10642     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10643     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10644                                const LValue &Subobject,
10645                                APValue *Value, QualType Type);
10646     bool VisitStringLiteral(const StringLiteral *E,
10647                             QualType AllocType = QualType()) {
10648       expandStringLiteral(Info, E, Result, AllocType);
10649       return true;
10650     }
10651   };
10652 } // end anonymous namespace
10653 
10654 static bool EvaluateArray(const Expr *E, const LValue &This,
10655                           APValue &Result, EvalInfo &Info) {
10656   assert(!E->isValueDependent());
10657   assert(E->isPRValue() && E->getType()->isArrayType() &&
10658          "not an array prvalue");
10659   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10660 }
10661 
10662 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10663                                      APValue &Result, const InitListExpr *ILE,
10664                                      QualType AllocType) {
10665   assert(!ILE->isValueDependent());
10666   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10667          "not an array prvalue");
10668   return ArrayExprEvaluator(Info, This, Result)
10669       .VisitInitListExpr(ILE, AllocType);
10670 }
10671 
10672 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10673                                           APValue &Result,
10674                                           const CXXConstructExpr *CCE,
10675                                           QualType AllocType) {
10676   assert(!CCE->isValueDependent());
10677   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10678          "not an array prvalue");
10679   return ArrayExprEvaluator(Info, This, Result)
10680       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10681 }
10682 
10683 // Return true iff the given array filler may depend on the element index.
10684 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10685   // For now, just allow non-class value-initialization and initialization
10686   // lists comprised of them.
10687   if (isa<ImplicitValueInitExpr>(FillerExpr))
10688     return false;
10689   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10690     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10691       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10692         return true;
10693     }
10694     return false;
10695   }
10696   return true;
10697 }
10698 
10699 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10700                                            QualType AllocType) {
10701   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10702       AllocType.isNull() ? E->getType() : AllocType);
10703   if (!CAT)
10704     return Error(E);
10705 
10706   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10707   // an appropriately-typed string literal enclosed in braces.
10708   if (E->isStringLiteralInit()) {
10709     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10710     // FIXME: Support ObjCEncodeExpr here once we support it in
10711     // ArrayExprEvaluator generally.
10712     if (!SL)
10713       return Error(E);
10714     return VisitStringLiteral(SL, AllocType);
10715   }
10716   // Any other transparent list init will need proper handling of the
10717   // AllocType; we can't just recurse to the inner initializer.
10718   assert(!E->isTransparent() &&
10719          "transparent array list initialization is not string literal init?");
10720 
10721   bool Success = true;
10722 
10723   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10724          "zero-initialized array shouldn't have any initialized elts");
10725   APValue Filler;
10726   if (Result.isArray() && Result.hasArrayFiller())
10727     Filler = Result.getArrayFiller();
10728 
10729   unsigned NumEltsToInit = E->getNumInits();
10730   unsigned NumElts = CAT->getSize().getZExtValue();
10731   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10732 
10733   // If the initializer might depend on the array index, run it for each
10734   // array element.
10735   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10736     NumEltsToInit = NumElts;
10737 
10738   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10739                           << NumEltsToInit << ".\n");
10740 
10741   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10742 
10743   // If the array was previously zero-initialized, preserve the
10744   // zero-initialized values.
10745   if (Filler.hasValue()) {
10746     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10747       Result.getArrayInitializedElt(I) = Filler;
10748     if (Result.hasArrayFiller())
10749       Result.getArrayFiller() = Filler;
10750   }
10751 
10752   LValue Subobject = This;
10753   Subobject.addArray(Info, E, CAT);
10754   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10755     const Expr *Init =
10756         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10757     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10758                          Info, Subobject, Init) ||
10759         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10760                                      CAT->getElementType(), 1)) {
10761       if (!Info.noteFailure())
10762         return false;
10763       Success = false;
10764     }
10765   }
10766 
10767   if (!Result.hasArrayFiller())
10768     return Success;
10769 
10770   // If we get here, we have a trivial filler, which we can just evaluate
10771   // once and splat over the rest of the array elements.
10772   assert(FillerExpr && "no array filler for incomplete init list");
10773   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10774                          FillerExpr) && Success;
10775 }
10776 
10777 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10778   LValue CommonLV;
10779   if (E->getCommonExpr() &&
10780       !Evaluate(Info.CurrentCall->createTemporary(
10781                     E->getCommonExpr(),
10782                     getStorageType(Info.Ctx, E->getCommonExpr()),
10783                     ScopeKind::FullExpression, CommonLV),
10784                 Info, E->getCommonExpr()->getSourceExpr()))
10785     return false;
10786 
10787   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10788 
10789   uint64_t Elements = CAT->getSize().getZExtValue();
10790   Result = APValue(APValue::UninitArray(), Elements, Elements);
10791 
10792   LValue Subobject = This;
10793   Subobject.addArray(Info, E, CAT);
10794 
10795   bool Success = true;
10796   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10797     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10798                          Info, Subobject, E->getSubExpr()) ||
10799         !HandleLValueArrayAdjustment(Info, E, Subobject,
10800                                      CAT->getElementType(), 1)) {
10801       if (!Info.noteFailure())
10802         return false;
10803       Success = false;
10804     }
10805   }
10806 
10807   return Success;
10808 }
10809 
10810 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10811   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10812 }
10813 
10814 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10815                                                const LValue &Subobject,
10816                                                APValue *Value,
10817                                                QualType Type) {
10818   bool HadZeroInit = Value->hasValue();
10819 
10820   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10821     unsigned FinalSize = CAT->getSize().getZExtValue();
10822 
10823     // Preserve the array filler if we had prior zero-initialization.
10824     APValue Filler =
10825       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10826                                              : APValue();
10827 
10828     *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10829     if (FinalSize == 0)
10830       return true;
10831 
10832     LValue ArrayElt = Subobject;
10833     ArrayElt.addArray(Info, E, CAT);
10834     // We do the whole initialization in two passes, first for just one element,
10835     // then for the whole array. It's possible we may find out we can't do const
10836     // init in the first pass, in which case we avoid allocating a potentially
10837     // large array. We don't do more passes because expanding array requires
10838     // copying the data, which is wasteful.
10839     for (const unsigned N : {1u, FinalSize}) {
10840       unsigned OldElts = Value->getArrayInitializedElts();
10841       if (OldElts == N)
10842         break;
10843 
10844       // Expand the array to appropriate size.
10845       APValue NewValue(APValue::UninitArray(), N, FinalSize);
10846       for (unsigned I = 0; I < OldElts; ++I)
10847         NewValue.getArrayInitializedElt(I).swap(
10848             Value->getArrayInitializedElt(I));
10849       Value->swap(NewValue);
10850 
10851       if (HadZeroInit)
10852         for (unsigned I = OldElts; I < N; ++I)
10853           Value->getArrayInitializedElt(I) = Filler;
10854 
10855       // Initialize the elements.
10856       for (unsigned I = OldElts; I < N; ++I) {
10857         if (!VisitCXXConstructExpr(E, ArrayElt,
10858                                    &Value->getArrayInitializedElt(I),
10859                                    CAT->getElementType()) ||
10860             !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10861                                          CAT->getElementType(), 1))
10862           return false;
10863         // When checking for const initilization any diagnostic is considered
10864         // an error.
10865         if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10866             !Info.keepEvaluatingAfterFailure())
10867           return false;
10868       }
10869     }
10870 
10871     return true;
10872   }
10873 
10874   if (!Type->isRecordType())
10875     return Error(E);
10876 
10877   return RecordExprEvaluator(Info, Subobject, *Value)
10878              .VisitCXXConstructExpr(E, Type);
10879 }
10880 
10881 //===----------------------------------------------------------------------===//
10882 // Integer Evaluation
10883 //
10884 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10885 // types and back in constant folding. Integer values are thus represented
10886 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10887 //===----------------------------------------------------------------------===//
10888 
10889 namespace {
10890 class IntExprEvaluator
10891         : public ExprEvaluatorBase<IntExprEvaluator> {
10892   APValue &Result;
10893 public:
10894   IntExprEvaluator(EvalInfo &info, APValue &result)
10895       : ExprEvaluatorBaseTy(info), Result(result) {}
10896 
10897   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10898     assert(E->getType()->isIntegralOrEnumerationType() &&
10899            "Invalid evaluation result.");
10900     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10901            "Invalid evaluation result.");
10902     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10903            "Invalid evaluation result.");
10904     Result = APValue(SI);
10905     return true;
10906   }
10907   bool Success(const llvm::APSInt &SI, const Expr *E) {
10908     return Success(SI, E, Result);
10909   }
10910 
10911   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10912     assert(E->getType()->isIntegralOrEnumerationType() &&
10913            "Invalid evaluation result.");
10914     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10915            "Invalid evaluation result.");
10916     Result = APValue(APSInt(I));
10917     Result.getInt().setIsUnsigned(
10918                             E->getType()->isUnsignedIntegerOrEnumerationType());
10919     return true;
10920   }
10921   bool Success(const llvm::APInt &I, const Expr *E) {
10922     return Success(I, E, Result);
10923   }
10924 
10925   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10926     assert(E->getType()->isIntegralOrEnumerationType() &&
10927            "Invalid evaluation result.");
10928     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10929     return true;
10930   }
10931   bool Success(uint64_t Value, const Expr *E) {
10932     return Success(Value, E, Result);
10933   }
10934 
10935   bool Success(CharUnits Size, const Expr *E) {
10936     return Success(Size.getQuantity(), E);
10937   }
10938 
10939   bool Success(const APValue &V, const Expr *E) {
10940     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10941       Result = V;
10942       return true;
10943     }
10944     return Success(V.getInt(), E);
10945   }
10946 
10947   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10948 
10949   //===--------------------------------------------------------------------===//
10950   //                            Visitor Methods
10951   //===--------------------------------------------------------------------===//
10952 
10953   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10954     return Success(E->getValue(), E);
10955   }
10956   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10957     return Success(E->getValue(), E);
10958   }
10959 
10960   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10961   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10962     if (CheckReferencedDecl(E, E->getDecl()))
10963       return true;
10964 
10965     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10966   }
10967   bool VisitMemberExpr(const MemberExpr *E) {
10968     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10969       VisitIgnoredBaseExpression(E->getBase());
10970       return true;
10971     }
10972 
10973     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10974   }
10975 
10976   bool VisitCallExpr(const CallExpr *E);
10977   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10978   bool VisitBinaryOperator(const BinaryOperator *E);
10979   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10980   bool VisitUnaryOperator(const UnaryOperator *E);
10981 
10982   bool VisitCastExpr(const CastExpr* E);
10983   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10984 
10985   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10986     return Success(E->getValue(), E);
10987   }
10988 
10989   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10990     return Success(E->getValue(), E);
10991   }
10992 
10993   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10994     if (Info.ArrayInitIndex == uint64_t(-1)) {
10995       // We were asked to evaluate this subexpression independent of the
10996       // enclosing ArrayInitLoopExpr. We can't do that.
10997       Info.FFDiag(E);
10998       return false;
10999     }
11000     return Success(Info.ArrayInitIndex, E);
11001   }
11002 
11003   // Note, GNU defines __null as an integer, not a pointer.
11004   bool VisitGNUNullExpr(const GNUNullExpr *E) {
11005     return ZeroInitialization(E);
11006   }
11007 
11008   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11009     return Success(E->getValue(), E);
11010   }
11011 
11012   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11013     return Success(E->getValue(), E);
11014   }
11015 
11016   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11017     return Success(E->getValue(), E);
11018   }
11019 
11020   bool VisitUnaryReal(const UnaryOperator *E);
11021   bool VisitUnaryImag(const UnaryOperator *E);
11022 
11023   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11024   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11025   bool VisitSourceLocExpr(const SourceLocExpr *E);
11026   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11027   bool VisitRequiresExpr(const RequiresExpr *E);
11028   // FIXME: Missing: array subscript of vector, member of vector
11029 };
11030 
11031 class FixedPointExprEvaluator
11032     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11033   APValue &Result;
11034 
11035  public:
11036   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11037       : ExprEvaluatorBaseTy(info), Result(result) {}
11038 
11039   bool Success(const llvm::APInt &I, const Expr *E) {
11040     return Success(
11041         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11042   }
11043 
11044   bool Success(uint64_t Value, const Expr *E) {
11045     return Success(
11046         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11047   }
11048 
11049   bool Success(const APValue &V, const Expr *E) {
11050     return Success(V.getFixedPoint(), E);
11051   }
11052 
11053   bool Success(const APFixedPoint &V, const Expr *E) {
11054     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11055     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11056            "Invalid evaluation result.");
11057     Result = APValue(V);
11058     return true;
11059   }
11060 
11061   //===--------------------------------------------------------------------===//
11062   //                            Visitor Methods
11063   //===--------------------------------------------------------------------===//
11064 
11065   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11066     return Success(E->getValue(), E);
11067   }
11068 
11069   bool VisitCastExpr(const CastExpr *E);
11070   bool VisitUnaryOperator(const UnaryOperator *E);
11071   bool VisitBinaryOperator(const BinaryOperator *E);
11072 };
11073 } // end anonymous namespace
11074 
11075 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11076 /// produce either the integer value or a pointer.
11077 ///
11078 /// GCC has a heinous extension which folds casts between pointer types and
11079 /// pointer-sized integral types. We support this by allowing the evaluation of
11080 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11081 /// Some simple arithmetic on such values is supported (they are treated much
11082 /// like char*).
11083 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11084                                     EvalInfo &Info) {
11085   assert(!E->isValueDependent());
11086   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11087   return IntExprEvaluator(Info, Result).Visit(E);
11088 }
11089 
11090 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11091   assert(!E->isValueDependent());
11092   APValue Val;
11093   if (!EvaluateIntegerOrLValue(E, Val, Info))
11094     return false;
11095   if (!Val.isInt()) {
11096     // FIXME: It would be better to produce the diagnostic for casting
11097     //        a pointer to an integer.
11098     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11099     return false;
11100   }
11101   Result = Val.getInt();
11102   return true;
11103 }
11104 
11105 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11106   APValue Evaluated = E->EvaluateInContext(
11107       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11108   return Success(Evaluated, E);
11109 }
11110 
11111 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11112                                EvalInfo &Info) {
11113   assert(!E->isValueDependent());
11114   if (E->getType()->isFixedPointType()) {
11115     APValue Val;
11116     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11117       return false;
11118     if (!Val.isFixedPoint())
11119       return false;
11120 
11121     Result = Val.getFixedPoint();
11122     return true;
11123   }
11124   return false;
11125 }
11126 
11127 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11128                                         EvalInfo &Info) {
11129   assert(!E->isValueDependent());
11130   if (E->getType()->isIntegerType()) {
11131     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11132     APSInt Val;
11133     if (!EvaluateInteger(E, Val, Info))
11134       return false;
11135     Result = APFixedPoint(Val, FXSema);
11136     return true;
11137   } else if (E->getType()->isFixedPointType()) {
11138     return EvaluateFixedPoint(E, Result, Info);
11139   }
11140   return false;
11141 }
11142 
11143 /// Check whether the given declaration can be directly converted to an integral
11144 /// rvalue. If not, no diagnostic is produced; there are other things we can
11145 /// try.
11146 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11147   // Enums are integer constant exprs.
11148   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11149     // Check for signedness/width mismatches between E type and ECD value.
11150     bool SameSign = (ECD->getInitVal().isSigned()
11151                      == E->getType()->isSignedIntegerOrEnumerationType());
11152     bool SameWidth = (ECD->getInitVal().getBitWidth()
11153                       == Info.Ctx.getIntWidth(E->getType()));
11154     if (SameSign && SameWidth)
11155       return Success(ECD->getInitVal(), E);
11156     else {
11157       // Get rid of mismatch (otherwise Success assertions will fail)
11158       // by computing a new value matching the type of E.
11159       llvm::APSInt Val = ECD->getInitVal();
11160       if (!SameSign)
11161         Val.setIsSigned(!ECD->getInitVal().isSigned());
11162       if (!SameWidth)
11163         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11164       return Success(Val, E);
11165     }
11166   }
11167   return false;
11168 }
11169 
11170 /// Values returned by __builtin_classify_type, chosen to match the values
11171 /// produced by GCC's builtin.
11172 enum class GCCTypeClass {
11173   None = -1,
11174   Void = 0,
11175   Integer = 1,
11176   // GCC reserves 2 for character types, but instead classifies them as
11177   // integers.
11178   Enum = 3,
11179   Bool = 4,
11180   Pointer = 5,
11181   // GCC reserves 6 for references, but appears to never use it (because
11182   // expressions never have reference type, presumably).
11183   PointerToDataMember = 7,
11184   RealFloat = 8,
11185   Complex = 9,
11186   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11187   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11188   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11189   // uses 12 for that purpose, same as for a class or struct. Maybe it
11190   // internally implements a pointer to member as a struct?  Who knows.
11191   PointerToMemberFunction = 12, // Not a bug, see above.
11192   ClassOrStruct = 12,
11193   Union = 13,
11194   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11195   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11196   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11197   // literals.
11198 };
11199 
11200 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11201 /// as GCC.
11202 static GCCTypeClass
11203 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11204   assert(!T->isDependentType() && "unexpected dependent type");
11205 
11206   QualType CanTy = T.getCanonicalType();
11207   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11208 
11209   switch (CanTy->getTypeClass()) {
11210 #define TYPE(ID, BASE)
11211 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11212 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11213 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11214 #include "clang/AST/TypeNodes.inc"
11215   case Type::Auto:
11216   case Type::DeducedTemplateSpecialization:
11217       llvm_unreachable("unexpected non-canonical or dependent type");
11218 
11219   case Type::Builtin:
11220     switch (BT->getKind()) {
11221 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11222 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11223     case BuiltinType::ID: return GCCTypeClass::Integer;
11224 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11225     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11226 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11227     case BuiltinType::ID: break;
11228 #include "clang/AST/BuiltinTypes.def"
11229     case BuiltinType::Void:
11230       return GCCTypeClass::Void;
11231 
11232     case BuiltinType::Bool:
11233       return GCCTypeClass::Bool;
11234 
11235     case BuiltinType::Char_U:
11236     case BuiltinType::UChar:
11237     case BuiltinType::WChar_U:
11238     case BuiltinType::Char8:
11239     case BuiltinType::Char16:
11240     case BuiltinType::Char32:
11241     case BuiltinType::UShort:
11242     case BuiltinType::UInt:
11243     case BuiltinType::ULong:
11244     case BuiltinType::ULongLong:
11245     case BuiltinType::UInt128:
11246       return GCCTypeClass::Integer;
11247 
11248     case BuiltinType::UShortAccum:
11249     case BuiltinType::UAccum:
11250     case BuiltinType::ULongAccum:
11251     case BuiltinType::UShortFract:
11252     case BuiltinType::UFract:
11253     case BuiltinType::ULongFract:
11254     case BuiltinType::SatUShortAccum:
11255     case BuiltinType::SatUAccum:
11256     case BuiltinType::SatULongAccum:
11257     case BuiltinType::SatUShortFract:
11258     case BuiltinType::SatUFract:
11259     case BuiltinType::SatULongFract:
11260       return GCCTypeClass::None;
11261 
11262     case BuiltinType::NullPtr:
11263 
11264     case BuiltinType::ObjCId:
11265     case BuiltinType::ObjCClass:
11266     case BuiltinType::ObjCSel:
11267 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11268     case BuiltinType::Id:
11269 #include "clang/Basic/OpenCLImageTypes.def"
11270 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11271     case BuiltinType::Id:
11272 #include "clang/Basic/OpenCLExtensionTypes.def"
11273     case BuiltinType::OCLSampler:
11274     case BuiltinType::OCLEvent:
11275     case BuiltinType::OCLClkEvent:
11276     case BuiltinType::OCLQueue:
11277     case BuiltinType::OCLReserveID:
11278 #define SVE_TYPE(Name, Id, SingletonId) \
11279     case BuiltinType::Id:
11280 #include "clang/Basic/AArch64SVEACLETypes.def"
11281 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11282     case BuiltinType::Id:
11283 #include "clang/Basic/PPCTypes.def"
11284 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11285 #include "clang/Basic/RISCVVTypes.def"
11286       return GCCTypeClass::None;
11287 
11288     case BuiltinType::Dependent:
11289       llvm_unreachable("unexpected dependent type");
11290     };
11291     llvm_unreachable("unexpected placeholder type");
11292 
11293   case Type::Enum:
11294     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11295 
11296   case Type::Pointer:
11297   case Type::ConstantArray:
11298   case Type::VariableArray:
11299   case Type::IncompleteArray:
11300   case Type::FunctionNoProto:
11301   case Type::FunctionProto:
11302     return GCCTypeClass::Pointer;
11303 
11304   case Type::MemberPointer:
11305     return CanTy->isMemberDataPointerType()
11306                ? GCCTypeClass::PointerToDataMember
11307                : GCCTypeClass::PointerToMemberFunction;
11308 
11309   case Type::Complex:
11310     return GCCTypeClass::Complex;
11311 
11312   case Type::Record:
11313     return CanTy->isUnionType() ? GCCTypeClass::Union
11314                                 : GCCTypeClass::ClassOrStruct;
11315 
11316   case Type::Atomic:
11317     // GCC classifies _Atomic T the same as T.
11318     return EvaluateBuiltinClassifyType(
11319         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11320 
11321   case Type::BlockPointer:
11322   case Type::Vector:
11323   case Type::ExtVector:
11324   case Type::ConstantMatrix:
11325   case Type::ObjCObject:
11326   case Type::ObjCInterface:
11327   case Type::ObjCObjectPointer:
11328   case Type::Pipe:
11329   case Type::BitInt:
11330     // GCC classifies vectors as None. We follow its lead and classify all
11331     // other types that don't fit into the regular classification the same way.
11332     return GCCTypeClass::None;
11333 
11334   case Type::LValueReference:
11335   case Type::RValueReference:
11336     llvm_unreachable("invalid type for expression");
11337   }
11338 
11339   llvm_unreachable("unexpected type class");
11340 }
11341 
11342 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11343 /// as GCC.
11344 static GCCTypeClass
11345 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11346   // If no argument was supplied, default to None. This isn't
11347   // ideal, however it is what gcc does.
11348   if (E->getNumArgs() == 0)
11349     return GCCTypeClass::None;
11350 
11351   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11352   // being an ICE, but still folds it to a constant using the type of the first
11353   // argument.
11354   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11355 }
11356 
11357 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11358 /// __builtin_constant_p when applied to the given pointer.
11359 ///
11360 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11361 /// or it points to the first character of a string literal.
11362 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11363   APValue::LValueBase Base = LV.getLValueBase();
11364   if (Base.isNull()) {
11365     // A null base is acceptable.
11366     return true;
11367   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11368     if (!isa<StringLiteral>(E))
11369       return false;
11370     return LV.getLValueOffset().isZero();
11371   } else if (Base.is<TypeInfoLValue>()) {
11372     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11373     // evaluate to true.
11374     return true;
11375   } else {
11376     // Any other base is not constant enough for GCC.
11377     return false;
11378   }
11379 }
11380 
11381 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11382 /// GCC as we can manage.
11383 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11384   // This evaluation is not permitted to have side-effects, so evaluate it in
11385   // a speculative evaluation context.
11386   SpeculativeEvaluationRAII SpeculativeEval(Info);
11387 
11388   // Constant-folding is always enabled for the operand of __builtin_constant_p
11389   // (even when the enclosing evaluation context otherwise requires a strict
11390   // language-specific constant expression).
11391   FoldConstant Fold(Info, true);
11392 
11393   QualType ArgType = Arg->getType();
11394 
11395   // __builtin_constant_p always has one operand. The rules which gcc follows
11396   // are not precisely documented, but are as follows:
11397   //
11398   //  - If the operand is of integral, floating, complex or enumeration type,
11399   //    and can be folded to a known value of that type, it returns 1.
11400   //  - If the operand can be folded to a pointer to the first character
11401   //    of a string literal (or such a pointer cast to an integral type)
11402   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11403   //
11404   // Otherwise, it returns 0.
11405   //
11406   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11407   // its support for this did not work prior to GCC 9 and is not yet well
11408   // understood.
11409   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11410       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11411       ArgType->isNullPtrType()) {
11412     APValue V;
11413     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11414       Fold.keepDiagnostics();
11415       return false;
11416     }
11417 
11418     // For a pointer (possibly cast to integer), there are special rules.
11419     if (V.getKind() == APValue::LValue)
11420       return EvaluateBuiltinConstantPForLValue(V);
11421 
11422     // Otherwise, any constant value is good enough.
11423     return V.hasValue();
11424   }
11425 
11426   // Anything else isn't considered to be sufficiently constant.
11427   return false;
11428 }
11429 
11430 /// Retrieves the "underlying object type" of the given expression,
11431 /// as used by __builtin_object_size.
11432 static QualType getObjectType(APValue::LValueBase B) {
11433   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11434     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11435       return VD->getType();
11436   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11437     if (isa<CompoundLiteralExpr>(E))
11438       return E->getType();
11439   } else if (B.is<TypeInfoLValue>()) {
11440     return B.getTypeInfoType();
11441   } else if (B.is<DynamicAllocLValue>()) {
11442     return B.getDynamicAllocType();
11443   }
11444 
11445   return QualType();
11446 }
11447 
11448 /// A more selective version of E->IgnoreParenCasts for
11449 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11450 /// to change the type of E.
11451 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11452 ///
11453 /// Always returns an RValue with a pointer representation.
11454 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11455   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11456 
11457   auto *NoParens = E->IgnoreParens();
11458   auto *Cast = dyn_cast<CastExpr>(NoParens);
11459   if (Cast == nullptr)
11460     return NoParens;
11461 
11462   // We only conservatively allow a few kinds of casts, because this code is
11463   // inherently a simple solution that seeks to support the common case.
11464   auto CastKind = Cast->getCastKind();
11465   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11466       CastKind != CK_AddressSpaceConversion)
11467     return NoParens;
11468 
11469   auto *SubExpr = Cast->getSubExpr();
11470   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11471     return NoParens;
11472   return ignorePointerCastsAndParens(SubExpr);
11473 }
11474 
11475 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11476 /// record layout. e.g.
11477 ///   struct { struct { int a, b; } fst, snd; } obj;
11478 ///   obj.fst   // no
11479 ///   obj.snd   // yes
11480 ///   obj.fst.a // no
11481 ///   obj.fst.b // no
11482 ///   obj.snd.a // no
11483 ///   obj.snd.b // yes
11484 ///
11485 /// Please note: this function is specialized for how __builtin_object_size
11486 /// views "objects".
11487 ///
11488 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11489 /// correct result, it will always return true.
11490 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11491   assert(!LVal.Designator.Invalid);
11492 
11493   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11494     const RecordDecl *Parent = FD->getParent();
11495     Invalid = Parent->isInvalidDecl();
11496     if (Invalid || Parent->isUnion())
11497       return true;
11498     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11499     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11500   };
11501 
11502   auto &Base = LVal.getLValueBase();
11503   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11504     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11505       bool Invalid;
11506       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11507         return Invalid;
11508     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11509       for (auto *FD : IFD->chain()) {
11510         bool Invalid;
11511         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11512           return Invalid;
11513       }
11514     }
11515   }
11516 
11517   unsigned I = 0;
11518   QualType BaseType = getType(Base);
11519   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11520     // If we don't know the array bound, conservatively assume we're looking at
11521     // the final array element.
11522     ++I;
11523     if (BaseType->isIncompleteArrayType())
11524       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11525     else
11526       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11527   }
11528 
11529   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11530     const auto &Entry = LVal.Designator.Entries[I];
11531     if (BaseType->isArrayType()) {
11532       // Because __builtin_object_size treats arrays as objects, we can ignore
11533       // the index iff this is the last array in the Designator.
11534       if (I + 1 == E)
11535         return true;
11536       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11537       uint64_t Index = Entry.getAsArrayIndex();
11538       if (Index + 1 != CAT->getSize())
11539         return false;
11540       BaseType = CAT->getElementType();
11541     } else if (BaseType->isAnyComplexType()) {
11542       const auto *CT = BaseType->castAs<ComplexType>();
11543       uint64_t Index = Entry.getAsArrayIndex();
11544       if (Index != 1)
11545         return false;
11546       BaseType = CT->getElementType();
11547     } else if (auto *FD = getAsField(Entry)) {
11548       bool Invalid;
11549       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11550         return Invalid;
11551       BaseType = FD->getType();
11552     } else {
11553       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11554       return false;
11555     }
11556   }
11557   return true;
11558 }
11559 
11560 /// Tests to see if the LValue has a user-specified designator (that isn't
11561 /// necessarily valid). Note that this always returns 'true' if the LValue has
11562 /// an unsized array as its first designator entry, because there's currently no
11563 /// way to tell if the user typed *foo or foo[0].
11564 static bool refersToCompleteObject(const LValue &LVal) {
11565   if (LVal.Designator.Invalid)
11566     return false;
11567 
11568   if (!LVal.Designator.Entries.empty())
11569     return LVal.Designator.isMostDerivedAnUnsizedArray();
11570 
11571   if (!LVal.InvalidBase)
11572     return true;
11573 
11574   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11575   // the LValueBase.
11576   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11577   return !E || !isa<MemberExpr>(E);
11578 }
11579 
11580 /// Attempts to detect a user writing into a piece of memory that's impossible
11581 /// to figure out the size of by just using types.
11582 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11583   const SubobjectDesignator &Designator = LVal.Designator;
11584   // Notes:
11585   // - Users can only write off of the end when we have an invalid base. Invalid
11586   //   bases imply we don't know where the memory came from.
11587   // - We used to be a bit more aggressive here; we'd only be conservative if
11588   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11589   //   broke some common standard library extensions (PR30346), but was
11590   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11591   //   with some sort of list. OTOH, it seems that GCC is always
11592   //   conservative with the last element in structs (if it's an array), so our
11593   //   current behavior is more compatible than an explicit list approach would
11594   //   be.
11595   return LVal.InvalidBase &&
11596          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11597          Designator.MostDerivedIsArrayElement &&
11598          isDesignatorAtObjectEnd(Ctx, LVal);
11599 }
11600 
11601 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11602 /// Fails if the conversion would cause loss of precision.
11603 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11604                                             CharUnits &Result) {
11605   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11606   if (Int.ugt(CharUnitsMax))
11607     return false;
11608   Result = CharUnits::fromQuantity(Int.getZExtValue());
11609   return true;
11610 }
11611 
11612 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11613 /// determine how many bytes exist from the beginning of the object to either
11614 /// the end of the current subobject, or the end of the object itself, depending
11615 /// on what the LValue looks like + the value of Type.
11616 ///
11617 /// If this returns false, the value of Result is undefined.
11618 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11619                                unsigned Type, const LValue &LVal,
11620                                CharUnits &EndOffset) {
11621   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11622 
11623   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11624     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11625       return false;
11626     return HandleSizeof(Info, ExprLoc, Ty, Result);
11627   };
11628 
11629   // We want to evaluate the size of the entire object. This is a valid fallback
11630   // for when Type=1 and the designator is invalid, because we're asked for an
11631   // upper-bound.
11632   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11633     // Type=3 wants a lower bound, so we can't fall back to this.
11634     if (Type == 3 && !DetermineForCompleteObject)
11635       return false;
11636 
11637     llvm::APInt APEndOffset;
11638     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11639         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11640       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11641 
11642     if (LVal.InvalidBase)
11643       return false;
11644 
11645     QualType BaseTy = getObjectType(LVal.getLValueBase());
11646     return CheckedHandleSizeof(BaseTy, EndOffset);
11647   }
11648 
11649   // We want to evaluate the size of a subobject.
11650   const SubobjectDesignator &Designator = LVal.Designator;
11651 
11652   // The following is a moderately common idiom in C:
11653   //
11654   // struct Foo { int a; char c[1]; };
11655   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11656   // strcpy(&F->c[0], Bar);
11657   //
11658   // In order to not break too much legacy code, we need to support it.
11659   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11660     // If we can resolve this to an alloc_size call, we can hand that back,
11661     // because we know for certain how many bytes there are to write to.
11662     llvm::APInt APEndOffset;
11663     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11664         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11665       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11666 
11667     // If we cannot determine the size of the initial allocation, then we can't
11668     // given an accurate upper-bound. However, we are still able to give
11669     // conservative lower-bounds for Type=3.
11670     if (Type == 1)
11671       return false;
11672   }
11673 
11674   CharUnits BytesPerElem;
11675   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11676     return false;
11677 
11678   // According to the GCC documentation, we want the size of the subobject
11679   // denoted by the pointer. But that's not quite right -- what we actually
11680   // want is the size of the immediately-enclosing array, if there is one.
11681   int64_t ElemsRemaining;
11682   if (Designator.MostDerivedIsArrayElement &&
11683       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11684     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11685     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11686     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11687   } else {
11688     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11689   }
11690 
11691   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11692   return true;
11693 }
11694 
11695 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11696 /// returns true and stores the result in @p Size.
11697 ///
11698 /// If @p WasError is non-null, this will report whether the failure to evaluate
11699 /// is to be treated as an Error in IntExprEvaluator.
11700 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11701                                          EvalInfo &Info, uint64_t &Size) {
11702   // Determine the denoted object.
11703   LValue LVal;
11704   {
11705     // The operand of __builtin_object_size is never evaluated for side-effects.
11706     // If there are any, but we can determine the pointed-to object anyway, then
11707     // ignore the side-effects.
11708     SpeculativeEvaluationRAII SpeculativeEval(Info);
11709     IgnoreSideEffectsRAII Fold(Info);
11710 
11711     if (E->isGLValue()) {
11712       // It's possible for us to be given GLValues if we're called via
11713       // Expr::tryEvaluateObjectSize.
11714       APValue RVal;
11715       if (!EvaluateAsRValue(Info, E, RVal))
11716         return false;
11717       LVal.setFrom(Info.Ctx, RVal);
11718     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11719                                 /*InvalidBaseOK=*/true))
11720       return false;
11721   }
11722 
11723   // If we point to before the start of the object, there are no accessible
11724   // bytes.
11725   if (LVal.getLValueOffset().isNegative()) {
11726     Size = 0;
11727     return true;
11728   }
11729 
11730   CharUnits EndOffset;
11731   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11732     return false;
11733 
11734   // If we've fallen outside of the end offset, just pretend there's nothing to
11735   // write to/read from.
11736   if (EndOffset <= LVal.getLValueOffset())
11737     Size = 0;
11738   else
11739     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11740   return true;
11741 }
11742 
11743 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11744   if (unsigned BuiltinOp = E->getBuiltinCallee())
11745     return VisitBuiltinCallExpr(E, BuiltinOp);
11746 
11747   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11748 }
11749 
11750 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11751                                      APValue &Val, APSInt &Alignment) {
11752   QualType SrcTy = E->getArg(0)->getType();
11753   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11754     return false;
11755   // Even though we are evaluating integer expressions we could get a pointer
11756   // argument for the __builtin_is_aligned() case.
11757   if (SrcTy->isPointerType()) {
11758     LValue Ptr;
11759     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11760       return false;
11761     Ptr.moveInto(Val);
11762   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11763     Info.FFDiag(E->getArg(0));
11764     return false;
11765   } else {
11766     APSInt SrcInt;
11767     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11768       return false;
11769     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11770            "Bit widths must be the same");
11771     Val = APValue(SrcInt);
11772   }
11773   assert(Val.hasValue());
11774   return true;
11775 }
11776 
11777 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11778                                             unsigned BuiltinOp) {
11779   switch (BuiltinOp) {
11780   default:
11781     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11782 
11783   case Builtin::BI__builtin_dynamic_object_size:
11784   case Builtin::BI__builtin_object_size: {
11785     // The type was checked when we built the expression.
11786     unsigned Type =
11787         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11788     assert(Type <= 3 && "unexpected type");
11789 
11790     uint64_t Size;
11791     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11792       return Success(Size, E);
11793 
11794     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11795       return Success((Type & 2) ? 0 : -1, E);
11796 
11797     // Expression had no side effects, but we couldn't statically determine the
11798     // size of the referenced object.
11799     switch (Info.EvalMode) {
11800     case EvalInfo::EM_ConstantExpression:
11801     case EvalInfo::EM_ConstantFold:
11802     case EvalInfo::EM_IgnoreSideEffects:
11803       // Leave it to IR generation.
11804       return Error(E);
11805     case EvalInfo::EM_ConstantExpressionUnevaluated:
11806       // Reduce it to a constant now.
11807       return Success((Type & 2) ? 0 : -1, E);
11808     }
11809 
11810     llvm_unreachable("unexpected EvalMode");
11811   }
11812 
11813   case Builtin::BI__builtin_os_log_format_buffer_size: {
11814     analyze_os_log::OSLogBufferLayout Layout;
11815     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11816     return Success(Layout.size().getQuantity(), E);
11817   }
11818 
11819   case Builtin::BI__builtin_is_aligned: {
11820     APValue Src;
11821     APSInt Alignment;
11822     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11823       return false;
11824     if (Src.isLValue()) {
11825       // If we evaluated a pointer, check the minimum known alignment.
11826       LValue Ptr;
11827       Ptr.setFrom(Info.Ctx, Src);
11828       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11829       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11830       // We can return true if the known alignment at the computed offset is
11831       // greater than the requested alignment.
11832       assert(PtrAlign.isPowerOfTwo());
11833       assert(Alignment.isPowerOf2());
11834       if (PtrAlign.getQuantity() >= Alignment)
11835         return Success(1, E);
11836       // If the alignment is not known to be sufficient, some cases could still
11837       // be aligned at run time. However, if the requested alignment is less or
11838       // equal to the base alignment and the offset is not aligned, we know that
11839       // the run-time value can never be aligned.
11840       if (BaseAlignment.getQuantity() >= Alignment &&
11841           PtrAlign.getQuantity() < Alignment)
11842         return Success(0, E);
11843       // Otherwise we can't infer whether the value is sufficiently aligned.
11844       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11845       //  in cases where we can't fully evaluate the pointer.
11846       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11847           << Alignment;
11848       return false;
11849     }
11850     assert(Src.isInt());
11851     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11852   }
11853   case Builtin::BI__builtin_align_up: {
11854     APValue Src;
11855     APSInt Alignment;
11856     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11857       return false;
11858     if (!Src.isInt())
11859       return Error(E);
11860     APSInt AlignedVal =
11861         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11862                Src.getInt().isUnsigned());
11863     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11864     return Success(AlignedVal, E);
11865   }
11866   case Builtin::BI__builtin_align_down: {
11867     APValue Src;
11868     APSInt Alignment;
11869     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11870       return false;
11871     if (!Src.isInt())
11872       return Error(E);
11873     APSInt AlignedVal =
11874         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11875     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11876     return Success(AlignedVal, E);
11877   }
11878 
11879   case Builtin::BI__builtin_bitreverse8:
11880   case Builtin::BI__builtin_bitreverse16:
11881   case Builtin::BI__builtin_bitreverse32:
11882   case Builtin::BI__builtin_bitreverse64: {
11883     APSInt Val;
11884     if (!EvaluateInteger(E->getArg(0), Val, Info))
11885       return false;
11886 
11887     return Success(Val.reverseBits(), E);
11888   }
11889 
11890   case Builtin::BI__builtin_bswap16:
11891   case Builtin::BI__builtin_bswap32:
11892   case Builtin::BI__builtin_bswap64: {
11893     APSInt Val;
11894     if (!EvaluateInteger(E->getArg(0), Val, Info))
11895       return false;
11896 
11897     return Success(Val.byteSwap(), E);
11898   }
11899 
11900   case Builtin::BI__builtin_classify_type:
11901     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11902 
11903   case Builtin::BI__builtin_clrsb:
11904   case Builtin::BI__builtin_clrsbl:
11905   case Builtin::BI__builtin_clrsbll: {
11906     APSInt Val;
11907     if (!EvaluateInteger(E->getArg(0), Val, Info))
11908       return false;
11909 
11910     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11911   }
11912 
11913   case Builtin::BI__builtin_clz:
11914   case Builtin::BI__builtin_clzl:
11915   case Builtin::BI__builtin_clzll:
11916   case Builtin::BI__builtin_clzs: {
11917     APSInt Val;
11918     if (!EvaluateInteger(E->getArg(0), Val, Info))
11919       return false;
11920     if (!Val)
11921       return Error(E);
11922 
11923     return Success(Val.countLeadingZeros(), E);
11924   }
11925 
11926   case Builtin::BI__builtin_constant_p: {
11927     const Expr *Arg = E->getArg(0);
11928     if (EvaluateBuiltinConstantP(Info, Arg))
11929       return Success(true, E);
11930     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11931       // Outside a constant context, eagerly evaluate to false in the presence
11932       // of side-effects in order to avoid -Wunsequenced false-positives in
11933       // a branch on __builtin_constant_p(expr).
11934       return Success(false, E);
11935     }
11936     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11937     return false;
11938   }
11939 
11940   case Builtin::BI__builtin_is_constant_evaluated: {
11941     const auto *Callee = Info.CurrentCall->getCallee();
11942     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11943         (Info.CallStackDepth == 1 ||
11944          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11945           Callee->getIdentifier() &&
11946           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11947       // FIXME: Find a better way to avoid duplicated diagnostics.
11948       if (Info.EvalStatus.Diag)
11949         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11950                                                : Info.CurrentCall->CallLoc,
11951                     diag::warn_is_constant_evaluated_always_true_constexpr)
11952             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11953                                          : "std::is_constant_evaluated");
11954     }
11955 
11956     return Success(Info.InConstantContext, E);
11957   }
11958 
11959   case Builtin::BI__builtin_ctz:
11960   case Builtin::BI__builtin_ctzl:
11961   case Builtin::BI__builtin_ctzll:
11962   case Builtin::BI__builtin_ctzs: {
11963     APSInt Val;
11964     if (!EvaluateInteger(E->getArg(0), Val, Info))
11965       return false;
11966     if (!Val)
11967       return Error(E);
11968 
11969     return Success(Val.countTrailingZeros(), E);
11970   }
11971 
11972   case Builtin::BI__builtin_eh_return_data_regno: {
11973     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11974     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11975     return Success(Operand, E);
11976   }
11977 
11978   case Builtin::BI__builtin_expect:
11979   case Builtin::BI__builtin_expect_with_probability:
11980     return Visit(E->getArg(0));
11981 
11982   case Builtin::BI__builtin_ffs:
11983   case Builtin::BI__builtin_ffsl:
11984   case Builtin::BI__builtin_ffsll: {
11985     APSInt Val;
11986     if (!EvaluateInteger(E->getArg(0), Val, Info))
11987       return false;
11988 
11989     unsigned N = Val.countTrailingZeros();
11990     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11991   }
11992 
11993   case Builtin::BI__builtin_fpclassify: {
11994     APFloat Val(0.0);
11995     if (!EvaluateFloat(E->getArg(5), Val, Info))
11996       return false;
11997     unsigned Arg;
11998     switch (Val.getCategory()) {
11999     case APFloat::fcNaN: Arg = 0; break;
12000     case APFloat::fcInfinity: Arg = 1; break;
12001     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12002     case APFloat::fcZero: Arg = 4; break;
12003     }
12004     return Visit(E->getArg(Arg));
12005   }
12006 
12007   case Builtin::BI__builtin_isinf_sign: {
12008     APFloat Val(0.0);
12009     return EvaluateFloat(E->getArg(0), Val, Info) &&
12010            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12011   }
12012 
12013   case Builtin::BI__builtin_isinf: {
12014     APFloat Val(0.0);
12015     return EvaluateFloat(E->getArg(0), Val, Info) &&
12016            Success(Val.isInfinity() ? 1 : 0, E);
12017   }
12018 
12019   case Builtin::BI__builtin_isfinite: {
12020     APFloat Val(0.0);
12021     return EvaluateFloat(E->getArg(0), Val, Info) &&
12022            Success(Val.isFinite() ? 1 : 0, E);
12023   }
12024 
12025   case Builtin::BI__builtin_isnan: {
12026     APFloat Val(0.0);
12027     return EvaluateFloat(E->getArg(0), Val, Info) &&
12028            Success(Val.isNaN() ? 1 : 0, E);
12029   }
12030 
12031   case Builtin::BI__builtin_isnormal: {
12032     APFloat Val(0.0);
12033     return EvaluateFloat(E->getArg(0), Val, Info) &&
12034            Success(Val.isNormal() ? 1 : 0, E);
12035   }
12036 
12037   case Builtin::BI__builtin_parity:
12038   case Builtin::BI__builtin_parityl:
12039   case Builtin::BI__builtin_parityll: {
12040     APSInt Val;
12041     if (!EvaluateInteger(E->getArg(0), Val, Info))
12042       return false;
12043 
12044     return Success(Val.countPopulation() % 2, E);
12045   }
12046 
12047   case Builtin::BI__builtin_popcount:
12048   case Builtin::BI__builtin_popcountl:
12049   case Builtin::BI__builtin_popcountll: {
12050     APSInt Val;
12051     if (!EvaluateInteger(E->getArg(0), Val, Info))
12052       return false;
12053 
12054     return Success(Val.countPopulation(), E);
12055   }
12056 
12057   case Builtin::BI__builtin_rotateleft8:
12058   case Builtin::BI__builtin_rotateleft16:
12059   case Builtin::BI__builtin_rotateleft32:
12060   case Builtin::BI__builtin_rotateleft64:
12061   case Builtin::BI_rotl8: // Microsoft variants of rotate right
12062   case Builtin::BI_rotl16:
12063   case Builtin::BI_rotl:
12064   case Builtin::BI_lrotl:
12065   case Builtin::BI_rotl64: {
12066     APSInt Val, Amt;
12067     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12068         !EvaluateInteger(E->getArg(1), Amt, Info))
12069       return false;
12070 
12071     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12072   }
12073 
12074   case Builtin::BI__builtin_rotateright8:
12075   case Builtin::BI__builtin_rotateright16:
12076   case Builtin::BI__builtin_rotateright32:
12077   case Builtin::BI__builtin_rotateright64:
12078   case Builtin::BI_rotr8: // Microsoft variants of rotate right
12079   case Builtin::BI_rotr16:
12080   case Builtin::BI_rotr:
12081   case Builtin::BI_lrotr:
12082   case Builtin::BI_rotr64: {
12083     APSInt Val, Amt;
12084     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12085         !EvaluateInteger(E->getArg(1), Amt, Info))
12086       return false;
12087 
12088     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12089   }
12090 
12091   case Builtin::BIstrlen:
12092   case Builtin::BIwcslen:
12093     // A call to strlen is not a constant expression.
12094     if (Info.getLangOpts().CPlusPlus11)
12095       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12096         << /*isConstexpr*/0 << /*isConstructor*/0
12097         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12098     else
12099       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12100     LLVM_FALLTHROUGH;
12101   case Builtin::BI__builtin_strlen:
12102   case Builtin::BI__builtin_wcslen: {
12103     // As an extension, we support __builtin_strlen() as a constant expression,
12104     // and support folding strlen() to a constant.
12105     uint64_t StrLen;
12106     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12107       return Success(StrLen, E);
12108     return false;
12109   }
12110 
12111   case Builtin::BIstrcmp:
12112   case Builtin::BIwcscmp:
12113   case Builtin::BIstrncmp:
12114   case Builtin::BIwcsncmp:
12115   case Builtin::BImemcmp:
12116   case Builtin::BIbcmp:
12117   case Builtin::BIwmemcmp:
12118     // A call to strlen is not a constant expression.
12119     if (Info.getLangOpts().CPlusPlus11)
12120       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12121         << /*isConstexpr*/0 << /*isConstructor*/0
12122         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
12123     else
12124       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12125     LLVM_FALLTHROUGH;
12126   case Builtin::BI__builtin_strcmp:
12127   case Builtin::BI__builtin_wcscmp:
12128   case Builtin::BI__builtin_strncmp:
12129   case Builtin::BI__builtin_wcsncmp:
12130   case Builtin::BI__builtin_memcmp:
12131   case Builtin::BI__builtin_bcmp:
12132   case Builtin::BI__builtin_wmemcmp: {
12133     LValue String1, String2;
12134     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12135         !EvaluatePointer(E->getArg(1), String2, Info))
12136       return false;
12137 
12138     uint64_t MaxLength = uint64_t(-1);
12139     if (BuiltinOp != Builtin::BIstrcmp &&
12140         BuiltinOp != Builtin::BIwcscmp &&
12141         BuiltinOp != Builtin::BI__builtin_strcmp &&
12142         BuiltinOp != Builtin::BI__builtin_wcscmp) {
12143       APSInt N;
12144       if (!EvaluateInteger(E->getArg(2), N, Info))
12145         return false;
12146       MaxLength = N.getExtValue();
12147     }
12148 
12149     // Empty substrings compare equal by definition.
12150     if (MaxLength == 0u)
12151       return Success(0, E);
12152 
12153     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12154         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12155         String1.Designator.Invalid || String2.Designator.Invalid)
12156       return false;
12157 
12158     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12159     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12160 
12161     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12162                      BuiltinOp == Builtin::BIbcmp ||
12163                      BuiltinOp == Builtin::BI__builtin_memcmp ||
12164                      BuiltinOp == Builtin::BI__builtin_bcmp;
12165 
12166     assert(IsRawByte ||
12167            (Info.Ctx.hasSameUnqualifiedType(
12168                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12169             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12170 
12171     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12172     // 'char8_t', but no other types.
12173     if (IsRawByte &&
12174         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12175       // FIXME: Consider using our bit_cast implementation to support this.
12176       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12177           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12178           << CharTy1 << CharTy2;
12179       return false;
12180     }
12181 
12182     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12183       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12184              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12185              Char1.isInt() && Char2.isInt();
12186     };
12187     const auto &AdvanceElems = [&] {
12188       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12189              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12190     };
12191 
12192     bool StopAtNull =
12193         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12194          BuiltinOp != Builtin::BIwmemcmp &&
12195          BuiltinOp != Builtin::BI__builtin_memcmp &&
12196          BuiltinOp != Builtin::BI__builtin_bcmp &&
12197          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12198     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12199                   BuiltinOp == Builtin::BIwcsncmp ||
12200                   BuiltinOp == Builtin::BIwmemcmp ||
12201                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12202                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12203                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12204 
12205     for (; MaxLength; --MaxLength) {
12206       APValue Char1, Char2;
12207       if (!ReadCurElems(Char1, Char2))
12208         return false;
12209       if (Char1.getInt().ne(Char2.getInt())) {
12210         if (IsWide) // wmemcmp compares with wchar_t signedness.
12211           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12212         // memcmp always compares unsigned chars.
12213         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12214       }
12215       if (StopAtNull && !Char1.getInt())
12216         return Success(0, E);
12217       assert(!(StopAtNull && !Char2.getInt()));
12218       if (!AdvanceElems())
12219         return false;
12220     }
12221     // We hit the strncmp / memcmp limit.
12222     return Success(0, E);
12223   }
12224 
12225   case Builtin::BI__atomic_always_lock_free:
12226   case Builtin::BI__atomic_is_lock_free:
12227   case Builtin::BI__c11_atomic_is_lock_free: {
12228     APSInt SizeVal;
12229     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12230       return false;
12231 
12232     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12233     // of two less than or equal to the maximum inline atomic width, we know it
12234     // is lock-free.  If the size isn't a power of two, or greater than the
12235     // maximum alignment where we promote atomics, we know it is not lock-free
12236     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12237     // the answer can only be determined at runtime; for example, 16-byte
12238     // atomics have lock-free implementations on some, but not all,
12239     // x86-64 processors.
12240 
12241     // Check power-of-two.
12242     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12243     if (Size.isPowerOfTwo()) {
12244       // Check against inlining width.
12245       unsigned InlineWidthBits =
12246           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12247       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12248         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12249             Size == CharUnits::One() ||
12250             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12251                                                 Expr::NPC_NeverValueDependent))
12252           // OK, we will inline appropriately-aligned operations of this size,
12253           // and _Atomic(T) is appropriately-aligned.
12254           return Success(1, E);
12255 
12256         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12257           castAs<PointerType>()->getPointeeType();
12258         if (!PointeeType->isIncompleteType() &&
12259             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12260           // OK, we will inline operations on this object.
12261           return Success(1, E);
12262         }
12263       }
12264     }
12265 
12266     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12267         Success(0, E) : Error(E);
12268   }
12269   case Builtin::BI__builtin_add_overflow:
12270   case Builtin::BI__builtin_sub_overflow:
12271   case Builtin::BI__builtin_mul_overflow:
12272   case Builtin::BI__builtin_sadd_overflow:
12273   case Builtin::BI__builtin_uadd_overflow:
12274   case Builtin::BI__builtin_uaddl_overflow:
12275   case Builtin::BI__builtin_uaddll_overflow:
12276   case Builtin::BI__builtin_usub_overflow:
12277   case Builtin::BI__builtin_usubl_overflow:
12278   case Builtin::BI__builtin_usubll_overflow:
12279   case Builtin::BI__builtin_umul_overflow:
12280   case Builtin::BI__builtin_umull_overflow:
12281   case Builtin::BI__builtin_umulll_overflow:
12282   case Builtin::BI__builtin_saddl_overflow:
12283   case Builtin::BI__builtin_saddll_overflow:
12284   case Builtin::BI__builtin_ssub_overflow:
12285   case Builtin::BI__builtin_ssubl_overflow:
12286   case Builtin::BI__builtin_ssubll_overflow:
12287   case Builtin::BI__builtin_smul_overflow:
12288   case Builtin::BI__builtin_smull_overflow:
12289   case Builtin::BI__builtin_smulll_overflow: {
12290     LValue ResultLValue;
12291     APSInt LHS, RHS;
12292 
12293     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12294     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12295         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12296         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12297       return false;
12298 
12299     APSInt Result;
12300     bool DidOverflow = false;
12301 
12302     // If the types don't have to match, enlarge all 3 to the largest of them.
12303     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12304         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12305         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12306       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12307                       ResultType->isSignedIntegerOrEnumerationType();
12308       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12309                       ResultType->isSignedIntegerOrEnumerationType();
12310       uint64_t LHSSize = LHS.getBitWidth();
12311       uint64_t RHSSize = RHS.getBitWidth();
12312       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12313       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12314 
12315       // Add an additional bit if the signedness isn't uniformly agreed to. We
12316       // could do this ONLY if there is a signed and an unsigned that both have
12317       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12318       // caught in the shrink-to-result later anyway.
12319       if (IsSigned && !AllSigned)
12320         ++MaxBits;
12321 
12322       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12323       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12324       Result = APSInt(MaxBits, !IsSigned);
12325     }
12326 
12327     // Find largest int.
12328     switch (BuiltinOp) {
12329     default:
12330       llvm_unreachable("Invalid value for BuiltinOp");
12331     case Builtin::BI__builtin_add_overflow:
12332     case Builtin::BI__builtin_sadd_overflow:
12333     case Builtin::BI__builtin_saddl_overflow:
12334     case Builtin::BI__builtin_saddll_overflow:
12335     case Builtin::BI__builtin_uadd_overflow:
12336     case Builtin::BI__builtin_uaddl_overflow:
12337     case Builtin::BI__builtin_uaddll_overflow:
12338       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12339                               : LHS.uadd_ov(RHS, DidOverflow);
12340       break;
12341     case Builtin::BI__builtin_sub_overflow:
12342     case Builtin::BI__builtin_ssub_overflow:
12343     case Builtin::BI__builtin_ssubl_overflow:
12344     case Builtin::BI__builtin_ssubll_overflow:
12345     case Builtin::BI__builtin_usub_overflow:
12346     case Builtin::BI__builtin_usubl_overflow:
12347     case Builtin::BI__builtin_usubll_overflow:
12348       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12349                               : LHS.usub_ov(RHS, DidOverflow);
12350       break;
12351     case Builtin::BI__builtin_mul_overflow:
12352     case Builtin::BI__builtin_smul_overflow:
12353     case Builtin::BI__builtin_smull_overflow:
12354     case Builtin::BI__builtin_smulll_overflow:
12355     case Builtin::BI__builtin_umul_overflow:
12356     case Builtin::BI__builtin_umull_overflow:
12357     case Builtin::BI__builtin_umulll_overflow:
12358       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12359                               : LHS.umul_ov(RHS, DidOverflow);
12360       break;
12361     }
12362 
12363     // In the case where multiple sizes are allowed, truncate and see if
12364     // the values are the same.
12365     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12366         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12367         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12368       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12369       // since it will give us the behavior of a TruncOrSelf in the case where
12370       // its parameter <= its size.  We previously set Result to be at least the
12371       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12372       // will work exactly like TruncOrSelf.
12373       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12374       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12375 
12376       if (!APSInt::isSameValue(Temp, Result))
12377         DidOverflow = true;
12378       Result = Temp;
12379     }
12380 
12381     APValue APV{Result};
12382     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12383       return false;
12384     return Success(DidOverflow, E);
12385   }
12386   }
12387 }
12388 
12389 /// Determine whether this is a pointer past the end of the complete
12390 /// object referred to by the lvalue.
12391 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12392                                             const LValue &LV) {
12393   // A null pointer can be viewed as being "past the end" but we don't
12394   // choose to look at it that way here.
12395   if (!LV.getLValueBase())
12396     return false;
12397 
12398   // If the designator is valid and refers to a subobject, we're not pointing
12399   // past the end.
12400   if (!LV.getLValueDesignator().Invalid &&
12401       !LV.getLValueDesignator().isOnePastTheEnd())
12402     return false;
12403 
12404   // A pointer to an incomplete type might be past-the-end if the type's size is
12405   // zero.  We cannot tell because the type is incomplete.
12406   QualType Ty = getType(LV.getLValueBase());
12407   if (Ty->isIncompleteType())
12408     return true;
12409 
12410   // We're a past-the-end pointer if we point to the byte after the object,
12411   // no matter what our type or path is.
12412   auto Size = Ctx.getTypeSizeInChars(Ty);
12413   return LV.getLValueOffset() == Size;
12414 }
12415 
12416 namespace {
12417 
12418 /// Data recursive integer evaluator of certain binary operators.
12419 ///
12420 /// We use a data recursive algorithm for binary operators so that we are able
12421 /// to handle extreme cases of chained binary operators without causing stack
12422 /// overflow.
12423 class DataRecursiveIntBinOpEvaluator {
12424   struct EvalResult {
12425     APValue Val;
12426     bool Failed;
12427 
12428     EvalResult() : Failed(false) { }
12429 
12430     void swap(EvalResult &RHS) {
12431       Val.swap(RHS.Val);
12432       Failed = RHS.Failed;
12433       RHS.Failed = false;
12434     }
12435   };
12436 
12437   struct Job {
12438     const Expr *E;
12439     EvalResult LHSResult; // meaningful only for binary operator expression.
12440     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12441 
12442     Job() = default;
12443     Job(Job &&) = default;
12444 
12445     void startSpeculativeEval(EvalInfo &Info) {
12446       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12447     }
12448 
12449   private:
12450     SpeculativeEvaluationRAII SpecEvalRAII;
12451   };
12452 
12453   SmallVector<Job, 16> Queue;
12454 
12455   IntExprEvaluator &IntEval;
12456   EvalInfo &Info;
12457   APValue &FinalResult;
12458 
12459 public:
12460   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12461     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12462 
12463   /// True if \param E is a binary operator that we are going to handle
12464   /// data recursively.
12465   /// We handle binary operators that are comma, logical, or that have operands
12466   /// with integral or enumeration type.
12467   static bool shouldEnqueue(const BinaryOperator *E) {
12468     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12469            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12470             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12471             E->getRHS()->getType()->isIntegralOrEnumerationType());
12472   }
12473 
12474   bool Traverse(const BinaryOperator *E) {
12475     enqueue(E);
12476     EvalResult PrevResult;
12477     while (!Queue.empty())
12478       process(PrevResult);
12479 
12480     if (PrevResult.Failed) return false;
12481 
12482     FinalResult.swap(PrevResult.Val);
12483     return true;
12484   }
12485 
12486 private:
12487   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12488     return IntEval.Success(Value, E, Result);
12489   }
12490   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12491     return IntEval.Success(Value, E, Result);
12492   }
12493   bool Error(const Expr *E) {
12494     return IntEval.Error(E);
12495   }
12496   bool Error(const Expr *E, diag::kind D) {
12497     return IntEval.Error(E, D);
12498   }
12499 
12500   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12501     return Info.CCEDiag(E, D);
12502   }
12503 
12504   // Returns true if visiting the RHS is necessary, false otherwise.
12505   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12506                          bool &SuppressRHSDiags);
12507 
12508   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12509                   const BinaryOperator *E, APValue &Result);
12510 
12511   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12512     Result.Failed = !Evaluate(Result.Val, Info, E);
12513     if (Result.Failed)
12514       Result.Val = APValue();
12515   }
12516 
12517   void process(EvalResult &Result);
12518 
12519   void enqueue(const Expr *E) {
12520     E = E->IgnoreParens();
12521     Queue.resize(Queue.size()+1);
12522     Queue.back().E = E;
12523     Queue.back().Kind = Job::AnyExprKind;
12524   }
12525 };
12526 
12527 }
12528 
12529 bool DataRecursiveIntBinOpEvaluator::
12530        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12531                          bool &SuppressRHSDiags) {
12532   if (E->getOpcode() == BO_Comma) {
12533     // Ignore LHS but note if we could not evaluate it.
12534     if (LHSResult.Failed)
12535       return Info.noteSideEffect();
12536     return true;
12537   }
12538 
12539   if (E->isLogicalOp()) {
12540     bool LHSAsBool;
12541     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12542       // We were able to evaluate the LHS, see if we can get away with not
12543       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12544       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12545         Success(LHSAsBool, E, LHSResult.Val);
12546         return false; // Ignore RHS
12547       }
12548     } else {
12549       LHSResult.Failed = true;
12550 
12551       // Since we weren't able to evaluate the left hand side, it
12552       // might have had side effects.
12553       if (!Info.noteSideEffect())
12554         return false;
12555 
12556       // We can't evaluate the LHS; however, sometimes the result
12557       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12558       // Don't ignore RHS and suppress diagnostics from this arm.
12559       SuppressRHSDiags = true;
12560     }
12561 
12562     return true;
12563   }
12564 
12565   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12566          E->getRHS()->getType()->isIntegralOrEnumerationType());
12567 
12568   if (LHSResult.Failed && !Info.noteFailure())
12569     return false; // Ignore RHS;
12570 
12571   return true;
12572 }
12573 
12574 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12575                                     bool IsSub) {
12576   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12577   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12578   // offsets.
12579   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12580   CharUnits &Offset = LVal.getLValueOffset();
12581   uint64_t Offset64 = Offset.getQuantity();
12582   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12583   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12584                                          : Offset64 + Index64);
12585 }
12586 
12587 bool DataRecursiveIntBinOpEvaluator::
12588        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12589                   const BinaryOperator *E, APValue &Result) {
12590   if (E->getOpcode() == BO_Comma) {
12591     if (RHSResult.Failed)
12592       return false;
12593     Result = RHSResult.Val;
12594     return true;
12595   }
12596 
12597   if (E->isLogicalOp()) {
12598     bool lhsResult, rhsResult;
12599     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12600     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12601 
12602     if (LHSIsOK) {
12603       if (RHSIsOK) {
12604         if (E->getOpcode() == BO_LOr)
12605           return Success(lhsResult || rhsResult, E, Result);
12606         else
12607           return Success(lhsResult && rhsResult, E, Result);
12608       }
12609     } else {
12610       if (RHSIsOK) {
12611         // We can't evaluate the LHS; however, sometimes the result
12612         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12613         if (rhsResult == (E->getOpcode() == BO_LOr))
12614           return Success(rhsResult, E, Result);
12615       }
12616     }
12617 
12618     return false;
12619   }
12620 
12621   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12622          E->getRHS()->getType()->isIntegralOrEnumerationType());
12623 
12624   if (LHSResult.Failed || RHSResult.Failed)
12625     return false;
12626 
12627   const APValue &LHSVal = LHSResult.Val;
12628   const APValue &RHSVal = RHSResult.Val;
12629 
12630   // Handle cases like (unsigned long)&a + 4.
12631   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12632     Result = LHSVal;
12633     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12634     return true;
12635   }
12636 
12637   // Handle cases like 4 + (unsigned long)&a
12638   if (E->getOpcode() == BO_Add &&
12639       RHSVal.isLValue() && LHSVal.isInt()) {
12640     Result = RHSVal;
12641     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12642     return true;
12643   }
12644 
12645   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12646     // Handle (intptr_t)&&A - (intptr_t)&&B.
12647     if (!LHSVal.getLValueOffset().isZero() ||
12648         !RHSVal.getLValueOffset().isZero())
12649       return false;
12650     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12651     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12652     if (!LHSExpr || !RHSExpr)
12653       return false;
12654     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12655     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12656     if (!LHSAddrExpr || !RHSAddrExpr)
12657       return false;
12658     // Make sure both labels come from the same function.
12659     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12660         RHSAddrExpr->getLabel()->getDeclContext())
12661       return false;
12662     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12663     return true;
12664   }
12665 
12666   // All the remaining cases expect both operands to be an integer
12667   if (!LHSVal.isInt() || !RHSVal.isInt())
12668     return Error(E);
12669 
12670   // Set up the width and signedness manually, in case it can't be deduced
12671   // from the operation we're performing.
12672   // FIXME: Don't do this in the cases where we can deduce it.
12673   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12674                E->getType()->isUnsignedIntegerOrEnumerationType());
12675   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12676                          RHSVal.getInt(), Value))
12677     return false;
12678   return Success(Value, E, Result);
12679 }
12680 
12681 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12682   Job &job = Queue.back();
12683 
12684   switch (job.Kind) {
12685     case Job::AnyExprKind: {
12686       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12687         if (shouldEnqueue(Bop)) {
12688           job.Kind = Job::BinOpKind;
12689           enqueue(Bop->getLHS());
12690           return;
12691         }
12692       }
12693 
12694       EvaluateExpr(job.E, Result);
12695       Queue.pop_back();
12696       return;
12697     }
12698 
12699     case Job::BinOpKind: {
12700       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12701       bool SuppressRHSDiags = false;
12702       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12703         Queue.pop_back();
12704         return;
12705       }
12706       if (SuppressRHSDiags)
12707         job.startSpeculativeEval(Info);
12708       job.LHSResult.swap(Result);
12709       job.Kind = Job::BinOpVisitedLHSKind;
12710       enqueue(Bop->getRHS());
12711       return;
12712     }
12713 
12714     case Job::BinOpVisitedLHSKind: {
12715       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12716       EvalResult RHS;
12717       RHS.swap(Result);
12718       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12719       Queue.pop_back();
12720       return;
12721     }
12722   }
12723 
12724   llvm_unreachable("Invalid Job::Kind!");
12725 }
12726 
12727 namespace {
12728 enum class CmpResult {
12729   Unequal,
12730   Less,
12731   Equal,
12732   Greater,
12733   Unordered,
12734 };
12735 }
12736 
12737 template <class SuccessCB, class AfterCB>
12738 static bool
12739 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12740                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12741   assert(!E->isValueDependent());
12742   assert(E->isComparisonOp() && "expected comparison operator");
12743   assert((E->getOpcode() == BO_Cmp ||
12744           E->getType()->isIntegralOrEnumerationType()) &&
12745          "unsupported binary expression evaluation");
12746   auto Error = [&](const Expr *E) {
12747     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12748     return false;
12749   };
12750 
12751   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12752   bool IsEquality = E->isEqualityOp();
12753 
12754   QualType LHSTy = E->getLHS()->getType();
12755   QualType RHSTy = E->getRHS()->getType();
12756 
12757   if (LHSTy->isIntegralOrEnumerationType() &&
12758       RHSTy->isIntegralOrEnumerationType()) {
12759     APSInt LHS, RHS;
12760     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12761     if (!LHSOK && !Info.noteFailure())
12762       return false;
12763     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12764       return false;
12765     if (LHS < RHS)
12766       return Success(CmpResult::Less, E);
12767     if (LHS > RHS)
12768       return Success(CmpResult::Greater, E);
12769     return Success(CmpResult::Equal, E);
12770   }
12771 
12772   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12773     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12774     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12775 
12776     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12777     if (!LHSOK && !Info.noteFailure())
12778       return false;
12779     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12780       return false;
12781     if (LHSFX < RHSFX)
12782       return Success(CmpResult::Less, E);
12783     if (LHSFX > RHSFX)
12784       return Success(CmpResult::Greater, E);
12785     return Success(CmpResult::Equal, E);
12786   }
12787 
12788   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12789     ComplexValue LHS, RHS;
12790     bool LHSOK;
12791     if (E->isAssignmentOp()) {
12792       LValue LV;
12793       EvaluateLValue(E->getLHS(), LV, Info);
12794       LHSOK = false;
12795     } else if (LHSTy->isRealFloatingType()) {
12796       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12797       if (LHSOK) {
12798         LHS.makeComplexFloat();
12799         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12800       }
12801     } else {
12802       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12803     }
12804     if (!LHSOK && !Info.noteFailure())
12805       return false;
12806 
12807     if (E->getRHS()->getType()->isRealFloatingType()) {
12808       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12809         return false;
12810       RHS.makeComplexFloat();
12811       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12812     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12813       return false;
12814 
12815     if (LHS.isComplexFloat()) {
12816       APFloat::cmpResult CR_r =
12817         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12818       APFloat::cmpResult CR_i =
12819         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12820       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12821       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12822     } else {
12823       assert(IsEquality && "invalid complex comparison");
12824       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12825                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12826       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12827     }
12828   }
12829 
12830   if (LHSTy->isRealFloatingType() &&
12831       RHSTy->isRealFloatingType()) {
12832     APFloat RHS(0.0), LHS(0.0);
12833 
12834     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12835     if (!LHSOK && !Info.noteFailure())
12836       return false;
12837 
12838     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12839       return false;
12840 
12841     assert(E->isComparisonOp() && "Invalid binary operator!");
12842     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12843     if (!Info.InConstantContext &&
12844         APFloatCmpResult == APFloat::cmpUnordered &&
12845         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12846       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12847       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12848       return false;
12849     }
12850     auto GetCmpRes = [&]() {
12851       switch (APFloatCmpResult) {
12852       case APFloat::cmpEqual:
12853         return CmpResult::Equal;
12854       case APFloat::cmpLessThan:
12855         return CmpResult::Less;
12856       case APFloat::cmpGreaterThan:
12857         return CmpResult::Greater;
12858       case APFloat::cmpUnordered:
12859         return CmpResult::Unordered;
12860       }
12861       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12862     };
12863     return Success(GetCmpRes(), E);
12864   }
12865 
12866   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12867     LValue LHSValue, RHSValue;
12868 
12869     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12870     if (!LHSOK && !Info.noteFailure())
12871       return false;
12872 
12873     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12874       return false;
12875 
12876     // Reject differing bases from the normal codepath; we special-case
12877     // comparisons to null.
12878     if (!HasSameBase(LHSValue, RHSValue)) {
12879       // Inequalities and subtractions between unrelated pointers have
12880       // unspecified or undefined behavior.
12881       if (!IsEquality) {
12882         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12883         return false;
12884       }
12885       // A constant address may compare equal to the address of a symbol.
12886       // The one exception is that address of an object cannot compare equal
12887       // to a null pointer constant.
12888       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12889           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12890         return Error(E);
12891       // It's implementation-defined whether distinct literals will have
12892       // distinct addresses. In clang, the result of such a comparison is
12893       // unspecified, so it is not a constant expression. However, we do know
12894       // that the address of a literal will be non-null.
12895       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12896           LHSValue.Base && RHSValue.Base)
12897         return Error(E);
12898       // We can't tell whether weak symbols will end up pointing to the same
12899       // object.
12900       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12901         return Error(E);
12902       // We can't compare the address of the start of one object with the
12903       // past-the-end address of another object, per C++ DR1652.
12904       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12905            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12906           (RHSValue.Base && RHSValue.Offset.isZero() &&
12907            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12908         return Error(E);
12909       // We can't tell whether an object is at the same address as another
12910       // zero sized object.
12911       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12912           (LHSValue.Base && isZeroSized(RHSValue)))
12913         return Error(E);
12914       return Success(CmpResult::Unequal, E);
12915     }
12916 
12917     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12918     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12919 
12920     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12921     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12922 
12923     // C++11 [expr.rel]p3:
12924     //   Pointers to void (after pointer conversions) can be compared, with a
12925     //   result defined as follows: If both pointers represent the same
12926     //   address or are both the null pointer value, the result is true if the
12927     //   operator is <= or >= and false otherwise; otherwise the result is
12928     //   unspecified.
12929     // We interpret this as applying to pointers to *cv* void.
12930     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12931       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12932 
12933     // C++11 [expr.rel]p2:
12934     // - If two pointers point to non-static data members of the same object,
12935     //   or to subobjects or array elements fo such members, recursively, the
12936     //   pointer to the later declared member compares greater provided the
12937     //   two members have the same access control and provided their class is
12938     //   not a union.
12939     //   [...]
12940     // - Otherwise pointer comparisons are unspecified.
12941     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12942       bool WasArrayIndex;
12943       unsigned Mismatch = FindDesignatorMismatch(
12944           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12945       // At the point where the designators diverge, the comparison has a
12946       // specified value if:
12947       //  - we are comparing array indices
12948       //  - we are comparing fields of a union, or fields with the same access
12949       // Otherwise, the result is unspecified and thus the comparison is not a
12950       // constant expression.
12951       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12952           Mismatch < RHSDesignator.Entries.size()) {
12953         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12954         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12955         if (!LF && !RF)
12956           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12957         else if (!LF)
12958           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12959               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12960               << RF->getParent() << RF;
12961         else if (!RF)
12962           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12963               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12964               << LF->getParent() << LF;
12965         else if (!LF->getParent()->isUnion() &&
12966                  LF->getAccess() != RF->getAccess())
12967           Info.CCEDiag(E,
12968                        diag::note_constexpr_pointer_comparison_differing_access)
12969               << LF << LF->getAccess() << RF << RF->getAccess()
12970               << LF->getParent();
12971       }
12972     }
12973 
12974     // The comparison here must be unsigned, and performed with the same
12975     // width as the pointer.
12976     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12977     uint64_t CompareLHS = LHSOffset.getQuantity();
12978     uint64_t CompareRHS = RHSOffset.getQuantity();
12979     assert(PtrSize <= 64 && "Unexpected pointer width");
12980     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12981     CompareLHS &= Mask;
12982     CompareRHS &= Mask;
12983 
12984     // If there is a base and this is a relational operator, we can only
12985     // compare pointers within the object in question; otherwise, the result
12986     // depends on where the object is located in memory.
12987     if (!LHSValue.Base.isNull() && IsRelational) {
12988       QualType BaseTy = getType(LHSValue.Base);
12989       if (BaseTy->isIncompleteType())
12990         return Error(E);
12991       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12992       uint64_t OffsetLimit = Size.getQuantity();
12993       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12994         return Error(E);
12995     }
12996 
12997     if (CompareLHS < CompareRHS)
12998       return Success(CmpResult::Less, E);
12999     if (CompareLHS > CompareRHS)
13000       return Success(CmpResult::Greater, E);
13001     return Success(CmpResult::Equal, E);
13002   }
13003 
13004   if (LHSTy->isMemberPointerType()) {
13005     assert(IsEquality && "unexpected member pointer operation");
13006     assert(RHSTy->isMemberPointerType() && "invalid comparison");
13007 
13008     MemberPtr LHSValue, RHSValue;
13009 
13010     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13011     if (!LHSOK && !Info.noteFailure())
13012       return false;
13013 
13014     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13015       return false;
13016 
13017     // C++11 [expr.eq]p2:
13018     //   If both operands are null, they compare equal. Otherwise if only one is
13019     //   null, they compare unequal.
13020     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13021       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13022       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13023     }
13024 
13025     //   Otherwise if either is a pointer to a virtual member function, the
13026     //   result is unspecified.
13027     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13028       if (MD->isVirtual())
13029         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13030     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13031       if (MD->isVirtual())
13032         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13033 
13034     //   Otherwise they compare equal if and only if they would refer to the
13035     //   same member of the same most derived object or the same subobject if
13036     //   they were dereferenced with a hypothetical object of the associated
13037     //   class type.
13038     bool Equal = LHSValue == RHSValue;
13039     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13040   }
13041 
13042   if (LHSTy->isNullPtrType()) {
13043     assert(E->isComparisonOp() && "unexpected nullptr operation");
13044     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13045     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13046     // are compared, the result is true of the operator is <=, >= or ==, and
13047     // false otherwise.
13048     return Success(CmpResult::Equal, E);
13049   }
13050 
13051   return DoAfter();
13052 }
13053 
13054 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13055   if (!CheckLiteralType(Info, E))
13056     return false;
13057 
13058   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13059     ComparisonCategoryResult CCR;
13060     switch (CR) {
13061     case CmpResult::Unequal:
13062       llvm_unreachable("should never produce Unequal for three-way comparison");
13063     case CmpResult::Less:
13064       CCR = ComparisonCategoryResult::Less;
13065       break;
13066     case CmpResult::Equal:
13067       CCR = ComparisonCategoryResult::Equal;
13068       break;
13069     case CmpResult::Greater:
13070       CCR = ComparisonCategoryResult::Greater;
13071       break;
13072     case CmpResult::Unordered:
13073       CCR = ComparisonCategoryResult::Unordered;
13074       break;
13075     }
13076     // Evaluation succeeded. Lookup the information for the comparison category
13077     // type and fetch the VarDecl for the result.
13078     const ComparisonCategoryInfo &CmpInfo =
13079         Info.Ctx.CompCategories.getInfoForType(E->getType());
13080     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13081     // Check and evaluate the result as a constant expression.
13082     LValue LV;
13083     LV.set(VD);
13084     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13085       return false;
13086     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13087                                    ConstantExprKind::Normal);
13088   };
13089   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13090     return ExprEvaluatorBaseTy::VisitBinCmp(E);
13091   });
13092 }
13093 
13094 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13095   // We don't support assignment in C. C++ assignments don't get here because
13096   // assignment is an lvalue in C++.
13097   if (E->isAssignmentOp()) {
13098     Error(E);
13099     if (!Info.noteFailure())
13100       return false;
13101   }
13102 
13103   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13104     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13105 
13106   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13107           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13108          "DataRecursiveIntBinOpEvaluator should have handled integral types");
13109 
13110   if (E->isComparisonOp()) {
13111     // Evaluate builtin binary comparisons by evaluating them as three-way
13112     // comparisons and then translating the result.
13113     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13114       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13115              "should only produce Unequal for equality comparisons");
13116       bool IsEqual   = CR == CmpResult::Equal,
13117            IsLess    = CR == CmpResult::Less,
13118            IsGreater = CR == CmpResult::Greater;
13119       auto Op = E->getOpcode();
13120       switch (Op) {
13121       default:
13122         llvm_unreachable("unsupported binary operator");
13123       case BO_EQ:
13124       case BO_NE:
13125         return Success(IsEqual == (Op == BO_EQ), E);
13126       case BO_LT:
13127         return Success(IsLess, E);
13128       case BO_GT:
13129         return Success(IsGreater, E);
13130       case BO_LE:
13131         return Success(IsEqual || IsLess, E);
13132       case BO_GE:
13133         return Success(IsEqual || IsGreater, E);
13134       }
13135     };
13136     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13137       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13138     });
13139   }
13140 
13141   QualType LHSTy = E->getLHS()->getType();
13142   QualType RHSTy = E->getRHS()->getType();
13143 
13144   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13145       E->getOpcode() == BO_Sub) {
13146     LValue LHSValue, RHSValue;
13147 
13148     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13149     if (!LHSOK && !Info.noteFailure())
13150       return false;
13151 
13152     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13153       return false;
13154 
13155     // Reject differing bases from the normal codepath; we special-case
13156     // comparisons to null.
13157     if (!HasSameBase(LHSValue, RHSValue)) {
13158       // Handle &&A - &&B.
13159       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13160         return Error(E);
13161       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13162       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13163       if (!LHSExpr || !RHSExpr)
13164         return Error(E);
13165       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13166       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13167       if (!LHSAddrExpr || !RHSAddrExpr)
13168         return Error(E);
13169       // Make sure both labels come from the same function.
13170       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13171           RHSAddrExpr->getLabel()->getDeclContext())
13172         return Error(E);
13173       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13174     }
13175     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13176     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13177 
13178     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13179     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13180 
13181     // C++11 [expr.add]p6:
13182     //   Unless both pointers point to elements of the same array object, or
13183     //   one past the last element of the array object, the behavior is
13184     //   undefined.
13185     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13186         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13187                                 RHSDesignator))
13188       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13189 
13190     QualType Type = E->getLHS()->getType();
13191     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13192 
13193     CharUnits ElementSize;
13194     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13195       return false;
13196 
13197     // As an extension, a type may have zero size (empty struct or union in
13198     // C, array of zero length). Pointer subtraction in such cases has
13199     // undefined behavior, so is not constant.
13200     if (ElementSize.isZero()) {
13201       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13202           << ElementType;
13203       return false;
13204     }
13205 
13206     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13207     // and produce incorrect results when it overflows. Such behavior
13208     // appears to be non-conforming, but is common, so perhaps we should
13209     // assume the standard intended for such cases to be undefined behavior
13210     // and check for them.
13211 
13212     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13213     // overflow in the final conversion to ptrdiff_t.
13214     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13215     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13216     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13217                     false);
13218     APSInt TrueResult = (LHS - RHS) / ElemSize;
13219     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13220 
13221     if (Result.extend(65) != TrueResult &&
13222         !HandleOverflow(Info, E, TrueResult, E->getType()))
13223       return false;
13224     return Success(Result, E);
13225   }
13226 
13227   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13228 }
13229 
13230 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13231 /// a result as the expression's type.
13232 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13233                                     const UnaryExprOrTypeTraitExpr *E) {
13234   switch(E->getKind()) {
13235   case UETT_PreferredAlignOf:
13236   case UETT_AlignOf: {
13237     if (E->isArgumentType())
13238       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13239                      E);
13240     else
13241       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13242                      E);
13243   }
13244 
13245   case UETT_VecStep: {
13246     QualType Ty = E->getTypeOfArgument();
13247 
13248     if (Ty->isVectorType()) {
13249       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13250 
13251       // The vec_step built-in functions that take a 3-component
13252       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13253       if (n == 3)
13254         n = 4;
13255 
13256       return Success(n, E);
13257     } else
13258       return Success(1, E);
13259   }
13260 
13261   case UETT_SizeOf: {
13262     QualType SrcTy = E->getTypeOfArgument();
13263     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13264     //   the result is the size of the referenced type."
13265     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13266       SrcTy = Ref->getPointeeType();
13267 
13268     CharUnits Sizeof;
13269     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13270       return false;
13271     return Success(Sizeof, E);
13272   }
13273   case UETT_OpenMPRequiredSimdAlign:
13274     assert(E->isArgumentType());
13275     return Success(
13276         Info.Ctx.toCharUnitsFromBits(
13277                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13278             .getQuantity(),
13279         E);
13280   }
13281 
13282   llvm_unreachable("unknown expr/type trait");
13283 }
13284 
13285 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13286   CharUnits Result;
13287   unsigned n = OOE->getNumComponents();
13288   if (n == 0)
13289     return Error(OOE);
13290   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13291   for (unsigned i = 0; i != n; ++i) {
13292     OffsetOfNode ON = OOE->getComponent(i);
13293     switch (ON.getKind()) {
13294     case OffsetOfNode::Array: {
13295       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13296       APSInt IdxResult;
13297       if (!EvaluateInteger(Idx, IdxResult, Info))
13298         return false;
13299       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13300       if (!AT)
13301         return Error(OOE);
13302       CurrentType = AT->getElementType();
13303       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13304       Result += IdxResult.getSExtValue() * ElementSize;
13305       break;
13306     }
13307 
13308     case OffsetOfNode::Field: {
13309       FieldDecl *MemberDecl = ON.getField();
13310       const RecordType *RT = CurrentType->getAs<RecordType>();
13311       if (!RT)
13312         return Error(OOE);
13313       RecordDecl *RD = RT->getDecl();
13314       if (RD->isInvalidDecl()) return false;
13315       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13316       unsigned i = MemberDecl->getFieldIndex();
13317       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13318       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13319       CurrentType = MemberDecl->getType().getNonReferenceType();
13320       break;
13321     }
13322 
13323     case OffsetOfNode::Identifier:
13324       llvm_unreachable("dependent __builtin_offsetof");
13325 
13326     case OffsetOfNode::Base: {
13327       CXXBaseSpecifier *BaseSpec = ON.getBase();
13328       if (BaseSpec->isVirtual())
13329         return Error(OOE);
13330 
13331       // Find the layout of the class whose base we are looking into.
13332       const RecordType *RT = CurrentType->getAs<RecordType>();
13333       if (!RT)
13334         return Error(OOE);
13335       RecordDecl *RD = RT->getDecl();
13336       if (RD->isInvalidDecl()) return false;
13337       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13338 
13339       // Find the base class itself.
13340       CurrentType = BaseSpec->getType();
13341       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13342       if (!BaseRT)
13343         return Error(OOE);
13344 
13345       // Add the offset to the base.
13346       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13347       break;
13348     }
13349     }
13350   }
13351   return Success(Result, OOE);
13352 }
13353 
13354 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13355   switch (E->getOpcode()) {
13356   default:
13357     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13358     // See C99 6.6p3.
13359     return Error(E);
13360   case UO_Extension:
13361     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13362     // If so, we could clear the diagnostic ID.
13363     return Visit(E->getSubExpr());
13364   case UO_Plus:
13365     // The result is just the value.
13366     return Visit(E->getSubExpr());
13367   case UO_Minus: {
13368     if (!Visit(E->getSubExpr()))
13369       return false;
13370     if (!Result.isInt()) return Error(E);
13371     const APSInt &Value = Result.getInt();
13372     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13373         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13374                         E->getType()))
13375       return false;
13376     return Success(-Value, E);
13377   }
13378   case UO_Not: {
13379     if (!Visit(E->getSubExpr()))
13380       return false;
13381     if (!Result.isInt()) return Error(E);
13382     return Success(~Result.getInt(), E);
13383   }
13384   case UO_LNot: {
13385     bool bres;
13386     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13387       return false;
13388     return Success(!bres, E);
13389   }
13390   }
13391 }
13392 
13393 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13394 /// result type is integer.
13395 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13396   const Expr *SubExpr = E->getSubExpr();
13397   QualType DestType = E->getType();
13398   QualType SrcType = SubExpr->getType();
13399 
13400   switch (E->getCastKind()) {
13401   case CK_BaseToDerived:
13402   case CK_DerivedToBase:
13403   case CK_UncheckedDerivedToBase:
13404   case CK_Dynamic:
13405   case CK_ToUnion:
13406   case CK_ArrayToPointerDecay:
13407   case CK_FunctionToPointerDecay:
13408   case CK_NullToPointer:
13409   case CK_NullToMemberPointer:
13410   case CK_BaseToDerivedMemberPointer:
13411   case CK_DerivedToBaseMemberPointer:
13412   case CK_ReinterpretMemberPointer:
13413   case CK_ConstructorConversion:
13414   case CK_IntegralToPointer:
13415   case CK_ToVoid:
13416   case CK_VectorSplat:
13417   case CK_IntegralToFloating:
13418   case CK_FloatingCast:
13419   case CK_CPointerToObjCPointerCast:
13420   case CK_BlockPointerToObjCPointerCast:
13421   case CK_AnyPointerToBlockPointerCast:
13422   case CK_ObjCObjectLValueCast:
13423   case CK_FloatingRealToComplex:
13424   case CK_FloatingComplexToReal:
13425   case CK_FloatingComplexCast:
13426   case CK_FloatingComplexToIntegralComplex:
13427   case CK_IntegralRealToComplex:
13428   case CK_IntegralComplexCast:
13429   case CK_IntegralComplexToFloatingComplex:
13430   case CK_BuiltinFnToFnPtr:
13431   case CK_ZeroToOCLOpaqueType:
13432   case CK_NonAtomicToAtomic:
13433   case CK_AddressSpaceConversion:
13434   case CK_IntToOCLSampler:
13435   case CK_FloatingToFixedPoint:
13436   case CK_FixedPointToFloating:
13437   case CK_FixedPointCast:
13438   case CK_IntegralToFixedPoint:
13439   case CK_MatrixCast:
13440     llvm_unreachable("invalid cast kind for integral value");
13441 
13442   case CK_BitCast:
13443   case CK_Dependent:
13444   case CK_LValueBitCast:
13445   case CK_ARCProduceObject:
13446   case CK_ARCConsumeObject:
13447   case CK_ARCReclaimReturnedObject:
13448   case CK_ARCExtendBlockObject:
13449   case CK_CopyAndAutoreleaseBlockObject:
13450     return Error(E);
13451 
13452   case CK_UserDefinedConversion:
13453   case CK_LValueToRValue:
13454   case CK_AtomicToNonAtomic:
13455   case CK_NoOp:
13456   case CK_LValueToRValueBitCast:
13457     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13458 
13459   case CK_MemberPointerToBoolean:
13460   case CK_PointerToBoolean:
13461   case CK_IntegralToBoolean:
13462   case CK_FloatingToBoolean:
13463   case CK_BooleanToSignedIntegral:
13464   case CK_FloatingComplexToBoolean:
13465   case CK_IntegralComplexToBoolean: {
13466     bool BoolResult;
13467     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13468       return false;
13469     uint64_t IntResult = BoolResult;
13470     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13471       IntResult = (uint64_t)-1;
13472     return Success(IntResult, E);
13473   }
13474 
13475   case CK_FixedPointToIntegral: {
13476     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13477     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13478       return false;
13479     bool Overflowed;
13480     llvm::APSInt Result = Src.convertToInt(
13481         Info.Ctx.getIntWidth(DestType),
13482         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13483     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13484       return false;
13485     return Success(Result, E);
13486   }
13487 
13488   case CK_FixedPointToBoolean: {
13489     // Unsigned padding does not affect this.
13490     APValue Val;
13491     if (!Evaluate(Val, Info, SubExpr))
13492       return false;
13493     return Success(Val.getFixedPoint().getBoolValue(), E);
13494   }
13495 
13496   case CK_IntegralCast: {
13497     if (!Visit(SubExpr))
13498       return false;
13499 
13500     if (!Result.isInt()) {
13501       // Allow casts of address-of-label differences if they are no-ops
13502       // or narrowing.  (The narrowing case isn't actually guaranteed to
13503       // be constant-evaluatable except in some narrow cases which are hard
13504       // to detect here.  We let it through on the assumption the user knows
13505       // what they are doing.)
13506       if (Result.isAddrLabelDiff())
13507         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13508       // Only allow casts of lvalues if they are lossless.
13509       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13510     }
13511 
13512     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13513                                       Result.getInt()), E);
13514   }
13515 
13516   case CK_PointerToIntegral: {
13517     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13518 
13519     LValue LV;
13520     if (!EvaluatePointer(SubExpr, LV, Info))
13521       return false;
13522 
13523     if (LV.getLValueBase()) {
13524       // Only allow based lvalue casts if they are lossless.
13525       // FIXME: Allow a larger integer size than the pointer size, and allow
13526       // narrowing back down to pointer width in subsequent integral casts.
13527       // FIXME: Check integer type's active bits, not its type size.
13528       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13529         return Error(E);
13530 
13531       LV.Designator.setInvalid();
13532       LV.moveInto(Result);
13533       return true;
13534     }
13535 
13536     APSInt AsInt;
13537     APValue V;
13538     LV.moveInto(V);
13539     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13540       llvm_unreachable("Can't cast this!");
13541 
13542     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13543   }
13544 
13545   case CK_IntegralComplexToReal: {
13546     ComplexValue C;
13547     if (!EvaluateComplex(SubExpr, C, Info))
13548       return false;
13549     return Success(C.getComplexIntReal(), E);
13550   }
13551 
13552   case CK_FloatingToIntegral: {
13553     APFloat F(0.0);
13554     if (!EvaluateFloat(SubExpr, F, Info))
13555       return false;
13556 
13557     APSInt Value;
13558     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13559       return false;
13560     return Success(Value, E);
13561   }
13562   }
13563 
13564   llvm_unreachable("unknown cast resulting in integral value");
13565 }
13566 
13567 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13568   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13569     ComplexValue LV;
13570     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13571       return false;
13572     if (!LV.isComplexInt())
13573       return Error(E);
13574     return Success(LV.getComplexIntReal(), E);
13575   }
13576 
13577   return Visit(E->getSubExpr());
13578 }
13579 
13580 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13581   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13582     ComplexValue LV;
13583     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13584       return false;
13585     if (!LV.isComplexInt())
13586       return Error(E);
13587     return Success(LV.getComplexIntImag(), E);
13588   }
13589 
13590   VisitIgnoredValue(E->getSubExpr());
13591   return Success(0, E);
13592 }
13593 
13594 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13595   return Success(E->getPackLength(), E);
13596 }
13597 
13598 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13599   return Success(E->getValue(), E);
13600 }
13601 
13602 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13603        const ConceptSpecializationExpr *E) {
13604   return Success(E->isSatisfied(), E);
13605 }
13606 
13607 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13608   return Success(E->isSatisfied(), E);
13609 }
13610 
13611 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13612   switch (E->getOpcode()) {
13613     default:
13614       // Invalid unary operators
13615       return Error(E);
13616     case UO_Plus:
13617       // The result is just the value.
13618       return Visit(E->getSubExpr());
13619     case UO_Minus: {
13620       if (!Visit(E->getSubExpr())) return false;
13621       if (!Result.isFixedPoint())
13622         return Error(E);
13623       bool Overflowed;
13624       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13625       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13626         return false;
13627       return Success(Negated, E);
13628     }
13629     case UO_LNot: {
13630       bool bres;
13631       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13632         return false;
13633       return Success(!bres, E);
13634     }
13635   }
13636 }
13637 
13638 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13639   const Expr *SubExpr = E->getSubExpr();
13640   QualType DestType = E->getType();
13641   assert(DestType->isFixedPointType() &&
13642          "Expected destination type to be a fixed point type");
13643   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13644 
13645   switch (E->getCastKind()) {
13646   case CK_FixedPointCast: {
13647     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13648     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13649       return false;
13650     bool Overflowed;
13651     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13652     if (Overflowed) {
13653       if (Info.checkingForUndefinedBehavior())
13654         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13655                                          diag::warn_fixedpoint_constant_overflow)
13656           << Result.toString() << E->getType();
13657       if (!HandleOverflow(Info, E, Result, E->getType()))
13658         return false;
13659     }
13660     return Success(Result, E);
13661   }
13662   case CK_IntegralToFixedPoint: {
13663     APSInt Src;
13664     if (!EvaluateInteger(SubExpr, Src, Info))
13665       return false;
13666 
13667     bool Overflowed;
13668     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13669         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13670 
13671     if (Overflowed) {
13672       if (Info.checkingForUndefinedBehavior())
13673         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13674                                          diag::warn_fixedpoint_constant_overflow)
13675           << IntResult.toString() << E->getType();
13676       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13677         return false;
13678     }
13679 
13680     return Success(IntResult, E);
13681   }
13682   case CK_FloatingToFixedPoint: {
13683     APFloat Src(0.0);
13684     if (!EvaluateFloat(SubExpr, Src, Info))
13685       return false;
13686 
13687     bool Overflowed;
13688     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13689         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13690 
13691     if (Overflowed) {
13692       if (Info.checkingForUndefinedBehavior())
13693         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13694                                          diag::warn_fixedpoint_constant_overflow)
13695           << Result.toString() << E->getType();
13696       if (!HandleOverflow(Info, E, Result, E->getType()))
13697         return false;
13698     }
13699 
13700     return Success(Result, E);
13701   }
13702   case CK_NoOp:
13703   case CK_LValueToRValue:
13704     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13705   default:
13706     return Error(E);
13707   }
13708 }
13709 
13710 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13711   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13712     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13713 
13714   const Expr *LHS = E->getLHS();
13715   const Expr *RHS = E->getRHS();
13716   FixedPointSemantics ResultFXSema =
13717       Info.Ctx.getFixedPointSemantics(E->getType());
13718 
13719   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13720   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13721     return false;
13722   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13723   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13724     return false;
13725 
13726   bool OpOverflow = false, ConversionOverflow = false;
13727   APFixedPoint Result(LHSFX.getSemantics());
13728   switch (E->getOpcode()) {
13729   case BO_Add: {
13730     Result = LHSFX.add(RHSFX, &OpOverflow)
13731                   .convert(ResultFXSema, &ConversionOverflow);
13732     break;
13733   }
13734   case BO_Sub: {
13735     Result = LHSFX.sub(RHSFX, &OpOverflow)
13736                   .convert(ResultFXSema, &ConversionOverflow);
13737     break;
13738   }
13739   case BO_Mul: {
13740     Result = LHSFX.mul(RHSFX, &OpOverflow)
13741                   .convert(ResultFXSema, &ConversionOverflow);
13742     break;
13743   }
13744   case BO_Div: {
13745     if (RHSFX.getValue() == 0) {
13746       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13747       return false;
13748     }
13749     Result = LHSFX.div(RHSFX, &OpOverflow)
13750                   .convert(ResultFXSema, &ConversionOverflow);
13751     break;
13752   }
13753   case BO_Shl:
13754   case BO_Shr: {
13755     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13756     llvm::APSInt RHSVal = RHSFX.getValue();
13757 
13758     unsigned ShiftBW =
13759         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13760     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13761     // Embedded-C 4.1.6.2.2:
13762     //   The right operand must be nonnegative and less than the total number
13763     //   of (nonpadding) bits of the fixed-point operand ...
13764     if (RHSVal.isNegative())
13765       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13766     else if (Amt != RHSVal)
13767       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13768           << RHSVal << E->getType() << ShiftBW;
13769 
13770     if (E->getOpcode() == BO_Shl)
13771       Result = LHSFX.shl(Amt, &OpOverflow);
13772     else
13773       Result = LHSFX.shr(Amt, &OpOverflow);
13774     break;
13775   }
13776   default:
13777     return false;
13778   }
13779   if (OpOverflow || ConversionOverflow) {
13780     if (Info.checkingForUndefinedBehavior())
13781       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13782                                        diag::warn_fixedpoint_constant_overflow)
13783         << Result.toString() << E->getType();
13784     if (!HandleOverflow(Info, E, Result, E->getType()))
13785       return false;
13786   }
13787   return Success(Result, E);
13788 }
13789 
13790 //===----------------------------------------------------------------------===//
13791 // Float Evaluation
13792 //===----------------------------------------------------------------------===//
13793 
13794 namespace {
13795 class FloatExprEvaluator
13796   : public ExprEvaluatorBase<FloatExprEvaluator> {
13797   APFloat &Result;
13798 public:
13799   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13800     : ExprEvaluatorBaseTy(info), Result(result) {}
13801 
13802   bool Success(const APValue &V, const Expr *e) {
13803     Result = V.getFloat();
13804     return true;
13805   }
13806 
13807   bool ZeroInitialization(const Expr *E) {
13808     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13809     return true;
13810   }
13811 
13812   bool VisitCallExpr(const CallExpr *E);
13813 
13814   bool VisitUnaryOperator(const UnaryOperator *E);
13815   bool VisitBinaryOperator(const BinaryOperator *E);
13816   bool VisitFloatingLiteral(const FloatingLiteral *E);
13817   bool VisitCastExpr(const CastExpr *E);
13818 
13819   bool VisitUnaryReal(const UnaryOperator *E);
13820   bool VisitUnaryImag(const UnaryOperator *E);
13821 
13822   // FIXME: Missing: array subscript of vector, member of vector
13823 };
13824 } // end anonymous namespace
13825 
13826 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13827   assert(!E->isValueDependent());
13828   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13829   return FloatExprEvaluator(Info, Result).Visit(E);
13830 }
13831 
13832 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13833                                   QualType ResultTy,
13834                                   const Expr *Arg,
13835                                   bool SNaN,
13836                                   llvm::APFloat &Result) {
13837   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13838   if (!S) return false;
13839 
13840   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13841 
13842   llvm::APInt fill;
13843 
13844   // Treat empty strings as if they were zero.
13845   if (S->getString().empty())
13846     fill = llvm::APInt(32, 0);
13847   else if (S->getString().getAsInteger(0, fill))
13848     return false;
13849 
13850   if (Context.getTargetInfo().isNan2008()) {
13851     if (SNaN)
13852       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13853     else
13854       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13855   } else {
13856     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13857     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13858     // a different encoding to what became a standard in 2008, and for pre-
13859     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13860     // sNaN. This is now known as "legacy NaN" encoding.
13861     if (SNaN)
13862       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13863     else
13864       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13865   }
13866 
13867   return true;
13868 }
13869 
13870 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13871   switch (E->getBuiltinCallee()) {
13872   default:
13873     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13874 
13875   case Builtin::BI__builtin_huge_val:
13876   case Builtin::BI__builtin_huge_valf:
13877   case Builtin::BI__builtin_huge_vall:
13878   case Builtin::BI__builtin_huge_valf16:
13879   case Builtin::BI__builtin_huge_valf128:
13880   case Builtin::BI__builtin_inf:
13881   case Builtin::BI__builtin_inff:
13882   case Builtin::BI__builtin_infl:
13883   case Builtin::BI__builtin_inff16:
13884   case Builtin::BI__builtin_inff128: {
13885     const llvm::fltSemantics &Sem =
13886       Info.Ctx.getFloatTypeSemantics(E->getType());
13887     Result = llvm::APFloat::getInf(Sem);
13888     return true;
13889   }
13890 
13891   case Builtin::BI__builtin_nans:
13892   case Builtin::BI__builtin_nansf:
13893   case Builtin::BI__builtin_nansl:
13894   case Builtin::BI__builtin_nansf16:
13895   case Builtin::BI__builtin_nansf128:
13896     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13897                                true, Result))
13898       return Error(E);
13899     return true;
13900 
13901   case Builtin::BI__builtin_nan:
13902   case Builtin::BI__builtin_nanf:
13903   case Builtin::BI__builtin_nanl:
13904   case Builtin::BI__builtin_nanf16:
13905   case Builtin::BI__builtin_nanf128:
13906     // If this is __builtin_nan() turn this into a nan, otherwise we
13907     // can't constant fold it.
13908     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13909                                false, Result))
13910       return Error(E);
13911     return true;
13912 
13913   case Builtin::BI__builtin_fabs:
13914   case Builtin::BI__builtin_fabsf:
13915   case Builtin::BI__builtin_fabsl:
13916   case Builtin::BI__builtin_fabsf128:
13917     // The C standard says "fabs raises no floating-point exceptions,
13918     // even if x is a signaling NaN. The returned value is independent of
13919     // the current rounding direction mode."  Therefore constant folding can
13920     // proceed without regard to the floating point settings.
13921     // Reference, WG14 N2478 F.10.4.3
13922     if (!EvaluateFloat(E->getArg(0), Result, Info))
13923       return false;
13924 
13925     if (Result.isNegative())
13926       Result.changeSign();
13927     return true;
13928 
13929   case Builtin::BI__arithmetic_fence:
13930     return EvaluateFloat(E->getArg(0), Result, Info);
13931 
13932   // FIXME: Builtin::BI__builtin_powi
13933   // FIXME: Builtin::BI__builtin_powif
13934   // FIXME: Builtin::BI__builtin_powil
13935 
13936   case Builtin::BI__builtin_copysign:
13937   case Builtin::BI__builtin_copysignf:
13938   case Builtin::BI__builtin_copysignl:
13939   case Builtin::BI__builtin_copysignf128: {
13940     APFloat RHS(0.);
13941     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13942         !EvaluateFloat(E->getArg(1), RHS, Info))
13943       return false;
13944     Result.copySign(RHS);
13945     return true;
13946   }
13947   }
13948 }
13949 
13950 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13951   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13952     ComplexValue CV;
13953     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13954       return false;
13955     Result = CV.FloatReal;
13956     return true;
13957   }
13958 
13959   return Visit(E->getSubExpr());
13960 }
13961 
13962 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13963   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13964     ComplexValue CV;
13965     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13966       return false;
13967     Result = CV.FloatImag;
13968     return true;
13969   }
13970 
13971   VisitIgnoredValue(E->getSubExpr());
13972   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13973   Result = llvm::APFloat::getZero(Sem);
13974   return true;
13975 }
13976 
13977 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13978   switch (E->getOpcode()) {
13979   default: return Error(E);
13980   case UO_Plus:
13981     return EvaluateFloat(E->getSubExpr(), Result, Info);
13982   case UO_Minus:
13983     // In C standard, WG14 N2478 F.3 p4
13984     // "the unary - raises no floating point exceptions,
13985     // even if the operand is signalling."
13986     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13987       return false;
13988     Result.changeSign();
13989     return true;
13990   }
13991 }
13992 
13993 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13994   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13995     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13996 
13997   APFloat RHS(0.0);
13998   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13999   if (!LHSOK && !Info.noteFailure())
14000     return false;
14001   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14002          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14003 }
14004 
14005 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14006   Result = E->getValue();
14007   return true;
14008 }
14009 
14010 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14011   const Expr* SubExpr = E->getSubExpr();
14012 
14013   switch (E->getCastKind()) {
14014   default:
14015     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14016 
14017   case CK_IntegralToFloating: {
14018     APSInt IntResult;
14019     const FPOptions FPO = E->getFPFeaturesInEffect(
14020                                   Info.Ctx.getLangOpts());
14021     return EvaluateInteger(SubExpr, IntResult, Info) &&
14022            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14023                                 IntResult, E->getType(), Result);
14024   }
14025 
14026   case CK_FixedPointToFloating: {
14027     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14028     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14029       return false;
14030     Result =
14031         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14032     return true;
14033   }
14034 
14035   case CK_FloatingCast: {
14036     if (!Visit(SubExpr))
14037       return false;
14038     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14039                                   Result);
14040   }
14041 
14042   case CK_FloatingComplexToReal: {
14043     ComplexValue V;
14044     if (!EvaluateComplex(SubExpr, V, Info))
14045       return false;
14046     Result = V.getComplexFloatReal();
14047     return true;
14048   }
14049   }
14050 }
14051 
14052 //===----------------------------------------------------------------------===//
14053 // Complex Evaluation (for float and integer)
14054 //===----------------------------------------------------------------------===//
14055 
14056 namespace {
14057 class ComplexExprEvaluator
14058   : public ExprEvaluatorBase<ComplexExprEvaluator> {
14059   ComplexValue &Result;
14060 
14061 public:
14062   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14063     : ExprEvaluatorBaseTy(info), Result(Result) {}
14064 
14065   bool Success(const APValue &V, const Expr *e) {
14066     Result.setFrom(V);
14067     return true;
14068   }
14069 
14070   bool ZeroInitialization(const Expr *E);
14071 
14072   //===--------------------------------------------------------------------===//
14073   //                            Visitor Methods
14074   //===--------------------------------------------------------------------===//
14075 
14076   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14077   bool VisitCastExpr(const CastExpr *E);
14078   bool VisitBinaryOperator(const BinaryOperator *E);
14079   bool VisitUnaryOperator(const UnaryOperator *E);
14080   bool VisitInitListExpr(const InitListExpr *E);
14081   bool VisitCallExpr(const CallExpr *E);
14082 };
14083 } // end anonymous namespace
14084 
14085 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14086                             EvalInfo &Info) {
14087   assert(!E->isValueDependent());
14088   assert(E->isPRValue() && E->getType()->isAnyComplexType());
14089   return ComplexExprEvaluator(Info, Result).Visit(E);
14090 }
14091 
14092 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14093   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14094   if (ElemTy->isRealFloatingType()) {
14095     Result.makeComplexFloat();
14096     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14097     Result.FloatReal = Zero;
14098     Result.FloatImag = Zero;
14099   } else {
14100     Result.makeComplexInt();
14101     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14102     Result.IntReal = Zero;
14103     Result.IntImag = Zero;
14104   }
14105   return true;
14106 }
14107 
14108 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14109   const Expr* SubExpr = E->getSubExpr();
14110 
14111   if (SubExpr->getType()->isRealFloatingType()) {
14112     Result.makeComplexFloat();
14113     APFloat &Imag = Result.FloatImag;
14114     if (!EvaluateFloat(SubExpr, Imag, Info))
14115       return false;
14116 
14117     Result.FloatReal = APFloat(Imag.getSemantics());
14118     return true;
14119   } else {
14120     assert(SubExpr->getType()->isIntegerType() &&
14121            "Unexpected imaginary literal.");
14122 
14123     Result.makeComplexInt();
14124     APSInt &Imag = Result.IntImag;
14125     if (!EvaluateInteger(SubExpr, Imag, Info))
14126       return false;
14127 
14128     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14129     return true;
14130   }
14131 }
14132 
14133 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14134 
14135   switch (E->getCastKind()) {
14136   case CK_BitCast:
14137   case CK_BaseToDerived:
14138   case CK_DerivedToBase:
14139   case CK_UncheckedDerivedToBase:
14140   case CK_Dynamic:
14141   case CK_ToUnion:
14142   case CK_ArrayToPointerDecay:
14143   case CK_FunctionToPointerDecay:
14144   case CK_NullToPointer:
14145   case CK_NullToMemberPointer:
14146   case CK_BaseToDerivedMemberPointer:
14147   case CK_DerivedToBaseMemberPointer:
14148   case CK_MemberPointerToBoolean:
14149   case CK_ReinterpretMemberPointer:
14150   case CK_ConstructorConversion:
14151   case CK_IntegralToPointer:
14152   case CK_PointerToIntegral:
14153   case CK_PointerToBoolean:
14154   case CK_ToVoid:
14155   case CK_VectorSplat:
14156   case CK_IntegralCast:
14157   case CK_BooleanToSignedIntegral:
14158   case CK_IntegralToBoolean:
14159   case CK_IntegralToFloating:
14160   case CK_FloatingToIntegral:
14161   case CK_FloatingToBoolean:
14162   case CK_FloatingCast:
14163   case CK_CPointerToObjCPointerCast:
14164   case CK_BlockPointerToObjCPointerCast:
14165   case CK_AnyPointerToBlockPointerCast:
14166   case CK_ObjCObjectLValueCast:
14167   case CK_FloatingComplexToReal:
14168   case CK_FloatingComplexToBoolean:
14169   case CK_IntegralComplexToReal:
14170   case CK_IntegralComplexToBoolean:
14171   case CK_ARCProduceObject:
14172   case CK_ARCConsumeObject:
14173   case CK_ARCReclaimReturnedObject:
14174   case CK_ARCExtendBlockObject:
14175   case CK_CopyAndAutoreleaseBlockObject:
14176   case CK_BuiltinFnToFnPtr:
14177   case CK_ZeroToOCLOpaqueType:
14178   case CK_NonAtomicToAtomic:
14179   case CK_AddressSpaceConversion:
14180   case CK_IntToOCLSampler:
14181   case CK_FloatingToFixedPoint:
14182   case CK_FixedPointToFloating:
14183   case CK_FixedPointCast:
14184   case CK_FixedPointToBoolean:
14185   case CK_FixedPointToIntegral:
14186   case CK_IntegralToFixedPoint:
14187   case CK_MatrixCast:
14188     llvm_unreachable("invalid cast kind for complex value");
14189 
14190   case CK_LValueToRValue:
14191   case CK_AtomicToNonAtomic:
14192   case CK_NoOp:
14193   case CK_LValueToRValueBitCast:
14194     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14195 
14196   case CK_Dependent:
14197   case CK_LValueBitCast:
14198   case CK_UserDefinedConversion:
14199     return Error(E);
14200 
14201   case CK_FloatingRealToComplex: {
14202     APFloat &Real = Result.FloatReal;
14203     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14204       return false;
14205 
14206     Result.makeComplexFloat();
14207     Result.FloatImag = APFloat(Real.getSemantics());
14208     return true;
14209   }
14210 
14211   case CK_FloatingComplexCast: {
14212     if (!Visit(E->getSubExpr()))
14213       return false;
14214 
14215     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14216     QualType From
14217       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14218 
14219     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14220            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14221   }
14222 
14223   case CK_FloatingComplexToIntegralComplex: {
14224     if (!Visit(E->getSubExpr()))
14225       return false;
14226 
14227     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14228     QualType From
14229       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14230     Result.makeComplexInt();
14231     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14232                                 To, Result.IntReal) &&
14233            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14234                                 To, Result.IntImag);
14235   }
14236 
14237   case CK_IntegralRealToComplex: {
14238     APSInt &Real = Result.IntReal;
14239     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14240       return false;
14241 
14242     Result.makeComplexInt();
14243     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14244     return true;
14245   }
14246 
14247   case CK_IntegralComplexCast: {
14248     if (!Visit(E->getSubExpr()))
14249       return false;
14250 
14251     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14252     QualType From
14253       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14254 
14255     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14256     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14257     return true;
14258   }
14259 
14260   case CK_IntegralComplexToFloatingComplex: {
14261     if (!Visit(E->getSubExpr()))
14262       return false;
14263 
14264     const FPOptions FPO = E->getFPFeaturesInEffect(
14265                                   Info.Ctx.getLangOpts());
14266     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14267     QualType From
14268       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14269     Result.makeComplexFloat();
14270     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14271                                 To, Result.FloatReal) &&
14272            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14273                                 To, Result.FloatImag);
14274   }
14275   }
14276 
14277   llvm_unreachable("unknown cast resulting in complex value");
14278 }
14279 
14280 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14281   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14282     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14283 
14284   // Track whether the LHS or RHS is real at the type system level. When this is
14285   // the case we can simplify our evaluation strategy.
14286   bool LHSReal = false, RHSReal = false;
14287 
14288   bool LHSOK;
14289   if (E->getLHS()->getType()->isRealFloatingType()) {
14290     LHSReal = true;
14291     APFloat &Real = Result.FloatReal;
14292     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14293     if (LHSOK) {
14294       Result.makeComplexFloat();
14295       Result.FloatImag = APFloat(Real.getSemantics());
14296     }
14297   } else {
14298     LHSOK = Visit(E->getLHS());
14299   }
14300   if (!LHSOK && !Info.noteFailure())
14301     return false;
14302 
14303   ComplexValue RHS;
14304   if (E->getRHS()->getType()->isRealFloatingType()) {
14305     RHSReal = true;
14306     APFloat &Real = RHS.FloatReal;
14307     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14308       return false;
14309     RHS.makeComplexFloat();
14310     RHS.FloatImag = APFloat(Real.getSemantics());
14311   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14312     return false;
14313 
14314   assert(!(LHSReal && RHSReal) &&
14315          "Cannot have both operands of a complex operation be real.");
14316   switch (E->getOpcode()) {
14317   default: return Error(E);
14318   case BO_Add:
14319     if (Result.isComplexFloat()) {
14320       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14321                                        APFloat::rmNearestTiesToEven);
14322       if (LHSReal)
14323         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14324       else if (!RHSReal)
14325         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14326                                          APFloat::rmNearestTiesToEven);
14327     } else {
14328       Result.getComplexIntReal() += RHS.getComplexIntReal();
14329       Result.getComplexIntImag() += RHS.getComplexIntImag();
14330     }
14331     break;
14332   case BO_Sub:
14333     if (Result.isComplexFloat()) {
14334       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14335                                             APFloat::rmNearestTiesToEven);
14336       if (LHSReal) {
14337         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14338         Result.getComplexFloatImag().changeSign();
14339       } else if (!RHSReal) {
14340         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14341                                               APFloat::rmNearestTiesToEven);
14342       }
14343     } else {
14344       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14345       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14346     }
14347     break;
14348   case BO_Mul:
14349     if (Result.isComplexFloat()) {
14350       // This is an implementation of complex multiplication according to the
14351       // constraints laid out in C11 Annex G. The implementation uses the
14352       // following naming scheme:
14353       //   (a + ib) * (c + id)
14354       ComplexValue LHS = Result;
14355       APFloat &A = LHS.getComplexFloatReal();
14356       APFloat &B = LHS.getComplexFloatImag();
14357       APFloat &C = RHS.getComplexFloatReal();
14358       APFloat &D = RHS.getComplexFloatImag();
14359       APFloat &ResR = Result.getComplexFloatReal();
14360       APFloat &ResI = Result.getComplexFloatImag();
14361       if (LHSReal) {
14362         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14363         ResR = A * C;
14364         ResI = A * D;
14365       } else if (RHSReal) {
14366         ResR = C * A;
14367         ResI = C * B;
14368       } else {
14369         // In the fully general case, we need to handle NaNs and infinities
14370         // robustly.
14371         APFloat AC = A * C;
14372         APFloat BD = B * D;
14373         APFloat AD = A * D;
14374         APFloat BC = B * C;
14375         ResR = AC - BD;
14376         ResI = AD + BC;
14377         if (ResR.isNaN() && ResI.isNaN()) {
14378           bool Recalc = false;
14379           if (A.isInfinity() || B.isInfinity()) {
14380             A = APFloat::copySign(
14381                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14382             B = APFloat::copySign(
14383                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14384             if (C.isNaN())
14385               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14386             if (D.isNaN())
14387               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14388             Recalc = true;
14389           }
14390           if (C.isInfinity() || D.isInfinity()) {
14391             C = APFloat::copySign(
14392                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14393             D = APFloat::copySign(
14394                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14395             if (A.isNaN())
14396               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14397             if (B.isNaN())
14398               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14399             Recalc = true;
14400           }
14401           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14402                           AD.isInfinity() || BC.isInfinity())) {
14403             if (A.isNaN())
14404               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14405             if (B.isNaN())
14406               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14407             if (C.isNaN())
14408               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14409             if (D.isNaN())
14410               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14411             Recalc = true;
14412           }
14413           if (Recalc) {
14414             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14415             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14416           }
14417         }
14418       }
14419     } else {
14420       ComplexValue LHS = Result;
14421       Result.getComplexIntReal() =
14422         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14423          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14424       Result.getComplexIntImag() =
14425         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14426          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14427     }
14428     break;
14429   case BO_Div:
14430     if (Result.isComplexFloat()) {
14431       // This is an implementation of complex division according to the
14432       // constraints laid out in C11 Annex G. The implementation uses the
14433       // following naming scheme:
14434       //   (a + ib) / (c + id)
14435       ComplexValue LHS = Result;
14436       APFloat &A = LHS.getComplexFloatReal();
14437       APFloat &B = LHS.getComplexFloatImag();
14438       APFloat &C = RHS.getComplexFloatReal();
14439       APFloat &D = RHS.getComplexFloatImag();
14440       APFloat &ResR = Result.getComplexFloatReal();
14441       APFloat &ResI = Result.getComplexFloatImag();
14442       if (RHSReal) {
14443         ResR = A / C;
14444         ResI = B / C;
14445       } else {
14446         if (LHSReal) {
14447           // No real optimizations we can do here, stub out with zero.
14448           B = APFloat::getZero(A.getSemantics());
14449         }
14450         int DenomLogB = 0;
14451         APFloat MaxCD = maxnum(abs(C), abs(D));
14452         if (MaxCD.isFinite()) {
14453           DenomLogB = ilogb(MaxCD);
14454           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14455           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14456         }
14457         APFloat Denom = C * C + D * D;
14458         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14459                       APFloat::rmNearestTiesToEven);
14460         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14461                       APFloat::rmNearestTiesToEven);
14462         if (ResR.isNaN() && ResI.isNaN()) {
14463           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14464             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14465             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14466           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14467                      D.isFinite()) {
14468             A = APFloat::copySign(
14469                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14470             B = APFloat::copySign(
14471                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14472             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14473             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14474           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14475             C = APFloat::copySign(
14476                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14477             D = APFloat::copySign(
14478                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14479             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14480             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14481           }
14482         }
14483       }
14484     } else {
14485       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14486         return Error(E, diag::note_expr_divide_by_zero);
14487 
14488       ComplexValue LHS = Result;
14489       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14490         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14491       Result.getComplexIntReal() =
14492         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14493          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14494       Result.getComplexIntImag() =
14495         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14496          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14497     }
14498     break;
14499   }
14500 
14501   return true;
14502 }
14503 
14504 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14505   // Get the operand value into 'Result'.
14506   if (!Visit(E->getSubExpr()))
14507     return false;
14508 
14509   switch (E->getOpcode()) {
14510   default:
14511     return Error(E);
14512   case UO_Extension:
14513     return true;
14514   case UO_Plus:
14515     // The result is always just the subexpr.
14516     return true;
14517   case UO_Minus:
14518     if (Result.isComplexFloat()) {
14519       Result.getComplexFloatReal().changeSign();
14520       Result.getComplexFloatImag().changeSign();
14521     }
14522     else {
14523       Result.getComplexIntReal() = -Result.getComplexIntReal();
14524       Result.getComplexIntImag() = -Result.getComplexIntImag();
14525     }
14526     return true;
14527   case UO_Not:
14528     if (Result.isComplexFloat())
14529       Result.getComplexFloatImag().changeSign();
14530     else
14531       Result.getComplexIntImag() = -Result.getComplexIntImag();
14532     return true;
14533   }
14534 }
14535 
14536 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14537   if (E->getNumInits() == 2) {
14538     if (E->getType()->isComplexType()) {
14539       Result.makeComplexFloat();
14540       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14541         return false;
14542       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14543         return false;
14544     } else {
14545       Result.makeComplexInt();
14546       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14547         return false;
14548       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14549         return false;
14550     }
14551     return true;
14552   }
14553   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14554 }
14555 
14556 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14557   switch (E->getBuiltinCallee()) {
14558   case Builtin::BI__builtin_complex:
14559     Result.makeComplexFloat();
14560     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14561       return false;
14562     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14563       return false;
14564     return true;
14565 
14566   default:
14567     break;
14568   }
14569 
14570   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14571 }
14572 
14573 //===----------------------------------------------------------------------===//
14574 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14575 // implicit conversion.
14576 //===----------------------------------------------------------------------===//
14577 
14578 namespace {
14579 class AtomicExprEvaluator :
14580     public ExprEvaluatorBase<AtomicExprEvaluator> {
14581   const LValue *This;
14582   APValue &Result;
14583 public:
14584   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14585       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14586 
14587   bool Success(const APValue &V, const Expr *E) {
14588     Result = V;
14589     return true;
14590   }
14591 
14592   bool ZeroInitialization(const Expr *E) {
14593     ImplicitValueInitExpr VIE(
14594         E->getType()->castAs<AtomicType>()->getValueType());
14595     // For atomic-qualified class (and array) types in C++, initialize the
14596     // _Atomic-wrapped subobject directly, in-place.
14597     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14598                 : Evaluate(Result, Info, &VIE);
14599   }
14600 
14601   bool VisitCastExpr(const CastExpr *E) {
14602     switch (E->getCastKind()) {
14603     default:
14604       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14605     case CK_NonAtomicToAtomic:
14606       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14607                   : Evaluate(Result, Info, E->getSubExpr());
14608     }
14609   }
14610 };
14611 } // end anonymous namespace
14612 
14613 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14614                            EvalInfo &Info) {
14615   assert(!E->isValueDependent());
14616   assert(E->isPRValue() && E->getType()->isAtomicType());
14617   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14618 }
14619 
14620 //===----------------------------------------------------------------------===//
14621 // Void expression evaluation, primarily for a cast to void on the LHS of a
14622 // comma operator
14623 //===----------------------------------------------------------------------===//
14624 
14625 namespace {
14626 class VoidExprEvaluator
14627   : public ExprEvaluatorBase<VoidExprEvaluator> {
14628 public:
14629   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14630 
14631   bool Success(const APValue &V, const Expr *e) { return true; }
14632 
14633   bool ZeroInitialization(const Expr *E) { return true; }
14634 
14635   bool VisitCastExpr(const CastExpr *E) {
14636     switch (E->getCastKind()) {
14637     default:
14638       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14639     case CK_ToVoid:
14640       VisitIgnoredValue(E->getSubExpr());
14641       return true;
14642     }
14643   }
14644 
14645   bool VisitCallExpr(const CallExpr *E) {
14646     switch (E->getBuiltinCallee()) {
14647     case Builtin::BI__assume:
14648     case Builtin::BI__builtin_assume:
14649       // The argument is not evaluated!
14650       return true;
14651 
14652     case Builtin::BI__builtin_operator_delete:
14653       return HandleOperatorDeleteCall(Info, E);
14654 
14655     default:
14656       break;
14657     }
14658 
14659     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14660   }
14661 
14662   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14663 };
14664 } // end anonymous namespace
14665 
14666 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14667   // We cannot speculatively evaluate a delete expression.
14668   if (Info.SpeculativeEvaluationDepth)
14669     return false;
14670 
14671   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14672   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14673     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14674         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14675     return false;
14676   }
14677 
14678   const Expr *Arg = E->getArgument();
14679 
14680   LValue Pointer;
14681   if (!EvaluatePointer(Arg, Pointer, Info))
14682     return false;
14683   if (Pointer.Designator.Invalid)
14684     return false;
14685 
14686   // Deleting a null pointer has no effect.
14687   if (Pointer.isNullPointer()) {
14688     // This is the only case where we need to produce an extension warning:
14689     // the only other way we can succeed is if we find a dynamic allocation,
14690     // and we will have warned when we allocated it in that case.
14691     if (!Info.getLangOpts().CPlusPlus20)
14692       Info.CCEDiag(E, diag::note_constexpr_new);
14693     return true;
14694   }
14695 
14696   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14697       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14698   if (!Alloc)
14699     return false;
14700   QualType AllocType = Pointer.Base.getDynamicAllocType();
14701 
14702   // For the non-array case, the designator must be empty if the static type
14703   // does not have a virtual destructor.
14704   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14705       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14706     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14707         << Arg->getType()->getPointeeType() << AllocType;
14708     return false;
14709   }
14710 
14711   // For a class type with a virtual destructor, the selected operator delete
14712   // is the one looked up when building the destructor.
14713   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14714     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14715     if (VirtualDelete &&
14716         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14717       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14718           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14719       return false;
14720     }
14721   }
14722 
14723   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14724                          (*Alloc)->Value, AllocType))
14725     return false;
14726 
14727   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14728     // The element was already erased. This means the destructor call also
14729     // deleted the object.
14730     // FIXME: This probably results in undefined behavior before we get this
14731     // far, and should be diagnosed elsewhere first.
14732     Info.FFDiag(E, diag::note_constexpr_double_delete);
14733     return false;
14734   }
14735 
14736   return true;
14737 }
14738 
14739 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14740   assert(!E->isValueDependent());
14741   assert(E->isPRValue() && E->getType()->isVoidType());
14742   return VoidExprEvaluator(Info).Visit(E);
14743 }
14744 
14745 //===----------------------------------------------------------------------===//
14746 // Top level Expr::EvaluateAsRValue method.
14747 //===----------------------------------------------------------------------===//
14748 
14749 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14750   assert(!E->isValueDependent());
14751   // In C, function designators are not lvalues, but we evaluate them as if they
14752   // are.
14753   QualType T = E->getType();
14754   if (E->isGLValue() || T->isFunctionType()) {
14755     LValue LV;
14756     if (!EvaluateLValue(E, LV, Info))
14757       return false;
14758     LV.moveInto(Result);
14759   } else if (T->isVectorType()) {
14760     if (!EvaluateVector(E, Result, Info))
14761       return false;
14762   } else if (T->isIntegralOrEnumerationType()) {
14763     if (!IntExprEvaluator(Info, Result).Visit(E))
14764       return false;
14765   } else if (T->hasPointerRepresentation()) {
14766     LValue LV;
14767     if (!EvaluatePointer(E, LV, Info))
14768       return false;
14769     LV.moveInto(Result);
14770   } else if (T->isRealFloatingType()) {
14771     llvm::APFloat F(0.0);
14772     if (!EvaluateFloat(E, F, Info))
14773       return false;
14774     Result = APValue(F);
14775   } else if (T->isAnyComplexType()) {
14776     ComplexValue C;
14777     if (!EvaluateComplex(E, C, Info))
14778       return false;
14779     C.moveInto(Result);
14780   } else if (T->isFixedPointType()) {
14781     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14782   } else if (T->isMemberPointerType()) {
14783     MemberPtr P;
14784     if (!EvaluateMemberPointer(E, P, Info))
14785       return false;
14786     P.moveInto(Result);
14787     return true;
14788   } else if (T->isArrayType()) {
14789     LValue LV;
14790     APValue &Value =
14791         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14792     if (!EvaluateArray(E, LV, Value, Info))
14793       return false;
14794     Result = Value;
14795   } else if (T->isRecordType()) {
14796     LValue LV;
14797     APValue &Value =
14798         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14799     if (!EvaluateRecord(E, LV, Value, Info))
14800       return false;
14801     Result = Value;
14802   } else if (T->isVoidType()) {
14803     if (!Info.getLangOpts().CPlusPlus11)
14804       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14805         << E->getType();
14806     if (!EvaluateVoid(E, Info))
14807       return false;
14808   } else if (T->isAtomicType()) {
14809     QualType Unqual = T.getAtomicUnqualifiedType();
14810     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14811       LValue LV;
14812       APValue &Value = Info.CurrentCall->createTemporary(
14813           E, Unqual, ScopeKind::FullExpression, LV);
14814       if (!EvaluateAtomic(E, &LV, Value, Info))
14815         return false;
14816     } else {
14817       if (!EvaluateAtomic(E, nullptr, Result, Info))
14818         return false;
14819     }
14820   } else if (Info.getLangOpts().CPlusPlus11) {
14821     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14822     return false;
14823   } else {
14824     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14825     return false;
14826   }
14827 
14828   return true;
14829 }
14830 
14831 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14832 /// cases, the in-place evaluation is essential, since later initializers for
14833 /// an object can indirectly refer to subobjects which were initialized earlier.
14834 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14835                             const Expr *E, bool AllowNonLiteralTypes) {
14836   assert(!E->isValueDependent());
14837 
14838   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14839     return false;
14840 
14841   if (E->isPRValue()) {
14842     // Evaluate arrays and record types in-place, so that later initializers can
14843     // refer to earlier-initialized members of the object.
14844     QualType T = E->getType();
14845     if (T->isArrayType())
14846       return EvaluateArray(E, This, Result, Info);
14847     else if (T->isRecordType())
14848       return EvaluateRecord(E, This, Result, Info);
14849     else if (T->isAtomicType()) {
14850       QualType Unqual = T.getAtomicUnqualifiedType();
14851       if (Unqual->isArrayType() || Unqual->isRecordType())
14852         return EvaluateAtomic(E, &This, Result, Info);
14853     }
14854   }
14855 
14856   // For any other type, in-place evaluation is unimportant.
14857   return Evaluate(Result, Info, E);
14858 }
14859 
14860 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14861 /// lvalue-to-rvalue cast if it is an lvalue.
14862 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14863   assert(!E->isValueDependent());
14864   if (Info.EnableNewConstInterp) {
14865     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14866       return false;
14867   } else {
14868     if (E->getType().isNull())
14869       return false;
14870 
14871     if (!CheckLiteralType(Info, E))
14872       return false;
14873 
14874     if (!::Evaluate(Result, Info, E))
14875       return false;
14876 
14877     if (E->isGLValue()) {
14878       LValue LV;
14879       LV.setFrom(Info.Ctx, Result);
14880       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14881         return false;
14882     }
14883   }
14884 
14885   // Check this core constant expression is a constant expression.
14886   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14887                                  ConstantExprKind::Normal) &&
14888          CheckMemoryLeaks(Info);
14889 }
14890 
14891 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14892                                  const ASTContext &Ctx, bool &IsConst) {
14893   // Fast-path evaluations of integer literals, since we sometimes see files
14894   // containing vast quantities of these.
14895   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14896     Result.Val = APValue(APSInt(L->getValue(),
14897                                 L->getType()->isUnsignedIntegerType()));
14898     IsConst = true;
14899     return true;
14900   }
14901 
14902   // This case should be rare, but we need to check it before we check on
14903   // the type below.
14904   if (Exp->getType().isNull()) {
14905     IsConst = false;
14906     return true;
14907   }
14908 
14909   // FIXME: Evaluating values of large array and record types can cause
14910   // performance problems. Only do so in C++11 for now.
14911   if (Exp->isPRValue() &&
14912       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14913       !Ctx.getLangOpts().CPlusPlus11) {
14914     IsConst = false;
14915     return true;
14916   }
14917   return false;
14918 }
14919 
14920 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14921                                       Expr::SideEffectsKind SEK) {
14922   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14923          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14924 }
14925 
14926 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14927                              const ASTContext &Ctx, EvalInfo &Info) {
14928   assert(!E->isValueDependent());
14929   bool IsConst;
14930   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14931     return IsConst;
14932 
14933   return EvaluateAsRValue(Info, E, Result.Val);
14934 }
14935 
14936 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14937                           const ASTContext &Ctx,
14938                           Expr::SideEffectsKind AllowSideEffects,
14939                           EvalInfo &Info) {
14940   assert(!E->isValueDependent());
14941   if (!E->getType()->isIntegralOrEnumerationType())
14942     return false;
14943 
14944   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14945       !ExprResult.Val.isInt() ||
14946       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14947     return false;
14948 
14949   return true;
14950 }
14951 
14952 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14953                                  const ASTContext &Ctx,
14954                                  Expr::SideEffectsKind AllowSideEffects,
14955                                  EvalInfo &Info) {
14956   assert(!E->isValueDependent());
14957   if (!E->getType()->isFixedPointType())
14958     return false;
14959 
14960   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14961     return false;
14962 
14963   if (!ExprResult.Val.isFixedPoint() ||
14964       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14965     return false;
14966 
14967   return true;
14968 }
14969 
14970 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14971 /// any crazy technique (that has nothing to do with language standards) that
14972 /// we want to.  If this function returns true, it returns the folded constant
14973 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14974 /// will be applied to the result.
14975 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14976                             bool InConstantContext) const {
14977   assert(!isValueDependent() &&
14978          "Expression evaluator can't be called on a dependent expression.");
14979   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14980   Info.InConstantContext = InConstantContext;
14981   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14982 }
14983 
14984 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14985                                       bool InConstantContext) const {
14986   assert(!isValueDependent() &&
14987          "Expression evaluator can't be called on a dependent expression.");
14988   EvalResult Scratch;
14989   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14990          HandleConversionToBool(Scratch.Val, Result);
14991 }
14992 
14993 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14994                          SideEffectsKind AllowSideEffects,
14995                          bool InConstantContext) const {
14996   assert(!isValueDependent() &&
14997          "Expression evaluator can't be called on a dependent expression.");
14998   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14999   Info.InConstantContext = InConstantContext;
15000   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15001 }
15002 
15003 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15004                                 SideEffectsKind AllowSideEffects,
15005                                 bool InConstantContext) const {
15006   assert(!isValueDependent() &&
15007          "Expression evaluator can't be called on a dependent expression.");
15008   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15009   Info.InConstantContext = InConstantContext;
15010   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15011 }
15012 
15013 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15014                            SideEffectsKind AllowSideEffects,
15015                            bool InConstantContext) const {
15016   assert(!isValueDependent() &&
15017          "Expression evaluator can't be called on a dependent expression.");
15018 
15019   if (!getType()->isRealFloatingType())
15020     return false;
15021 
15022   EvalResult ExprResult;
15023   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15024       !ExprResult.Val.isFloat() ||
15025       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15026     return false;
15027 
15028   Result = ExprResult.Val.getFloat();
15029   return true;
15030 }
15031 
15032 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15033                             bool InConstantContext) const {
15034   assert(!isValueDependent() &&
15035          "Expression evaluator can't be called on a dependent expression.");
15036 
15037   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15038   Info.InConstantContext = InConstantContext;
15039   LValue LV;
15040   CheckedTemporaries CheckedTemps;
15041   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15042       Result.HasSideEffects ||
15043       !CheckLValueConstantExpression(Info, getExprLoc(),
15044                                      Ctx.getLValueReferenceType(getType()), LV,
15045                                      ConstantExprKind::Normal, CheckedTemps))
15046     return false;
15047 
15048   LV.moveInto(Result.Val);
15049   return true;
15050 }
15051 
15052 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15053                                 APValue DestroyedValue, QualType Type,
15054                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
15055                                 bool IsConstantDestruction) {
15056   EvalInfo Info(Ctx, EStatus,
15057                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15058                                       : EvalInfo::EM_ConstantFold);
15059   Info.setEvaluatingDecl(Base, DestroyedValue,
15060                          EvalInfo::EvaluatingDeclKind::Dtor);
15061   Info.InConstantContext = IsConstantDestruction;
15062 
15063   LValue LVal;
15064   LVal.set(Base);
15065 
15066   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15067       EStatus.HasSideEffects)
15068     return false;
15069 
15070   if (!Info.discardCleanups())
15071     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15072 
15073   return true;
15074 }
15075 
15076 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15077                                   ConstantExprKind Kind) const {
15078   assert(!isValueDependent() &&
15079          "Expression evaluator can't be called on a dependent expression.");
15080 
15081   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15082   EvalInfo Info(Ctx, Result, EM);
15083   Info.InConstantContext = true;
15084 
15085   // The type of the object we're initializing is 'const T' for a class NTTP.
15086   QualType T = getType();
15087   if (Kind == ConstantExprKind::ClassTemplateArgument)
15088     T.addConst();
15089 
15090   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15091   // represent the result of the evaluation. CheckConstantExpression ensures
15092   // this doesn't escape.
15093   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15094   APValue::LValueBase Base(&BaseMTE);
15095 
15096   Info.setEvaluatingDecl(Base, Result.Val);
15097   LValue LVal;
15098   LVal.set(Base);
15099 
15100   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15101     return false;
15102 
15103   if (!Info.discardCleanups())
15104     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15105 
15106   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15107                                Result.Val, Kind))
15108     return false;
15109   if (!CheckMemoryLeaks(Info))
15110     return false;
15111 
15112   // If this is a class template argument, it's required to have constant
15113   // destruction too.
15114   if (Kind == ConstantExprKind::ClassTemplateArgument &&
15115       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15116                             true) ||
15117        Result.HasSideEffects)) {
15118     // FIXME: Prefix a note to indicate that the problem is lack of constant
15119     // destruction.
15120     return false;
15121   }
15122 
15123   return true;
15124 }
15125 
15126 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15127                                  const VarDecl *VD,
15128                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
15129                                  bool IsConstantInitialization) const {
15130   assert(!isValueDependent() &&
15131          "Expression evaluator can't be called on a dependent expression.");
15132 
15133   // FIXME: Evaluating initializers for large array and record types can cause
15134   // performance problems. Only do so in C++11 for now.
15135   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15136       !Ctx.getLangOpts().CPlusPlus11)
15137     return false;
15138 
15139   Expr::EvalStatus EStatus;
15140   EStatus.Diag = &Notes;
15141 
15142   EvalInfo Info(Ctx, EStatus,
15143                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15144                     ? EvalInfo::EM_ConstantExpression
15145                     : EvalInfo::EM_ConstantFold);
15146   Info.setEvaluatingDecl(VD, Value);
15147   Info.InConstantContext = IsConstantInitialization;
15148 
15149   SourceLocation DeclLoc = VD->getLocation();
15150   QualType DeclTy = VD->getType();
15151 
15152   if (Info.EnableNewConstInterp) {
15153     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15154     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15155       return false;
15156   } else {
15157     LValue LVal;
15158     LVal.set(VD);
15159 
15160     if (!EvaluateInPlace(Value, Info, LVal, this,
15161                          /*AllowNonLiteralTypes=*/true) ||
15162         EStatus.HasSideEffects)
15163       return false;
15164 
15165     // At this point, any lifetime-extended temporaries are completely
15166     // initialized.
15167     Info.performLifetimeExtension();
15168 
15169     if (!Info.discardCleanups())
15170       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15171   }
15172   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15173                                  ConstantExprKind::Normal) &&
15174          CheckMemoryLeaks(Info);
15175 }
15176 
15177 bool VarDecl::evaluateDestruction(
15178     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15179   Expr::EvalStatus EStatus;
15180   EStatus.Diag = &Notes;
15181 
15182   // Only treat the destruction as constant destruction if we formally have
15183   // constant initialization (or are usable in a constant expression).
15184   bool IsConstantDestruction = hasConstantInitialization();
15185 
15186   // Make a copy of the value for the destructor to mutate, if we know it.
15187   // Otherwise, treat the value as default-initialized; if the destructor works
15188   // anyway, then the destruction is constant (and must be essentially empty).
15189   APValue DestroyedValue;
15190   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15191     DestroyedValue = *getEvaluatedValue();
15192   else if (!getDefaultInitValue(getType(), DestroyedValue))
15193     return false;
15194 
15195   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15196                            getType(), getLocation(), EStatus,
15197                            IsConstantDestruction) ||
15198       EStatus.HasSideEffects)
15199     return false;
15200 
15201   ensureEvaluatedStmt()->HasConstantDestruction = true;
15202   return true;
15203 }
15204 
15205 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15206 /// constant folded, but discard the result.
15207 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15208   assert(!isValueDependent() &&
15209          "Expression evaluator can't be called on a dependent expression.");
15210 
15211   EvalResult Result;
15212   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15213          !hasUnacceptableSideEffect(Result, SEK);
15214 }
15215 
15216 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15217                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15218   assert(!isValueDependent() &&
15219          "Expression evaluator can't be called on a dependent expression.");
15220 
15221   EvalResult EVResult;
15222   EVResult.Diag = Diag;
15223   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15224   Info.InConstantContext = true;
15225 
15226   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15227   (void)Result;
15228   assert(Result && "Could not evaluate expression");
15229   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15230 
15231   return EVResult.Val.getInt();
15232 }
15233 
15234 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15235     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15236   assert(!isValueDependent() &&
15237          "Expression evaluator can't be called on a dependent expression.");
15238 
15239   EvalResult EVResult;
15240   EVResult.Diag = Diag;
15241   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15242   Info.InConstantContext = true;
15243   Info.CheckingForUndefinedBehavior = true;
15244 
15245   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15246   (void)Result;
15247   assert(Result && "Could not evaluate expression");
15248   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15249 
15250   return EVResult.Val.getInt();
15251 }
15252 
15253 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15254   assert(!isValueDependent() &&
15255          "Expression evaluator can't be called on a dependent expression.");
15256 
15257   bool IsConst;
15258   EvalResult EVResult;
15259   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15260     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15261     Info.CheckingForUndefinedBehavior = true;
15262     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15263   }
15264 }
15265 
15266 bool Expr::EvalResult::isGlobalLValue() const {
15267   assert(Val.isLValue());
15268   return IsGlobalLValue(Val.getLValueBase());
15269 }
15270 
15271 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15272 /// an integer constant expression.
15273 
15274 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15275 /// comma, etc
15276 
15277 // CheckICE - This function does the fundamental ICE checking: the returned
15278 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15279 // and a (possibly null) SourceLocation indicating the location of the problem.
15280 //
15281 // Note that to reduce code duplication, this helper does no evaluation
15282 // itself; the caller checks whether the expression is evaluatable, and
15283 // in the rare cases where CheckICE actually cares about the evaluated
15284 // value, it calls into Evaluate.
15285 
15286 namespace {
15287 
15288 enum ICEKind {
15289   /// This expression is an ICE.
15290   IK_ICE,
15291   /// This expression is not an ICE, but if it isn't evaluated, it's
15292   /// a legal subexpression for an ICE. This return value is used to handle
15293   /// the comma operator in C99 mode, and non-constant subexpressions.
15294   IK_ICEIfUnevaluated,
15295   /// This expression is not an ICE, and is not a legal subexpression for one.
15296   IK_NotICE
15297 };
15298 
15299 struct ICEDiag {
15300   ICEKind Kind;
15301   SourceLocation Loc;
15302 
15303   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15304 };
15305 
15306 }
15307 
15308 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15309 
15310 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15311 
15312 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15313   Expr::EvalResult EVResult;
15314   Expr::EvalStatus Status;
15315   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15316 
15317   Info.InConstantContext = true;
15318   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15319       !EVResult.Val.isInt())
15320     return ICEDiag(IK_NotICE, E->getBeginLoc());
15321 
15322   return NoDiag();
15323 }
15324 
15325 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15326   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15327   if (!E->getType()->isIntegralOrEnumerationType())
15328     return ICEDiag(IK_NotICE, E->getBeginLoc());
15329 
15330   switch (E->getStmtClass()) {
15331 #define ABSTRACT_STMT(Node)
15332 #define STMT(Node, Base) case Expr::Node##Class:
15333 #define EXPR(Node, Base)
15334 #include "clang/AST/StmtNodes.inc"
15335   case Expr::PredefinedExprClass:
15336   case Expr::FloatingLiteralClass:
15337   case Expr::ImaginaryLiteralClass:
15338   case Expr::StringLiteralClass:
15339   case Expr::ArraySubscriptExprClass:
15340   case Expr::MatrixSubscriptExprClass:
15341   case Expr::OMPArraySectionExprClass:
15342   case Expr::OMPArrayShapingExprClass:
15343   case Expr::OMPIteratorExprClass:
15344   case Expr::MemberExprClass:
15345   case Expr::CompoundAssignOperatorClass:
15346   case Expr::CompoundLiteralExprClass:
15347   case Expr::ExtVectorElementExprClass:
15348   case Expr::DesignatedInitExprClass:
15349   case Expr::ArrayInitLoopExprClass:
15350   case Expr::ArrayInitIndexExprClass:
15351   case Expr::NoInitExprClass:
15352   case Expr::DesignatedInitUpdateExprClass:
15353   case Expr::ImplicitValueInitExprClass:
15354   case Expr::ParenListExprClass:
15355   case Expr::VAArgExprClass:
15356   case Expr::AddrLabelExprClass:
15357   case Expr::StmtExprClass:
15358   case Expr::CXXMemberCallExprClass:
15359   case Expr::CUDAKernelCallExprClass:
15360   case Expr::CXXAddrspaceCastExprClass:
15361   case Expr::CXXDynamicCastExprClass:
15362   case Expr::CXXTypeidExprClass:
15363   case Expr::CXXUuidofExprClass:
15364   case Expr::MSPropertyRefExprClass:
15365   case Expr::MSPropertySubscriptExprClass:
15366   case Expr::CXXNullPtrLiteralExprClass:
15367   case Expr::UserDefinedLiteralClass:
15368   case Expr::CXXThisExprClass:
15369   case Expr::CXXThrowExprClass:
15370   case Expr::CXXNewExprClass:
15371   case Expr::CXXDeleteExprClass:
15372   case Expr::CXXPseudoDestructorExprClass:
15373   case Expr::UnresolvedLookupExprClass:
15374   case Expr::TypoExprClass:
15375   case Expr::RecoveryExprClass:
15376   case Expr::DependentScopeDeclRefExprClass:
15377   case Expr::CXXConstructExprClass:
15378   case Expr::CXXInheritedCtorInitExprClass:
15379   case Expr::CXXStdInitializerListExprClass:
15380   case Expr::CXXBindTemporaryExprClass:
15381   case Expr::ExprWithCleanupsClass:
15382   case Expr::CXXTemporaryObjectExprClass:
15383   case Expr::CXXUnresolvedConstructExprClass:
15384   case Expr::CXXDependentScopeMemberExprClass:
15385   case Expr::UnresolvedMemberExprClass:
15386   case Expr::ObjCStringLiteralClass:
15387   case Expr::ObjCBoxedExprClass:
15388   case Expr::ObjCArrayLiteralClass:
15389   case Expr::ObjCDictionaryLiteralClass:
15390   case Expr::ObjCEncodeExprClass:
15391   case Expr::ObjCMessageExprClass:
15392   case Expr::ObjCSelectorExprClass:
15393   case Expr::ObjCProtocolExprClass:
15394   case Expr::ObjCIvarRefExprClass:
15395   case Expr::ObjCPropertyRefExprClass:
15396   case Expr::ObjCSubscriptRefExprClass:
15397   case Expr::ObjCIsaExprClass:
15398   case Expr::ObjCAvailabilityCheckExprClass:
15399   case Expr::ShuffleVectorExprClass:
15400   case Expr::ConvertVectorExprClass:
15401   case Expr::BlockExprClass:
15402   case Expr::NoStmtClass:
15403   case Expr::OpaqueValueExprClass:
15404   case Expr::PackExpansionExprClass:
15405   case Expr::SubstNonTypeTemplateParmPackExprClass:
15406   case Expr::FunctionParmPackExprClass:
15407   case Expr::AsTypeExprClass:
15408   case Expr::ObjCIndirectCopyRestoreExprClass:
15409   case Expr::MaterializeTemporaryExprClass:
15410   case Expr::PseudoObjectExprClass:
15411   case Expr::AtomicExprClass:
15412   case Expr::LambdaExprClass:
15413   case Expr::CXXFoldExprClass:
15414   case Expr::CoawaitExprClass:
15415   case Expr::DependentCoawaitExprClass:
15416   case Expr::CoyieldExprClass:
15417   case Expr::SYCLUniqueStableNameExprClass:
15418     return ICEDiag(IK_NotICE, E->getBeginLoc());
15419 
15420   case Expr::InitListExprClass: {
15421     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15422     // form "T x = { a };" is equivalent to "T x = a;".
15423     // Unless we're initializing a reference, T is a scalar as it is known to be
15424     // of integral or enumeration type.
15425     if (E->isPRValue())
15426       if (cast<InitListExpr>(E)->getNumInits() == 1)
15427         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15428     return ICEDiag(IK_NotICE, E->getBeginLoc());
15429   }
15430 
15431   case Expr::SizeOfPackExprClass:
15432   case Expr::GNUNullExprClass:
15433   case Expr::SourceLocExprClass:
15434     return NoDiag();
15435 
15436   case Expr::SubstNonTypeTemplateParmExprClass:
15437     return
15438       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15439 
15440   case Expr::ConstantExprClass:
15441     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15442 
15443   case Expr::ParenExprClass:
15444     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15445   case Expr::GenericSelectionExprClass:
15446     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15447   case Expr::IntegerLiteralClass:
15448   case Expr::FixedPointLiteralClass:
15449   case Expr::CharacterLiteralClass:
15450   case Expr::ObjCBoolLiteralExprClass:
15451   case Expr::CXXBoolLiteralExprClass:
15452   case Expr::CXXScalarValueInitExprClass:
15453   case Expr::TypeTraitExprClass:
15454   case Expr::ConceptSpecializationExprClass:
15455   case Expr::RequiresExprClass:
15456   case Expr::ArrayTypeTraitExprClass:
15457   case Expr::ExpressionTraitExprClass:
15458   case Expr::CXXNoexceptExprClass:
15459     return NoDiag();
15460   case Expr::CallExprClass:
15461   case Expr::CXXOperatorCallExprClass: {
15462     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15463     // constant expressions, but they can never be ICEs because an ICE cannot
15464     // contain an operand of (pointer to) function type.
15465     const CallExpr *CE = cast<CallExpr>(E);
15466     if (CE->getBuiltinCallee())
15467       return CheckEvalInICE(E, Ctx);
15468     return ICEDiag(IK_NotICE, E->getBeginLoc());
15469   }
15470   case Expr::CXXRewrittenBinaryOperatorClass:
15471     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15472                     Ctx);
15473   case Expr::DeclRefExprClass: {
15474     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15475     if (isa<EnumConstantDecl>(D))
15476       return NoDiag();
15477 
15478     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15479     // integer variables in constant expressions:
15480     //
15481     // C++ 7.1.5.1p2
15482     //   A variable of non-volatile const-qualified integral or enumeration
15483     //   type initialized by an ICE can be used in ICEs.
15484     //
15485     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15486     // that mode, use of reference variables should not be allowed.
15487     const VarDecl *VD = dyn_cast<VarDecl>(D);
15488     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15489         !VD->getType()->isReferenceType())
15490       return NoDiag();
15491 
15492     return ICEDiag(IK_NotICE, E->getBeginLoc());
15493   }
15494   case Expr::UnaryOperatorClass: {
15495     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15496     switch (Exp->getOpcode()) {
15497     case UO_PostInc:
15498     case UO_PostDec:
15499     case UO_PreInc:
15500     case UO_PreDec:
15501     case UO_AddrOf:
15502     case UO_Deref:
15503     case UO_Coawait:
15504       // C99 6.6/3 allows increment and decrement within unevaluated
15505       // subexpressions of constant expressions, but they can never be ICEs
15506       // because an ICE cannot contain an lvalue operand.
15507       return ICEDiag(IK_NotICE, E->getBeginLoc());
15508     case UO_Extension:
15509     case UO_LNot:
15510     case UO_Plus:
15511     case UO_Minus:
15512     case UO_Not:
15513     case UO_Real:
15514     case UO_Imag:
15515       return CheckICE(Exp->getSubExpr(), Ctx);
15516     }
15517     llvm_unreachable("invalid unary operator class");
15518   }
15519   case Expr::OffsetOfExprClass: {
15520     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15521     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15522     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15523     // compliance: we should warn earlier for offsetof expressions with
15524     // array subscripts that aren't ICEs, and if the array subscripts
15525     // are ICEs, the value of the offsetof must be an integer constant.
15526     return CheckEvalInICE(E, Ctx);
15527   }
15528   case Expr::UnaryExprOrTypeTraitExprClass: {
15529     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15530     if ((Exp->getKind() ==  UETT_SizeOf) &&
15531         Exp->getTypeOfArgument()->isVariableArrayType())
15532       return ICEDiag(IK_NotICE, E->getBeginLoc());
15533     return NoDiag();
15534   }
15535   case Expr::BinaryOperatorClass: {
15536     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15537     switch (Exp->getOpcode()) {
15538     case BO_PtrMemD:
15539     case BO_PtrMemI:
15540     case BO_Assign:
15541     case BO_MulAssign:
15542     case BO_DivAssign:
15543     case BO_RemAssign:
15544     case BO_AddAssign:
15545     case BO_SubAssign:
15546     case BO_ShlAssign:
15547     case BO_ShrAssign:
15548     case BO_AndAssign:
15549     case BO_XorAssign:
15550     case BO_OrAssign:
15551       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15552       // constant expressions, but they can never be ICEs because an ICE cannot
15553       // contain an lvalue operand.
15554       return ICEDiag(IK_NotICE, E->getBeginLoc());
15555 
15556     case BO_Mul:
15557     case BO_Div:
15558     case BO_Rem:
15559     case BO_Add:
15560     case BO_Sub:
15561     case BO_Shl:
15562     case BO_Shr:
15563     case BO_LT:
15564     case BO_GT:
15565     case BO_LE:
15566     case BO_GE:
15567     case BO_EQ:
15568     case BO_NE:
15569     case BO_And:
15570     case BO_Xor:
15571     case BO_Or:
15572     case BO_Comma:
15573     case BO_Cmp: {
15574       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15575       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15576       if (Exp->getOpcode() == BO_Div ||
15577           Exp->getOpcode() == BO_Rem) {
15578         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15579         // we don't evaluate one.
15580         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15581           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15582           if (REval == 0)
15583             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15584           if (REval.isSigned() && REval.isAllOnes()) {
15585             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15586             if (LEval.isMinSignedValue())
15587               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15588           }
15589         }
15590       }
15591       if (Exp->getOpcode() == BO_Comma) {
15592         if (Ctx.getLangOpts().C99) {
15593           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15594           // if it isn't evaluated.
15595           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15596             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15597         } else {
15598           // In both C89 and C++, commas in ICEs are illegal.
15599           return ICEDiag(IK_NotICE, E->getBeginLoc());
15600         }
15601       }
15602       return Worst(LHSResult, RHSResult);
15603     }
15604     case BO_LAnd:
15605     case BO_LOr: {
15606       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15607       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15608       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15609         // Rare case where the RHS has a comma "side-effect"; we need
15610         // to actually check the condition to see whether the side
15611         // with the comma is evaluated.
15612         if ((Exp->getOpcode() == BO_LAnd) !=
15613             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15614           return RHSResult;
15615         return NoDiag();
15616       }
15617 
15618       return Worst(LHSResult, RHSResult);
15619     }
15620     }
15621     llvm_unreachable("invalid binary operator kind");
15622   }
15623   case Expr::ImplicitCastExprClass:
15624   case Expr::CStyleCastExprClass:
15625   case Expr::CXXFunctionalCastExprClass:
15626   case Expr::CXXStaticCastExprClass:
15627   case Expr::CXXReinterpretCastExprClass:
15628   case Expr::CXXConstCastExprClass:
15629   case Expr::ObjCBridgedCastExprClass: {
15630     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15631     if (isa<ExplicitCastExpr>(E)) {
15632       if (const FloatingLiteral *FL
15633             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15634         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15635         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15636         APSInt IgnoredVal(DestWidth, !DestSigned);
15637         bool Ignored;
15638         // If the value does not fit in the destination type, the behavior is
15639         // undefined, so we are not required to treat it as a constant
15640         // expression.
15641         if (FL->getValue().convertToInteger(IgnoredVal,
15642                                             llvm::APFloat::rmTowardZero,
15643                                             &Ignored) & APFloat::opInvalidOp)
15644           return ICEDiag(IK_NotICE, E->getBeginLoc());
15645         return NoDiag();
15646       }
15647     }
15648     switch (cast<CastExpr>(E)->getCastKind()) {
15649     case CK_LValueToRValue:
15650     case CK_AtomicToNonAtomic:
15651     case CK_NonAtomicToAtomic:
15652     case CK_NoOp:
15653     case CK_IntegralToBoolean:
15654     case CK_IntegralCast:
15655       return CheckICE(SubExpr, Ctx);
15656     default:
15657       return ICEDiag(IK_NotICE, E->getBeginLoc());
15658     }
15659   }
15660   case Expr::BinaryConditionalOperatorClass: {
15661     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15662     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15663     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15664     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15665     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15666     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15667     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15668         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15669     return FalseResult;
15670   }
15671   case Expr::ConditionalOperatorClass: {
15672     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15673     // If the condition (ignoring parens) is a __builtin_constant_p call,
15674     // then only the true side is actually considered in an integer constant
15675     // expression, and it is fully evaluated.  This is an important GNU
15676     // extension.  See GCC PR38377 for discussion.
15677     if (const CallExpr *CallCE
15678         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15679       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15680         return CheckEvalInICE(E, Ctx);
15681     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15682     if (CondResult.Kind == IK_NotICE)
15683       return CondResult;
15684 
15685     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15686     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15687 
15688     if (TrueResult.Kind == IK_NotICE)
15689       return TrueResult;
15690     if (FalseResult.Kind == IK_NotICE)
15691       return FalseResult;
15692     if (CondResult.Kind == IK_ICEIfUnevaluated)
15693       return CondResult;
15694     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15695       return NoDiag();
15696     // Rare case where the diagnostics depend on which side is evaluated
15697     // Note that if we get here, CondResult is 0, and at least one of
15698     // TrueResult and FalseResult is non-zero.
15699     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15700       return FalseResult;
15701     return TrueResult;
15702   }
15703   case Expr::CXXDefaultArgExprClass:
15704     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15705   case Expr::CXXDefaultInitExprClass:
15706     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15707   case Expr::ChooseExprClass: {
15708     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15709   }
15710   case Expr::BuiltinBitCastExprClass: {
15711     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15712       return ICEDiag(IK_NotICE, E->getBeginLoc());
15713     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15714   }
15715   }
15716 
15717   llvm_unreachable("Invalid StmtClass!");
15718 }
15719 
15720 /// Evaluate an expression as a C++11 integral constant expression.
15721 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15722                                                     const Expr *E,
15723                                                     llvm::APSInt *Value,
15724                                                     SourceLocation *Loc) {
15725   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15726     if (Loc) *Loc = E->getExprLoc();
15727     return false;
15728   }
15729 
15730   APValue Result;
15731   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15732     return false;
15733 
15734   if (!Result.isInt()) {
15735     if (Loc) *Loc = E->getExprLoc();
15736     return false;
15737   }
15738 
15739   if (Value) *Value = Result.getInt();
15740   return true;
15741 }
15742 
15743 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15744                                  SourceLocation *Loc) const {
15745   assert(!isValueDependent() &&
15746          "Expression evaluator can't be called on a dependent expression.");
15747 
15748   if (Ctx.getLangOpts().CPlusPlus11)
15749     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15750 
15751   ICEDiag D = CheckICE(this, Ctx);
15752   if (D.Kind != IK_ICE) {
15753     if (Loc) *Loc = D.Loc;
15754     return false;
15755   }
15756   return true;
15757 }
15758 
15759 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15760                                                     SourceLocation *Loc,
15761                                                     bool isEvaluated) const {
15762   if (isValueDependent()) {
15763     // Expression evaluator can't succeed on a dependent expression.
15764     return None;
15765   }
15766 
15767   APSInt Value;
15768 
15769   if (Ctx.getLangOpts().CPlusPlus11) {
15770     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15771       return Value;
15772     return None;
15773   }
15774 
15775   if (!isIntegerConstantExpr(Ctx, Loc))
15776     return None;
15777 
15778   // The only possible side-effects here are due to UB discovered in the
15779   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15780   // required to treat the expression as an ICE, so we produce the folded
15781   // value.
15782   EvalResult ExprResult;
15783   Expr::EvalStatus Status;
15784   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15785   Info.InConstantContext = true;
15786 
15787   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15788     llvm_unreachable("ICE cannot be evaluated!");
15789 
15790   return ExprResult.Val.getInt();
15791 }
15792 
15793 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15794   assert(!isValueDependent() &&
15795          "Expression evaluator can't be called on a dependent expression.");
15796 
15797   return CheckICE(this, Ctx).Kind == IK_ICE;
15798 }
15799 
15800 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15801                                SourceLocation *Loc) const {
15802   assert(!isValueDependent() &&
15803          "Expression evaluator can't be called on a dependent expression.");
15804 
15805   // We support this checking in C++98 mode in order to diagnose compatibility
15806   // issues.
15807   assert(Ctx.getLangOpts().CPlusPlus);
15808 
15809   // Build evaluation settings.
15810   Expr::EvalStatus Status;
15811   SmallVector<PartialDiagnosticAt, 8> Diags;
15812   Status.Diag = &Diags;
15813   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15814 
15815   APValue Scratch;
15816   bool IsConstExpr =
15817       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15818       // FIXME: We don't produce a diagnostic for this, but the callers that
15819       // call us on arbitrary full-expressions should generally not care.
15820       Info.discardCleanups() && !Status.HasSideEffects;
15821 
15822   if (!Diags.empty()) {
15823     IsConstExpr = false;
15824     if (Loc) *Loc = Diags[0].first;
15825   } else if (!IsConstExpr) {
15826     // FIXME: This shouldn't happen.
15827     if (Loc) *Loc = getExprLoc();
15828   }
15829 
15830   return IsConstExpr;
15831 }
15832 
15833 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15834                                     const FunctionDecl *Callee,
15835                                     ArrayRef<const Expr*> Args,
15836                                     const Expr *This) const {
15837   assert(!isValueDependent() &&
15838          "Expression evaluator can't be called on a dependent expression.");
15839 
15840   Expr::EvalStatus Status;
15841   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15842   Info.InConstantContext = true;
15843 
15844   LValue ThisVal;
15845   const LValue *ThisPtr = nullptr;
15846   if (This) {
15847 #ifndef NDEBUG
15848     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15849     assert(MD && "Don't provide `this` for non-methods.");
15850     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15851 #endif
15852     if (!This->isValueDependent() &&
15853         EvaluateObjectArgument(Info, This, ThisVal) &&
15854         !Info.EvalStatus.HasSideEffects)
15855       ThisPtr = &ThisVal;
15856 
15857     // Ignore any side-effects from a failed evaluation. This is safe because
15858     // they can't interfere with any other argument evaluation.
15859     Info.EvalStatus.HasSideEffects = false;
15860   }
15861 
15862   CallRef Call = Info.CurrentCall->createCall(Callee);
15863   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15864        I != E; ++I) {
15865     unsigned Idx = I - Args.begin();
15866     if (Idx >= Callee->getNumParams())
15867       break;
15868     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15869     if ((*I)->isValueDependent() ||
15870         !EvaluateCallArg(PVD, *I, Call, Info) ||
15871         Info.EvalStatus.HasSideEffects) {
15872       // If evaluation fails, throw away the argument entirely.
15873       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15874         *Slot = APValue();
15875     }
15876 
15877     // Ignore any side-effects from a failed evaluation. This is safe because
15878     // they can't interfere with any other argument evaluation.
15879     Info.EvalStatus.HasSideEffects = false;
15880   }
15881 
15882   // Parameter cleanups happen in the caller and are not part of this
15883   // evaluation.
15884   Info.discardCleanups();
15885   Info.EvalStatus.HasSideEffects = false;
15886 
15887   // Build fake call to Callee.
15888   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15889   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15890   FullExpressionRAII Scope(Info);
15891   return Evaluate(Value, Info, this) && Scope.destroy() &&
15892          !Info.EvalStatus.HasSideEffects;
15893 }
15894 
15895 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15896                                    SmallVectorImpl<
15897                                      PartialDiagnosticAt> &Diags) {
15898   // FIXME: It would be useful to check constexpr function templates, but at the
15899   // moment the constant expression evaluator cannot cope with the non-rigorous
15900   // ASTs which we build for dependent expressions.
15901   if (FD->isDependentContext())
15902     return true;
15903 
15904   Expr::EvalStatus Status;
15905   Status.Diag = &Diags;
15906 
15907   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15908   Info.InConstantContext = true;
15909   Info.CheckingPotentialConstantExpression = true;
15910 
15911   // The constexpr VM attempts to compile all methods to bytecode here.
15912   if (Info.EnableNewConstInterp) {
15913     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15914     return Diags.empty();
15915   }
15916 
15917   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15918   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15919 
15920   // Fabricate an arbitrary expression on the stack and pretend that it
15921   // is a temporary being used as the 'this' pointer.
15922   LValue This;
15923   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15924   This.set({&VIE, Info.CurrentCall->Index});
15925 
15926   ArrayRef<const Expr*> Args;
15927 
15928   APValue Scratch;
15929   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15930     // Evaluate the call as a constant initializer, to allow the construction
15931     // of objects of non-literal types.
15932     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15933     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15934   } else {
15935     SourceLocation Loc = FD->getLocation();
15936     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15937                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15938   }
15939 
15940   return Diags.empty();
15941 }
15942 
15943 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15944                                               const FunctionDecl *FD,
15945                                               SmallVectorImpl<
15946                                                 PartialDiagnosticAt> &Diags) {
15947   assert(!E->isValueDependent() &&
15948          "Expression evaluator can't be called on a dependent expression.");
15949 
15950   Expr::EvalStatus Status;
15951   Status.Diag = &Diags;
15952 
15953   EvalInfo Info(FD->getASTContext(), Status,
15954                 EvalInfo::EM_ConstantExpressionUnevaluated);
15955   Info.InConstantContext = true;
15956   Info.CheckingPotentialConstantExpression = true;
15957 
15958   // Fabricate a call stack frame to give the arguments a plausible cover story.
15959   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15960 
15961   APValue ResultScratch;
15962   Evaluate(ResultScratch, Info, E);
15963   return Diags.empty();
15964 }
15965 
15966 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15967                                  unsigned Type) const {
15968   if (!getType()->isPointerType())
15969     return false;
15970 
15971   Expr::EvalStatus Status;
15972   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15973   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15974 }
15975 
15976 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15977                                   EvalInfo &Info) {
15978   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15979     return false;
15980 
15981   LValue String;
15982 
15983   if (!EvaluatePointer(E, String, Info))
15984     return false;
15985 
15986   QualType CharTy = E->getType()->getPointeeType();
15987 
15988   // Fast path: if it's a string literal, search the string value.
15989   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15990           String.getLValueBase().dyn_cast<const Expr *>())) {
15991     StringRef Str = S->getBytes();
15992     int64_t Off = String.Offset.getQuantity();
15993     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15994         S->getCharByteWidth() == 1 &&
15995         // FIXME: Add fast-path for wchar_t too.
15996         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15997       Str = Str.substr(Off);
15998 
15999       StringRef::size_type Pos = Str.find(0);
16000       if (Pos != StringRef::npos)
16001         Str = Str.substr(0, Pos);
16002 
16003       Result = Str.size();
16004       return true;
16005     }
16006 
16007     // Fall through to slow path.
16008   }
16009 
16010   // Slow path: scan the bytes of the string looking for the terminating 0.
16011   for (uint64_t Strlen = 0; /**/; ++Strlen) {
16012     APValue Char;
16013     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16014         !Char.isInt())
16015       return false;
16016     if (!Char.getInt()) {
16017       Result = Strlen;
16018       return true;
16019     }
16020     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16021       return false;
16022   }
16023 }
16024 
16025 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16026   Expr::EvalStatus Status;
16027   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16028   return EvaluateBuiltinStrLen(this, Result, Info);
16029 }
16030