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     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
987                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
988       EvaluatingDecl = Base;
989       IsEvaluatingDecl = EDK;
990       EvaluatingDeclValue = &Value;
991     }
992 
993     bool CheckCallLimit(SourceLocation Loc) {
994       // Don't perform any constexpr calls (other than the call we're checking)
995       // when checking a potential constant expression.
996       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
997         return false;
998       if (NextCallIndex == 0) {
999         // NextCallIndex has wrapped around.
1000         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1001         return false;
1002       }
1003       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1004         return true;
1005       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1006         << getLangOpts().ConstexprCallDepth;
1007       return false;
1008     }
1009 
1010     std::pair<CallStackFrame *, unsigned>
1011     getCallFrameAndDepth(unsigned CallIndex) {
1012       assert(CallIndex && "no call index in getCallFrameAndDepth");
1013       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1014       // be null in this loop.
1015       unsigned Depth = CallStackDepth;
1016       CallStackFrame *Frame = CurrentCall;
1017       while (Frame->Index > CallIndex) {
1018         Frame = Frame->Caller;
1019         --Depth;
1020       }
1021       if (Frame->Index == CallIndex)
1022         return {Frame, Depth};
1023       return {nullptr, 0};
1024     }
1025 
1026     bool nextStep(const Stmt *S) {
1027       if (!StepsLeft) {
1028         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1029         return false;
1030       }
1031       --StepsLeft;
1032       return true;
1033     }
1034 
1035     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1036 
1037     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1038       Optional<DynAlloc*> Result;
1039       auto It = HeapAllocs.find(DA);
1040       if (It != HeapAllocs.end())
1041         Result = &It->second;
1042       return Result;
1043     }
1044 
1045     /// Get the allocated storage for the given parameter of the given call.
1046     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1047       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1048       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1049                    : nullptr;
1050     }
1051 
1052     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1053     struct StdAllocatorCaller {
1054       unsigned FrameIndex;
1055       QualType ElemType;
1056       explicit operator bool() const { return FrameIndex != 0; };
1057     };
1058 
1059     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1060       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1061            Call = Call->Caller) {
1062         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1063         if (!MD)
1064           continue;
1065         const IdentifierInfo *FnII = MD->getIdentifier();
1066         if (!FnII || !FnII->isStr(FnName))
1067           continue;
1068 
1069         const auto *CTSD =
1070             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1071         if (!CTSD)
1072           continue;
1073 
1074         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1075         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1076         if (CTSD->isInStdNamespace() && ClassII &&
1077             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1078             TAL[0].getKind() == TemplateArgument::Type)
1079           return {Call->Index, TAL[0].getAsType()};
1080       }
1081 
1082       return {};
1083     }
1084 
1085     void performLifetimeExtension() {
1086       // Disable the cleanups for lifetime-extended temporaries.
1087       llvm::erase_if(CleanupStack, [](Cleanup &C) {
1088         return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1089       });
1090     }
1091 
1092     /// Throw away any remaining cleanups at the end of evaluation. If any
1093     /// cleanups would have had a side-effect, note that as an unmodeled
1094     /// side-effect and return false. Otherwise, return true.
1095     bool discardCleanups() {
1096       for (Cleanup &C : CleanupStack) {
1097         if (C.hasSideEffect() && !noteSideEffect()) {
1098           CleanupStack.clear();
1099           return false;
1100         }
1101       }
1102       CleanupStack.clear();
1103       return true;
1104     }
1105 
1106   private:
1107     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1108     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1109 
1110     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1111     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1112 
1113     void setFoldFailureDiagnostic(bool Flag) override {
1114       HasFoldFailureDiagnostic = Flag;
1115     }
1116 
1117     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1118 
1119     ASTContext &getCtx() const override { return Ctx; }
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), Path() {}
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 string literal?
1958 static bool IsStringLiteralCall(const CallExpr *E) {
1959   unsigned Builtin = E->getBuiltinCallee();
1960   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1962 }
1963 
1964 static bool IsGlobalLValue(APValue::LValueBase B) {
1965   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1966   // constant expression of pointer type that evaluates to...
1967 
1968   // ... a null pointer value, or a prvalue core constant expression of type
1969   // std::nullptr_t.
1970   if (!B) return true;
1971 
1972   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1973     // ... the address of an object with static storage duration,
1974     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1975       return VD->hasGlobalStorage();
1976     if (isa<TemplateParamObjectDecl>(D))
1977       return true;
1978     // ... the address of a function,
1979     // ... the address of a GUID [MS extension],
1980     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1981   }
1982 
1983   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1984     return true;
1985 
1986   const Expr *E = B.get<const Expr*>();
1987   switch (E->getStmtClass()) {
1988   default:
1989     return false;
1990   case Expr::CompoundLiteralExprClass: {
1991     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1992     return CLE->isFileScope() && CLE->isLValue();
1993   }
1994   case Expr::MaterializeTemporaryExprClass:
1995     // A materialized temporary might have been lifetime-extended to static
1996     // storage duration.
1997     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1998   // A string literal has static storage duration.
1999   case Expr::StringLiteralClass:
2000   case Expr::PredefinedExprClass:
2001   case Expr::ObjCStringLiteralClass:
2002   case Expr::ObjCEncodeExprClass:
2003     return true;
2004   case Expr::ObjCBoxedExprClass:
2005     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2006   case Expr::CallExprClass:
2007     return IsStringLiteralCall(cast<CallExpr>(E));
2008   // For GCC compatibility, &&label has static storage duration.
2009   case Expr::AddrLabelExprClass:
2010     return true;
2011   // A Block literal expression may be used as the initialization value for
2012   // Block variables at global or local static scope.
2013   case Expr::BlockExprClass:
2014     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2015   case Expr::ImplicitValueInitExprClass:
2016     // FIXME:
2017     // We can never form an lvalue with an implicit value initialization as its
2018     // base through expression evaluation, so these only appear in one case: the
2019     // implicit variable declaration we invent when checking whether a constexpr
2020     // constructor can produce a constant expression. We must assume that such
2021     // an expression might be a global lvalue.
2022     return true;
2023   }
2024 }
2025 
2026 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2027   return LVal.Base.dyn_cast<const ValueDecl*>();
2028 }
2029 
2030 static bool IsLiteralLValue(const LValue &Value) {
2031   if (Value.getLValueCallIndex())
2032     return false;
2033   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2034   return E && !isa<MaterializeTemporaryExpr>(E);
2035 }
2036 
2037 static bool IsWeakLValue(const LValue &Value) {
2038   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2039   return Decl && Decl->isWeak();
2040 }
2041 
2042 static bool isZeroSized(const LValue &Value) {
2043   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2044   if (Decl && isa<VarDecl>(Decl)) {
2045     QualType Ty = Decl->getType();
2046     if (Ty->isArrayType())
2047       return Ty->isIncompleteType() ||
2048              Decl->getASTContext().getTypeSize(Ty) == 0;
2049   }
2050   return false;
2051 }
2052 
2053 static bool HasSameBase(const LValue &A, const LValue &B) {
2054   if (!A.getLValueBase())
2055     return !B.getLValueBase();
2056   if (!B.getLValueBase())
2057     return false;
2058 
2059   if (A.getLValueBase().getOpaqueValue() !=
2060       B.getLValueBase().getOpaqueValue())
2061     return false;
2062 
2063   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2064          A.getLValueVersion() == B.getLValueVersion();
2065 }
2066 
2067 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2068   assert(Base && "no location for a null lvalue");
2069   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2070 
2071   // For a parameter, find the corresponding call stack frame (if it still
2072   // exists), and point at the parameter of the function definition we actually
2073   // invoked.
2074   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2075     unsigned Idx = PVD->getFunctionScopeIndex();
2076     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2077       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2078           F->Arguments.Version == Base.getVersion() && F->Callee &&
2079           Idx < F->Callee->getNumParams()) {
2080         VD = F->Callee->getParamDecl(Idx);
2081         break;
2082       }
2083     }
2084   }
2085 
2086   if (VD)
2087     Info.Note(VD->getLocation(), diag::note_declared_at);
2088   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2089     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2090   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2091     // FIXME: Produce a note for dangling pointers too.
2092     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2093       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2094                 diag::note_constexpr_dynamic_alloc_here);
2095   }
2096   // We have no information to show for a typeid(T) object.
2097 }
2098 
2099 enum class CheckEvaluationResultKind {
2100   ConstantExpression,
2101   FullyInitialized,
2102 };
2103 
2104 /// Materialized temporaries that we've already checked to determine if they're
2105 /// initializsed by a constant expression.
2106 using CheckedTemporaries =
2107     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2108 
2109 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2110                                   EvalInfo &Info, SourceLocation DiagLoc,
2111                                   QualType Type, const APValue &Value,
2112                                   ConstantExprKind Kind,
2113                                   SourceLocation SubobjectLoc,
2114                                   CheckedTemporaries &CheckedTemps);
2115 
2116 /// Check that this reference or pointer core constant expression is a valid
2117 /// value for an address or reference constant expression. Return true if we
2118 /// can fold this expression, whether or not it's a constant expression.
2119 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2120                                           QualType Type, const LValue &LVal,
2121                                           ConstantExprKind Kind,
2122                                           CheckedTemporaries &CheckedTemps) {
2123   bool IsReferenceType = Type->isReferenceType();
2124 
2125   APValue::LValueBase Base = LVal.getLValueBase();
2126   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2127 
2128   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2129   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2130 
2131   // Additional restrictions apply in a template argument. We only enforce the
2132   // C++20 restrictions here; additional syntactic and semantic restrictions
2133   // are applied elsewhere.
2134   if (isTemplateArgument(Kind)) {
2135     int InvalidBaseKind = -1;
2136     StringRef Ident;
2137     if (Base.is<TypeInfoLValue>())
2138       InvalidBaseKind = 0;
2139     else if (isa_and_nonnull<StringLiteral>(BaseE))
2140       InvalidBaseKind = 1;
2141     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2142              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2143       InvalidBaseKind = 2;
2144     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2145       InvalidBaseKind = 3;
2146       Ident = PE->getIdentKindName();
2147     }
2148 
2149     if (InvalidBaseKind != -1) {
2150       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2151           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2152           << Ident;
2153       return false;
2154     }
2155   }
2156 
2157   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2158     if (FD->isConsteval()) {
2159       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2160           << !Type->isAnyPointerType();
2161       Info.Note(FD->getLocation(), diag::note_declared_at);
2162       return false;
2163     }
2164   }
2165 
2166   // Check that the object is a global. Note that the fake 'this' object we
2167   // manufacture when checking potential constant expressions is conservatively
2168   // assumed to be global here.
2169   if (!IsGlobalLValue(Base)) {
2170     if (Info.getLangOpts().CPlusPlus11) {
2171       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2172       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2173         << IsReferenceType << !Designator.Entries.empty()
2174         << !!VD << VD;
2175 
2176       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2177       if (VarD && VarD->isConstexpr()) {
2178         // Non-static local constexpr variables have unintuitive semantics:
2179         //   constexpr int a = 1;
2180         //   constexpr const int *p = &a;
2181         // ... is invalid because the address of 'a' is not constant. Suggest
2182         // adding a 'static' in this case.
2183         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2184             << VarD
2185             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2186       } else {
2187         NoteLValueLocation(Info, Base);
2188       }
2189     } else {
2190       Info.FFDiag(Loc);
2191     }
2192     // Don't allow references to temporaries to escape.
2193     return false;
2194   }
2195   assert((Info.checkingPotentialConstantExpression() ||
2196           LVal.getLValueCallIndex() == 0) &&
2197          "have call index for global lvalue");
2198 
2199   if (Base.is<DynamicAllocLValue>()) {
2200     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2201         << IsReferenceType << !Designator.Entries.empty();
2202     NoteLValueLocation(Info, Base);
2203     return false;
2204   }
2205 
2206   if (BaseVD) {
2207     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2208       // Check if this is a thread-local variable.
2209       if (Var->getTLSKind())
2210         // FIXME: Diagnostic!
2211         return false;
2212 
2213       // A dllimport variable never acts like a constant, unless we're
2214       // evaluating a value for use only in name mangling.
2215       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2216         // FIXME: Diagnostic!
2217         return false;
2218     }
2219     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2220       // __declspec(dllimport) must be handled very carefully:
2221       // We must never initialize an expression with the thunk in C++.
2222       // Doing otherwise would allow the same id-expression to yield
2223       // different addresses for the same function in different translation
2224       // units.  However, this means that we must dynamically initialize the
2225       // expression with the contents of the import address table at runtime.
2226       //
2227       // The C language has no notion of ODR; furthermore, it has no notion of
2228       // dynamic initialization.  This means that we are permitted to
2229       // perform initialization with the address of the thunk.
2230       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2231           FD->hasAttr<DLLImportAttr>())
2232         // FIXME: Diagnostic!
2233         return false;
2234     }
2235   } else if (const auto *MTE =
2236                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2237     if (CheckedTemps.insert(MTE).second) {
2238       QualType TempType = getType(Base);
2239       if (TempType.isDestructedType()) {
2240         Info.FFDiag(MTE->getExprLoc(),
2241                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2242             << TempType;
2243         return false;
2244       }
2245 
2246       APValue *V = MTE->getOrCreateValue(false);
2247       assert(V && "evasluation result refers to uninitialised temporary");
2248       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2249                                  Info, MTE->getExprLoc(), TempType, *V,
2250                                  Kind, SourceLocation(), CheckedTemps))
2251         return false;
2252     }
2253   }
2254 
2255   // Allow address constant expressions to be past-the-end pointers. This is
2256   // an extension: the standard requires them to point to an object.
2257   if (!IsReferenceType)
2258     return true;
2259 
2260   // A reference constant expression must refer to an object.
2261   if (!Base) {
2262     // FIXME: diagnostic
2263     Info.CCEDiag(Loc);
2264     return true;
2265   }
2266 
2267   // Does this refer one past the end of some object?
2268   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2269     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2270       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2271     NoteLValueLocation(Info, Base);
2272   }
2273 
2274   return true;
2275 }
2276 
2277 /// Member pointers are constant expressions unless they point to a
2278 /// non-virtual dllimport member function.
2279 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2280                                                  SourceLocation Loc,
2281                                                  QualType Type,
2282                                                  const APValue &Value,
2283                                                  ConstantExprKind Kind) {
2284   const ValueDecl *Member = Value.getMemberPointerDecl();
2285   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2286   if (!FD)
2287     return true;
2288   if (FD->isConsteval()) {
2289     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2290     Info.Note(FD->getLocation(), diag::note_declared_at);
2291     return false;
2292   }
2293   return isForManglingOnly(Kind) || FD->isVirtual() ||
2294          !FD->hasAttr<DLLImportAttr>();
2295 }
2296 
2297 /// Check that this core constant expression is of literal type, and if not,
2298 /// produce an appropriate diagnostic.
2299 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2300                              const LValue *This = nullptr) {
2301   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2302     return true;
2303 
2304   // C++1y: A constant initializer for an object o [...] may also invoke
2305   // constexpr constructors for o and its subobjects even if those objects
2306   // are of non-literal class types.
2307   //
2308   // C++11 missed this detail for aggregates, so classes like this:
2309   //   struct foo_t { union { int i; volatile int j; } u; };
2310   // are not (obviously) initializable like so:
2311   //   __attribute__((__require_constant_initialization__))
2312   //   static const foo_t x = {{0}};
2313   // because "i" is a subobject with non-literal initialization (due to the
2314   // volatile member of the union). See:
2315   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2316   // Therefore, we use the C++1y behavior.
2317   if (This && Info.EvaluatingDecl == This->getLValueBase())
2318     return true;
2319 
2320   // Prvalue constant expressions must be of literal types.
2321   if (Info.getLangOpts().CPlusPlus11)
2322     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2323       << E->getType();
2324   else
2325     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2326   return false;
2327 }
2328 
2329 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2330                                   EvalInfo &Info, SourceLocation DiagLoc,
2331                                   QualType Type, const APValue &Value,
2332                                   ConstantExprKind Kind,
2333                                   SourceLocation SubobjectLoc,
2334                                   CheckedTemporaries &CheckedTemps) {
2335   if (!Value.hasValue()) {
2336     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2337       << true << Type;
2338     if (SubobjectLoc.isValid())
2339       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2340     return false;
2341   }
2342 
2343   // We allow _Atomic(T) to be initialized from anything that T can be
2344   // initialized from.
2345   if (const AtomicType *AT = Type->getAs<AtomicType>())
2346     Type = AT->getValueType();
2347 
2348   // Core issue 1454: For a literal constant expression of array or class type,
2349   // each subobject of its value shall have been initialized by a constant
2350   // expression.
2351   if (Value.isArray()) {
2352     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2353     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2354       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2355                                  Value.getArrayInitializedElt(I), Kind,
2356                                  SubobjectLoc, CheckedTemps))
2357         return false;
2358     }
2359     if (!Value.hasArrayFiller())
2360       return true;
2361     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2362                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2363                                  CheckedTemps);
2364   }
2365   if (Value.isUnion() && Value.getUnionField()) {
2366     return CheckEvaluationResult(
2367         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2368         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2369         CheckedTemps);
2370   }
2371   if (Value.isStruct()) {
2372     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2373     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2374       unsigned BaseIndex = 0;
2375       for (const CXXBaseSpecifier &BS : CD->bases()) {
2376         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2377                                    Value.getStructBase(BaseIndex), Kind,
2378                                    BS.getBeginLoc(), CheckedTemps))
2379           return false;
2380         ++BaseIndex;
2381       }
2382     }
2383     for (const auto *I : RD->fields()) {
2384       if (I->isUnnamedBitfield())
2385         continue;
2386 
2387       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2388                                  Value.getStructField(I->getFieldIndex()),
2389                                  Kind, I->getLocation(), CheckedTemps))
2390         return false;
2391     }
2392   }
2393 
2394   if (Value.isLValue() &&
2395       CERK == CheckEvaluationResultKind::ConstantExpression) {
2396     LValue LVal;
2397     LVal.setFrom(Info.Ctx, Value);
2398     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2399                                          CheckedTemps);
2400   }
2401 
2402   if (Value.isMemberPointer() &&
2403       CERK == CheckEvaluationResultKind::ConstantExpression)
2404     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2405 
2406   // Everything else is fine.
2407   return true;
2408 }
2409 
2410 /// Check that this core constant expression value is a valid value for a
2411 /// constant expression. If not, report an appropriate diagnostic. Does not
2412 /// check that the expression is of literal type.
2413 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2414                                     QualType Type, const APValue &Value,
2415                                     ConstantExprKind Kind) {
2416   // Nothing to check for a constant expression of type 'cv void'.
2417   if (Type->isVoidType())
2418     return true;
2419 
2420   CheckedTemporaries CheckedTemps;
2421   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2422                                Info, DiagLoc, Type, Value, Kind,
2423                                SourceLocation(), CheckedTemps);
2424 }
2425 
2426 /// Check that this evaluated value is fully-initialized and can be loaded by
2427 /// an lvalue-to-rvalue conversion.
2428 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2429                                   QualType Type, const APValue &Value) {
2430   CheckedTemporaries CheckedTemps;
2431   return CheckEvaluationResult(
2432       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2433       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2434 }
2435 
2436 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2437 /// "the allocated storage is deallocated within the evaluation".
2438 static bool CheckMemoryLeaks(EvalInfo &Info) {
2439   if (!Info.HeapAllocs.empty()) {
2440     // We can still fold to a constant despite a compile-time memory leak,
2441     // so long as the heap allocation isn't referenced in the result (we check
2442     // that in CheckConstantExpression).
2443     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2444                  diag::note_constexpr_memory_leak)
2445         << unsigned(Info.HeapAllocs.size() - 1);
2446   }
2447   return true;
2448 }
2449 
2450 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2451   // A null base expression indicates a null pointer.  These are always
2452   // evaluatable, and they are false unless the offset is zero.
2453   if (!Value.getLValueBase()) {
2454     Result = !Value.getLValueOffset().isZero();
2455     return true;
2456   }
2457 
2458   // We have a non-null base.  These are generally known to be true, but if it's
2459   // a weak declaration it can be null at runtime.
2460   Result = true;
2461   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2462   return !Decl || !Decl->isWeak();
2463 }
2464 
2465 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2466   switch (Val.getKind()) {
2467   case APValue::None:
2468   case APValue::Indeterminate:
2469     return false;
2470   case APValue::Int:
2471     Result = Val.getInt().getBoolValue();
2472     return true;
2473   case APValue::FixedPoint:
2474     Result = Val.getFixedPoint().getBoolValue();
2475     return true;
2476   case APValue::Float:
2477     Result = !Val.getFloat().isZero();
2478     return true;
2479   case APValue::ComplexInt:
2480     Result = Val.getComplexIntReal().getBoolValue() ||
2481              Val.getComplexIntImag().getBoolValue();
2482     return true;
2483   case APValue::ComplexFloat:
2484     Result = !Val.getComplexFloatReal().isZero() ||
2485              !Val.getComplexFloatImag().isZero();
2486     return true;
2487   case APValue::LValue:
2488     return EvalPointerValueAsBool(Val, Result);
2489   case APValue::MemberPointer:
2490     Result = Val.getMemberPointerDecl();
2491     return true;
2492   case APValue::Vector:
2493   case APValue::Array:
2494   case APValue::Struct:
2495   case APValue::Union:
2496   case APValue::AddrLabelDiff:
2497     return false;
2498   }
2499 
2500   llvm_unreachable("unknown APValue kind");
2501 }
2502 
2503 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2504                                        EvalInfo &Info) {
2505   assert(!E->isValueDependent());
2506   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2507   APValue Val;
2508   if (!Evaluate(Val, Info, E))
2509     return false;
2510   return HandleConversionToBool(Val, Result);
2511 }
2512 
2513 template<typename T>
2514 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2515                            const T &SrcValue, QualType DestType) {
2516   Info.CCEDiag(E, diag::note_constexpr_overflow)
2517     << SrcValue << DestType;
2518   return Info.noteUndefinedBehavior();
2519 }
2520 
2521 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2522                                  QualType SrcType, const APFloat &Value,
2523                                  QualType DestType, APSInt &Result) {
2524   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2525   // Determine whether we are converting to unsigned or signed.
2526   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2527 
2528   Result = APSInt(DestWidth, !DestSigned);
2529   bool ignored;
2530   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2531       & APFloat::opInvalidOp)
2532     return HandleOverflow(Info, E, Value, DestType);
2533   return true;
2534 }
2535 
2536 /// Get rounding mode used for evaluation of the specified expression.
2537 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2538 ///                       dynamic.
2539 /// If rounding mode is unknown at compile time, still try to evaluate the
2540 /// expression. If the result is exact, it does not depend on rounding mode.
2541 /// So return "tonearest" mode instead of "dynamic".
2542 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2543                                                 bool &DynamicRM) {
2544   llvm::RoundingMode RM =
2545       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2546   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2547   if (DynamicRM)
2548     RM = llvm::RoundingMode::NearestTiesToEven;
2549   return RM;
2550 }
2551 
2552 /// Check if the given evaluation result is allowed for constant evaluation.
2553 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2554                                      APFloat::opStatus St) {
2555   // In a constant context, assume that any dynamic rounding mode or FP
2556   // exception state matches the default floating-point environment.
2557   if (Info.InConstantContext)
2558     return true;
2559 
2560   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2561   if ((St & APFloat::opInexact) &&
2562       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2563     // Inexact result means that it depends on rounding mode. If the requested
2564     // mode is dynamic, the evaluation cannot be made in compile time.
2565     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2566     return false;
2567   }
2568 
2569   if ((St != APFloat::opOK) &&
2570       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2571        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2572        FPO.getAllowFEnvAccess())) {
2573     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2574     return false;
2575   }
2576 
2577   if ((St & APFloat::opStatus::opInvalidOp) &&
2578       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2579     // There is no usefully definable result.
2580     Info.FFDiag(E);
2581     return false;
2582   }
2583 
2584   // FIXME: if:
2585   // - evaluation triggered other FP exception, and
2586   // - exception mode is not "ignore", and
2587   // - the expression being evaluated is not a part of global variable
2588   //   initializer,
2589   // the evaluation probably need to be rejected.
2590   return true;
2591 }
2592 
2593 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2594                                    QualType SrcType, QualType DestType,
2595                                    APFloat &Result) {
2596   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2597   bool DynamicRM;
2598   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2599   APFloat::opStatus St;
2600   APFloat Value = Result;
2601   bool ignored;
2602   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2603   return checkFloatingPointResult(Info, E, St);
2604 }
2605 
2606 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2607                                  QualType DestType, QualType SrcType,
2608                                  const APSInt &Value) {
2609   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2610   // Figure out if this is a truncate, extend or noop cast.
2611   // If the input is signed, do a sign extend, noop, or truncate.
2612   APSInt Result = Value.extOrTrunc(DestWidth);
2613   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2614   if (DestType->isBooleanType())
2615     Result = Value.getBoolValue();
2616   return Result;
2617 }
2618 
2619 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2620                                  const FPOptions FPO,
2621                                  QualType SrcType, const APSInt &Value,
2622                                  QualType DestType, APFloat &Result) {
2623   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2624   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2625        APFloat::rmNearestTiesToEven);
2626   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2627       FPO.isFPConstrained()) {
2628     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2629     return false;
2630   }
2631   return true;
2632 }
2633 
2634 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2635                                   APValue &Value, const FieldDecl *FD) {
2636   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2637 
2638   if (!Value.isInt()) {
2639     // Trying to store a pointer-cast-to-integer into a bitfield.
2640     // FIXME: In this case, we should provide the diagnostic for casting
2641     // a pointer to an integer.
2642     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2643     Info.FFDiag(E);
2644     return false;
2645   }
2646 
2647   APSInt &Int = Value.getInt();
2648   unsigned OldBitWidth = Int.getBitWidth();
2649   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2650   if (NewBitWidth < OldBitWidth)
2651     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2652   return true;
2653 }
2654 
2655 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2656                                   llvm::APInt &Res) {
2657   APValue SVal;
2658   if (!Evaluate(SVal, Info, E))
2659     return false;
2660   if (SVal.isInt()) {
2661     Res = SVal.getInt();
2662     return true;
2663   }
2664   if (SVal.isFloat()) {
2665     Res = SVal.getFloat().bitcastToAPInt();
2666     return true;
2667   }
2668   if (SVal.isVector()) {
2669     QualType VecTy = E->getType();
2670     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2671     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2672     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2673     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2674     Res = llvm::APInt::getZero(VecSize);
2675     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2676       APValue &Elt = SVal.getVectorElt(i);
2677       llvm::APInt EltAsInt;
2678       if (Elt.isInt()) {
2679         EltAsInt = Elt.getInt();
2680       } else if (Elt.isFloat()) {
2681         EltAsInt = Elt.getFloat().bitcastToAPInt();
2682       } else {
2683         // Don't try to handle vectors of anything other than int or float
2684         // (not sure if it's possible to hit this case).
2685         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2686         return false;
2687       }
2688       unsigned BaseEltSize = EltAsInt.getBitWidth();
2689       if (BigEndian)
2690         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2691       else
2692         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2693     }
2694     return true;
2695   }
2696   // Give up if the input isn't an int, float, or vector.  For example, we
2697   // reject "(v4i16)(intptr_t)&a".
2698   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2699   return false;
2700 }
2701 
2702 /// Perform the given integer operation, which is known to need at most BitWidth
2703 /// bits, and check for overflow in the original type (if that type was not an
2704 /// unsigned type).
2705 template<typename Operation>
2706 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2707                                  const APSInt &LHS, const APSInt &RHS,
2708                                  unsigned BitWidth, Operation Op,
2709                                  APSInt &Result) {
2710   if (LHS.isUnsigned()) {
2711     Result = Op(LHS, RHS);
2712     return true;
2713   }
2714 
2715   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2716   Result = Value.trunc(LHS.getBitWidth());
2717   if (Result.extend(BitWidth) != Value) {
2718     if (Info.checkingForUndefinedBehavior())
2719       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2720                                        diag::warn_integer_constant_overflow)
2721           << toString(Result, 10) << E->getType();
2722     return HandleOverflow(Info, E, Value, E->getType());
2723   }
2724   return true;
2725 }
2726 
2727 /// Perform the given binary integer operation.
2728 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2729                               BinaryOperatorKind Opcode, APSInt RHS,
2730                               APSInt &Result) {
2731   switch (Opcode) {
2732   default:
2733     Info.FFDiag(E);
2734     return false;
2735   case BO_Mul:
2736     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2737                                 std::multiplies<APSInt>(), Result);
2738   case BO_Add:
2739     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2740                                 std::plus<APSInt>(), Result);
2741   case BO_Sub:
2742     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2743                                 std::minus<APSInt>(), Result);
2744   case BO_And: Result = LHS & RHS; return true;
2745   case BO_Xor: Result = LHS ^ RHS; return true;
2746   case BO_Or:  Result = LHS | RHS; return true;
2747   case BO_Div:
2748   case BO_Rem:
2749     if (RHS == 0) {
2750       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2751       return false;
2752     }
2753     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2754     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2755     // this operation and gives the two's complement result.
2756     if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2757         LHS.isMinSignedValue())
2758       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2759                             E->getType());
2760     return true;
2761   case BO_Shl: {
2762     if (Info.getLangOpts().OpenCL)
2763       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2764       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2765                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2766                     RHS.isUnsigned());
2767     else if (RHS.isSigned() && RHS.isNegative()) {
2768       // During constant-folding, a negative shift is an opposite shift. Such
2769       // a shift is not a constant expression.
2770       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2771       RHS = -RHS;
2772       goto shift_right;
2773     }
2774   shift_left:
2775     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2776     // the shifted type.
2777     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2778     if (SA != RHS) {
2779       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2780         << RHS << E->getType() << LHS.getBitWidth();
2781     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2782       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2783       // operand, and must not overflow the corresponding unsigned type.
2784       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2785       // E1 x 2^E2 module 2^N.
2786       if (LHS.isNegative())
2787         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2788       else if (LHS.countLeadingZeros() < SA)
2789         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2790     }
2791     Result = LHS << SA;
2792     return true;
2793   }
2794   case BO_Shr: {
2795     if (Info.getLangOpts().OpenCL)
2796       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2797       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2798                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2799                     RHS.isUnsigned());
2800     else if (RHS.isSigned() && RHS.isNegative()) {
2801       // During constant-folding, a negative shift is an opposite shift. Such a
2802       // shift is not a constant expression.
2803       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2804       RHS = -RHS;
2805       goto shift_left;
2806     }
2807   shift_right:
2808     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2809     // shifted type.
2810     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2811     if (SA != RHS)
2812       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2813         << RHS << E->getType() << LHS.getBitWidth();
2814     Result = LHS >> SA;
2815     return true;
2816   }
2817 
2818   case BO_LT: Result = LHS < RHS; return true;
2819   case BO_GT: Result = LHS > RHS; return true;
2820   case BO_LE: Result = LHS <= RHS; return true;
2821   case BO_GE: Result = LHS >= RHS; return true;
2822   case BO_EQ: Result = LHS == RHS; return true;
2823   case BO_NE: Result = LHS != RHS; return true;
2824   case BO_Cmp:
2825     llvm_unreachable("BO_Cmp should be handled elsewhere");
2826   }
2827 }
2828 
2829 /// Perform the given binary floating-point operation, in-place, on LHS.
2830 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2831                                   APFloat &LHS, BinaryOperatorKind Opcode,
2832                                   const APFloat &RHS) {
2833   bool DynamicRM;
2834   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2835   APFloat::opStatus St;
2836   switch (Opcode) {
2837   default:
2838     Info.FFDiag(E);
2839     return false;
2840   case BO_Mul:
2841     St = LHS.multiply(RHS, RM);
2842     break;
2843   case BO_Add:
2844     St = LHS.add(RHS, RM);
2845     break;
2846   case BO_Sub:
2847     St = LHS.subtract(RHS, RM);
2848     break;
2849   case BO_Div:
2850     // [expr.mul]p4:
2851     //   If the second operand of / or % is zero the behavior is undefined.
2852     if (RHS.isZero())
2853       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2854     St = LHS.divide(RHS, RM);
2855     break;
2856   }
2857 
2858   // [expr.pre]p4:
2859   //   If during the evaluation of an expression, the result is not
2860   //   mathematically defined [...], the behavior is undefined.
2861   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2862   if (LHS.isNaN()) {
2863     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2864     return Info.noteUndefinedBehavior();
2865   }
2866 
2867   return checkFloatingPointResult(Info, E, St);
2868 }
2869 
2870 static bool handleLogicalOpForVector(const APInt &LHSValue,
2871                                      BinaryOperatorKind Opcode,
2872                                      const APInt &RHSValue, APInt &Result) {
2873   bool LHS = (LHSValue != 0);
2874   bool RHS = (RHSValue != 0);
2875 
2876   if (Opcode == BO_LAnd)
2877     Result = LHS && RHS;
2878   else
2879     Result = LHS || RHS;
2880   return true;
2881 }
2882 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2883                                      BinaryOperatorKind Opcode,
2884                                      const APFloat &RHSValue, APInt &Result) {
2885   bool LHS = !LHSValue.isZero();
2886   bool RHS = !RHSValue.isZero();
2887 
2888   if (Opcode == BO_LAnd)
2889     Result = LHS && RHS;
2890   else
2891     Result = LHS || RHS;
2892   return true;
2893 }
2894 
2895 static bool handleLogicalOpForVector(const APValue &LHSValue,
2896                                      BinaryOperatorKind Opcode,
2897                                      const APValue &RHSValue, APInt &Result) {
2898   // The result is always an int type, however operands match the first.
2899   if (LHSValue.getKind() == APValue::Int)
2900     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2901                                     RHSValue.getInt(), Result);
2902   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2903   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2904                                   RHSValue.getFloat(), Result);
2905 }
2906 
2907 template <typename APTy>
2908 static bool
2909 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2910                                const APTy &RHSValue, APInt &Result) {
2911   switch (Opcode) {
2912   default:
2913     llvm_unreachable("unsupported binary operator");
2914   case BO_EQ:
2915     Result = (LHSValue == RHSValue);
2916     break;
2917   case BO_NE:
2918     Result = (LHSValue != RHSValue);
2919     break;
2920   case BO_LT:
2921     Result = (LHSValue < RHSValue);
2922     break;
2923   case BO_GT:
2924     Result = (LHSValue > RHSValue);
2925     break;
2926   case BO_LE:
2927     Result = (LHSValue <= RHSValue);
2928     break;
2929   case BO_GE:
2930     Result = (LHSValue >= RHSValue);
2931     break;
2932   }
2933 
2934   return true;
2935 }
2936 
2937 static bool handleCompareOpForVector(const APValue &LHSValue,
2938                                      BinaryOperatorKind Opcode,
2939                                      const APValue &RHSValue, APInt &Result) {
2940   // The result is always an int type, however operands match the first.
2941   if (LHSValue.getKind() == APValue::Int)
2942     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2943                                           RHSValue.getInt(), Result);
2944   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2945   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2946                                         RHSValue.getFloat(), Result);
2947 }
2948 
2949 // Perform binary operations for vector types, in place on the LHS.
2950 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2951                                     BinaryOperatorKind Opcode,
2952                                     APValue &LHSValue,
2953                                     const APValue &RHSValue) {
2954   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2955          "Operation not supported on vector types");
2956 
2957   const auto *VT = E->getType()->castAs<VectorType>();
2958   unsigned NumElements = VT->getNumElements();
2959   QualType EltTy = VT->getElementType();
2960 
2961   // In the cases (typically C as I've observed) where we aren't evaluating
2962   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2963   // just give up.
2964   if (!LHSValue.isVector()) {
2965     assert(LHSValue.isLValue() &&
2966            "A vector result that isn't a vector OR uncalculated LValue");
2967     Info.FFDiag(E);
2968     return false;
2969   }
2970 
2971   assert(LHSValue.getVectorLength() == NumElements &&
2972          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2973 
2974   SmallVector<APValue, 4> ResultElements;
2975 
2976   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2977     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2978     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2979 
2980     if (EltTy->isIntegerType()) {
2981       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2982                        EltTy->isUnsignedIntegerType()};
2983       bool Success = true;
2984 
2985       if (BinaryOperator::isLogicalOp(Opcode))
2986         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2987       else if (BinaryOperator::isComparisonOp(Opcode))
2988         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2989       else
2990         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2991                                     RHSElt.getInt(), EltResult);
2992 
2993       if (!Success) {
2994         Info.FFDiag(E);
2995         return false;
2996       }
2997       ResultElements.emplace_back(EltResult);
2998 
2999     } else if (EltTy->isFloatingType()) {
3000       assert(LHSElt.getKind() == APValue::Float &&
3001              RHSElt.getKind() == APValue::Float &&
3002              "Mismatched LHS/RHS/Result Type");
3003       APFloat LHSFloat = LHSElt.getFloat();
3004 
3005       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3006                                  RHSElt.getFloat())) {
3007         Info.FFDiag(E);
3008         return false;
3009       }
3010 
3011       ResultElements.emplace_back(LHSFloat);
3012     }
3013   }
3014 
3015   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3016   return true;
3017 }
3018 
3019 /// Cast an lvalue referring to a base subobject to a derived class, by
3020 /// truncating the lvalue's path to the given length.
3021 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3022                                const RecordDecl *TruncatedType,
3023                                unsigned TruncatedElements) {
3024   SubobjectDesignator &D = Result.Designator;
3025 
3026   // Check we actually point to a derived class object.
3027   if (TruncatedElements == D.Entries.size())
3028     return true;
3029   assert(TruncatedElements >= D.MostDerivedPathLength &&
3030          "not casting to a derived class");
3031   if (!Result.checkSubobject(Info, E, CSK_Derived))
3032     return false;
3033 
3034   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3035   const RecordDecl *RD = TruncatedType;
3036   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3037     if (RD->isInvalidDecl()) return false;
3038     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3039     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3040     if (isVirtualBaseClass(D.Entries[I]))
3041       Result.Offset -= Layout.getVBaseClassOffset(Base);
3042     else
3043       Result.Offset -= Layout.getBaseClassOffset(Base);
3044     RD = Base;
3045   }
3046   D.Entries.resize(TruncatedElements);
3047   return true;
3048 }
3049 
3050 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3051                                    const CXXRecordDecl *Derived,
3052                                    const CXXRecordDecl *Base,
3053                                    const ASTRecordLayout *RL = nullptr) {
3054   if (!RL) {
3055     if (Derived->isInvalidDecl()) return false;
3056     RL = &Info.Ctx.getASTRecordLayout(Derived);
3057   }
3058 
3059   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3060   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3061   return true;
3062 }
3063 
3064 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3065                              const CXXRecordDecl *DerivedDecl,
3066                              const CXXBaseSpecifier *Base) {
3067   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3068 
3069   if (!Base->isVirtual())
3070     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3071 
3072   SubobjectDesignator &D = Obj.Designator;
3073   if (D.Invalid)
3074     return false;
3075 
3076   // Extract most-derived object and corresponding type.
3077   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3078   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3079     return false;
3080 
3081   // Find the virtual base class.
3082   if (DerivedDecl->isInvalidDecl()) return false;
3083   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3084   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3085   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3086   return true;
3087 }
3088 
3089 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3090                                  QualType Type, LValue &Result) {
3091   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3092                                      PathE = E->path_end();
3093        PathI != PathE; ++PathI) {
3094     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3095                           *PathI))
3096       return false;
3097     Type = (*PathI)->getType();
3098   }
3099   return true;
3100 }
3101 
3102 /// Cast an lvalue referring to a derived class to a known base subobject.
3103 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3104                             const CXXRecordDecl *DerivedRD,
3105                             const CXXRecordDecl *BaseRD) {
3106   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3107                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3108   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3109     llvm_unreachable("Class must be derived from the passed in base class!");
3110 
3111   for (CXXBasePathElement &Elem : Paths.front())
3112     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3113       return false;
3114   return true;
3115 }
3116 
3117 /// Update LVal to refer to the given field, which must be a member of the type
3118 /// currently described by LVal.
3119 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3120                                const FieldDecl *FD,
3121                                const ASTRecordLayout *RL = nullptr) {
3122   if (!RL) {
3123     if (FD->getParent()->isInvalidDecl()) return false;
3124     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3125   }
3126 
3127   unsigned I = FD->getFieldIndex();
3128   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3129   LVal.addDecl(Info, E, FD);
3130   return true;
3131 }
3132 
3133 /// Update LVal to refer to the given indirect field.
3134 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3135                                        LValue &LVal,
3136                                        const IndirectFieldDecl *IFD) {
3137   for (const auto *C : IFD->chain())
3138     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3139       return false;
3140   return true;
3141 }
3142 
3143 /// Get the size of the given type in char units.
3144 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3145                          QualType Type, CharUnits &Size) {
3146   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3147   // extension.
3148   if (Type->isVoidType() || Type->isFunctionType()) {
3149     Size = CharUnits::One();
3150     return true;
3151   }
3152 
3153   if (Type->isDependentType()) {
3154     Info.FFDiag(Loc);
3155     return false;
3156   }
3157 
3158   if (!Type->isConstantSizeType()) {
3159     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3160     // FIXME: Better diagnostic.
3161     Info.FFDiag(Loc);
3162     return false;
3163   }
3164 
3165   Size = Info.Ctx.getTypeSizeInChars(Type);
3166   return true;
3167 }
3168 
3169 /// Update a pointer value to model pointer arithmetic.
3170 /// \param Info - Information about the ongoing evaluation.
3171 /// \param E - The expression being evaluated, for diagnostic purposes.
3172 /// \param LVal - The pointer value to be updated.
3173 /// \param EltTy - The pointee type represented by LVal.
3174 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3175 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3176                                         LValue &LVal, QualType EltTy,
3177                                         APSInt Adjustment) {
3178   CharUnits SizeOfPointee;
3179   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3180     return false;
3181 
3182   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3183   return true;
3184 }
3185 
3186 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3187                                         LValue &LVal, QualType EltTy,
3188                                         int64_t Adjustment) {
3189   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3190                                      APSInt::get(Adjustment));
3191 }
3192 
3193 /// Update an lvalue to refer to a component of a complex number.
3194 /// \param Info - Information about the ongoing evaluation.
3195 /// \param LVal - The lvalue to be updated.
3196 /// \param EltTy - The complex number's component type.
3197 /// \param Imag - False for the real component, true for the imaginary.
3198 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3199                                        LValue &LVal, QualType EltTy,
3200                                        bool Imag) {
3201   if (Imag) {
3202     CharUnits SizeOfComponent;
3203     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3204       return false;
3205     LVal.Offset += SizeOfComponent;
3206   }
3207   LVal.addComplex(Info, E, EltTy, Imag);
3208   return true;
3209 }
3210 
3211 /// Try to evaluate the initializer for a variable declaration.
3212 ///
3213 /// \param Info   Information about the ongoing evaluation.
3214 /// \param E      An expression to be used when printing diagnostics.
3215 /// \param VD     The variable whose initializer should be obtained.
3216 /// \param Version The version of the variable within the frame.
3217 /// \param Frame  The frame in which the variable was created. Must be null
3218 ///               if this variable is not local to the evaluation.
3219 /// \param Result Filled in with a pointer to the value of the variable.
3220 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3221                                 const VarDecl *VD, CallStackFrame *Frame,
3222                                 unsigned Version, APValue *&Result) {
3223   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3224 
3225   // If this is a local variable, dig out its value.
3226   if (Frame) {
3227     Result = Frame->getTemporary(VD, Version);
3228     if (Result)
3229       return true;
3230 
3231     if (!isa<ParmVarDecl>(VD)) {
3232       // Assume variables referenced within a lambda's call operator that were
3233       // not declared within the call operator are captures and during checking
3234       // of a potential constant expression, assume they are unknown constant
3235       // expressions.
3236       assert(isLambdaCallOperator(Frame->Callee) &&
3237              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3238              "missing value for local variable");
3239       if (Info.checkingPotentialConstantExpression())
3240         return false;
3241       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3242       // still reachable at all?
3243       Info.FFDiag(E->getBeginLoc(),
3244                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3245           << "captures not currently allowed";
3246       return false;
3247     }
3248   }
3249 
3250   // If we're currently evaluating the initializer of this declaration, use that
3251   // in-flight value.
3252   if (Info.EvaluatingDecl == Base) {
3253     Result = Info.EvaluatingDeclValue;
3254     return true;
3255   }
3256 
3257   if (isa<ParmVarDecl>(VD)) {
3258     // Assume parameters of a potential constant expression are usable in
3259     // constant expressions.
3260     if (!Info.checkingPotentialConstantExpression() ||
3261         !Info.CurrentCall->Callee ||
3262         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3263       if (Info.getLangOpts().CPlusPlus11) {
3264         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3265             << VD;
3266         NoteLValueLocation(Info, Base);
3267       } else {
3268         Info.FFDiag(E);
3269       }
3270     }
3271     return false;
3272   }
3273 
3274   // Dig out the initializer, and use the declaration which it's attached to.
3275   // FIXME: We should eventually check whether the variable has a reachable
3276   // initializing declaration.
3277   const Expr *Init = VD->getAnyInitializer(VD);
3278   if (!Init) {
3279     // Don't diagnose during potential constant expression checking; an
3280     // initializer might be added later.
3281     if (!Info.checkingPotentialConstantExpression()) {
3282       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3283         << VD;
3284       NoteLValueLocation(Info, Base);
3285     }
3286     return false;
3287   }
3288 
3289   if (Init->isValueDependent()) {
3290     // The DeclRefExpr is not value-dependent, but the variable it refers to
3291     // has a value-dependent initializer. This should only happen in
3292     // constant-folding cases, where the variable is not actually of a suitable
3293     // type for use in a constant expression (otherwise the DeclRefExpr would
3294     // have been value-dependent too), so diagnose that.
3295     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3296     if (!Info.checkingPotentialConstantExpression()) {
3297       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3298                          ? diag::note_constexpr_ltor_non_constexpr
3299                          : diag::note_constexpr_ltor_non_integral, 1)
3300           << VD << VD->getType();
3301       NoteLValueLocation(Info, Base);
3302     }
3303     return false;
3304   }
3305 
3306   // Check that we can fold the initializer. In C++, we will have already done
3307   // this in the cases where it matters for conformance.
3308   if (!VD->evaluateValue()) {
3309     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3310     NoteLValueLocation(Info, Base);
3311     return false;
3312   }
3313 
3314   // Check that the variable is actually usable in constant expressions. For a
3315   // const integral variable or a reference, we might have a non-constant
3316   // initializer that we can nonetheless evaluate the initializer for. Such
3317   // variables are not usable in constant expressions. In C++98, the
3318   // initializer also syntactically needs to be an ICE.
3319   //
3320   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3321   // expressions here; doing so would regress diagnostics for things like
3322   // reading from a volatile constexpr variable.
3323   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3324        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3325       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3326        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3327     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3328     NoteLValueLocation(Info, Base);
3329   }
3330 
3331   // Never use the initializer of a weak variable, not even for constant
3332   // folding. We can't be sure that this is the definition that will be used.
3333   if (VD->isWeak()) {
3334     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3335     NoteLValueLocation(Info, Base);
3336     return false;
3337   }
3338 
3339   Result = VD->getEvaluatedValue();
3340   return true;
3341 }
3342 
3343 /// Get the base index of the given base class within an APValue representing
3344 /// the given derived class.
3345 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3346                              const CXXRecordDecl *Base) {
3347   Base = Base->getCanonicalDecl();
3348   unsigned Index = 0;
3349   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3350          E = Derived->bases_end(); I != E; ++I, ++Index) {
3351     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3352       return Index;
3353   }
3354 
3355   llvm_unreachable("base class missing from derived class's bases list");
3356 }
3357 
3358 /// Extract the value of a character from a string literal.
3359 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3360                                             uint64_t Index) {
3361   assert(!isa<SourceLocExpr>(Lit) &&
3362          "SourceLocExpr should have already been converted to a StringLiteral");
3363 
3364   // FIXME: Support MakeStringConstant
3365   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3366     std::string Str;
3367     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3368     assert(Index <= Str.size() && "Index too large");
3369     return APSInt::getUnsigned(Str.c_str()[Index]);
3370   }
3371 
3372   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3373     Lit = PE->getFunctionName();
3374   const StringLiteral *S = cast<StringLiteral>(Lit);
3375   const ConstantArrayType *CAT =
3376       Info.Ctx.getAsConstantArrayType(S->getType());
3377   assert(CAT && "string literal isn't an array");
3378   QualType CharType = CAT->getElementType();
3379   assert(CharType->isIntegerType() && "unexpected character type");
3380 
3381   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3382                CharType->isUnsignedIntegerType());
3383   if (Index < S->getLength())
3384     Value = S->getCodeUnit(Index);
3385   return Value;
3386 }
3387 
3388 // Expand a string literal into an array of characters.
3389 //
3390 // FIXME: This is inefficient; we should probably introduce something similar
3391 // to the LLVM ConstantDataArray to make this cheaper.
3392 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3393                                 APValue &Result,
3394                                 QualType AllocType = QualType()) {
3395   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3396       AllocType.isNull() ? S->getType() : AllocType);
3397   assert(CAT && "string literal isn't an array");
3398   QualType CharType = CAT->getElementType();
3399   assert(CharType->isIntegerType() && "unexpected character type");
3400 
3401   unsigned Elts = CAT->getSize().getZExtValue();
3402   Result = APValue(APValue::UninitArray(),
3403                    std::min(S->getLength(), Elts), Elts);
3404   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3405                CharType->isUnsignedIntegerType());
3406   if (Result.hasArrayFiller())
3407     Result.getArrayFiller() = APValue(Value);
3408   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3409     Value = S->getCodeUnit(I);
3410     Result.getArrayInitializedElt(I) = APValue(Value);
3411   }
3412 }
3413 
3414 // Expand an array so that it has more than Index filled elements.
3415 static void expandArray(APValue &Array, unsigned Index) {
3416   unsigned Size = Array.getArraySize();
3417   assert(Index < Size);
3418 
3419   // Always at least double the number of elements for which we store a value.
3420   unsigned OldElts = Array.getArrayInitializedElts();
3421   unsigned NewElts = std::max(Index+1, OldElts * 2);
3422   NewElts = std::min(Size, std::max(NewElts, 8u));
3423 
3424   // Copy the data across.
3425   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3426   for (unsigned I = 0; I != OldElts; ++I)
3427     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3428   for (unsigned I = OldElts; I != NewElts; ++I)
3429     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3430   if (NewValue.hasArrayFiller())
3431     NewValue.getArrayFiller() = Array.getArrayFiller();
3432   Array.swap(NewValue);
3433 }
3434 
3435 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3436 /// conversion. If it's of class type, we may assume that the copy operation
3437 /// is trivial. Note that this is never true for a union type with fields
3438 /// (because the copy always "reads" the active member) and always true for
3439 /// a non-class type.
3440 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3441 static bool isReadByLvalueToRvalueConversion(QualType T) {
3442   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3443   return !RD || isReadByLvalueToRvalueConversion(RD);
3444 }
3445 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3446   // FIXME: A trivial copy of a union copies the object representation, even if
3447   // the union is empty.
3448   if (RD->isUnion())
3449     return !RD->field_empty();
3450   if (RD->isEmpty())
3451     return false;
3452 
3453   for (auto *Field : RD->fields())
3454     if (!Field->isUnnamedBitfield() &&
3455         isReadByLvalueToRvalueConversion(Field->getType()))
3456       return true;
3457 
3458   for (auto &BaseSpec : RD->bases())
3459     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3460       return true;
3461 
3462   return false;
3463 }
3464 
3465 /// Diagnose an attempt to read from any unreadable field within the specified
3466 /// type, which might be a class type.
3467 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3468                                   QualType T) {
3469   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3470   if (!RD)
3471     return false;
3472 
3473   if (!RD->hasMutableFields())
3474     return false;
3475 
3476   for (auto *Field : RD->fields()) {
3477     // If we're actually going to read this field in some way, then it can't
3478     // be mutable. If we're in a union, then assigning to a mutable field
3479     // (even an empty one) can change the active member, so that's not OK.
3480     // FIXME: Add core issue number for the union case.
3481     if (Field->isMutable() &&
3482         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3483       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3484       Info.Note(Field->getLocation(), diag::note_declared_at);
3485       return true;
3486     }
3487 
3488     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3489       return true;
3490   }
3491 
3492   for (auto &BaseSpec : RD->bases())
3493     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3494       return true;
3495 
3496   // All mutable fields were empty, and thus not actually read.
3497   return false;
3498 }
3499 
3500 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3501                                         APValue::LValueBase Base,
3502                                         bool MutableSubobject = false) {
3503   // A temporary or transient heap allocation we created.
3504   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3505     return true;
3506 
3507   switch (Info.IsEvaluatingDecl) {
3508   case EvalInfo::EvaluatingDeclKind::None:
3509     return false;
3510 
3511   case EvalInfo::EvaluatingDeclKind::Ctor:
3512     // The variable whose initializer we're evaluating.
3513     if (Info.EvaluatingDecl == Base)
3514       return true;
3515 
3516     // A temporary lifetime-extended by the variable whose initializer we're
3517     // evaluating.
3518     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3519       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3520         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3521     return false;
3522 
3523   case EvalInfo::EvaluatingDeclKind::Dtor:
3524     // C++2a [expr.const]p6:
3525     //   [during constant destruction] the lifetime of a and its non-mutable
3526     //   subobjects (but not its mutable subobjects) [are] considered to start
3527     //   within e.
3528     if (MutableSubobject || Base != Info.EvaluatingDecl)
3529       return false;
3530     // FIXME: We can meaningfully extend this to cover non-const objects, but
3531     // we will need special handling: we should be able to access only
3532     // subobjects of such objects that are themselves declared const.
3533     QualType T = getType(Base);
3534     return T.isConstQualified() || T->isReferenceType();
3535   }
3536 
3537   llvm_unreachable("unknown evaluating decl kind");
3538 }
3539 
3540 namespace {
3541 /// A handle to a complete object (an object that is not a subobject of
3542 /// another object).
3543 struct CompleteObject {
3544   /// The identity of the object.
3545   APValue::LValueBase Base;
3546   /// The value of the complete object.
3547   APValue *Value;
3548   /// The type of the complete object.
3549   QualType Type;
3550 
3551   CompleteObject() : Value(nullptr) {}
3552   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3553       : Base(Base), Value(Value), Type(Type) {}
3554 
3555   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3556     // If this isn't a "real" access (eg, if it's just accessing the type
3557     // info), allow it. We assume the type doesn't change dynamically for
3558     // subobjects of constexpr objects (even though we'd hit UB here if it
3559     // did). FIXME: Is this right?
3560     if (!isAnyAccess(AK))
3561       return true;
3562 
3563     // In C++14 onwards, it is permitted to read a mutable member whose
3564     // lifetime began within the evaluation.
3565     // FIXME: Should we also allow this in C++11?
3566     if (!Info.getLangOpts().CPlusPlus14)
3567       return false;
3568     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3569   }
3570 
3571   explicit operator bool() const { return !Type.isNull(); }
3572 };
3573 } // end anonymous namespace
3574 
3575 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3576                                  bool IsMutable = false) {
3577   // C++ [basic.type.qualifier]p1:
3578   // - A const object is an object of type const T or a non-mutable subobject
3579   //   of a const object.
3580   if (ObjType.isConstQualified() && !IsMutable)
3581     SubobjType.addConst();
3582   // - A volatile object is an object of type const T or a subobject of a
3583   //   volatile object.
3584   if (ObjType.isVolatileQualified())
3585     SubobjType.addVolatile();
3586   return SubobjType;
3587 }
3588 
3589 /// Find the designated sub-object of an rvalue.
3590 template<typename SubobjectHandler>
3591 typename SubobjectHandler::result_type
3592 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3593               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3594   if (Sub.Invalid)
3595     // A diagnostic will have already been produced.
3596     return handler.failed();
3597   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3598     if (Info.getLangOpts().CPlusPlus11)
3599       Info.FFDiag(E, Sub.isOnePastTheEnd()
3600                          ? diag::note_constexpr_access_past_end
3601                          : diag::note_constexpr_access_unsized_array)
3602           << handler.AccessKind;
3603     else
3604       Info.FFDiag(E);
3605     return handler.failed();
3606   }
3607 
3608   APValue *O = Obj.Value;
3609   QualType ObjType = Obj.Type;
3610   const FieldDecl *LastField = nullptr;
3611   const FieldDecl *VolatileField = nullptr;
3612 
3613   // Walk the designator's path to find the subobject.
3614   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3615     // Reading an indeterminate value is undefined, but assigning over one is OK.
3616     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3617         (O->isIndeterminate() &&
3618          !isValidIndeterminateAccess(handler.AccessKind))) {
3619       if (!Info.checkingPotentialConstantExpression())
3620         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3621             << handler.AccessKind << O->isIndeterminate();
3622       return handler.failed();
3623     }
3624 
3625     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3626     //    const and volatile semantics are not applied on an object under
3627     //    {con,de}struction.
3628     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3629         ObjType->isRecordType() &&
3630         Info.isEvaluatingCtorDtor(
3631             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3632                                          Sub.Entries.begin() + I)) !=
3633                           ConstructionPhase::None) {
3634       ObjType = Info.Ctx.getCanonicalType(ObjType);
3635       ObjType.removeLocalConst();
3636       ObjType.removeLocalVolatile();
3637     }
3638 
3639     // If this is our last pass, check that the final object type is OK.
3640     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3641       // Accesses to volatile objects are prohibited.
3642       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3643         if (Info.getLangOpts().CPlusPlus) {
3644           int DiagKind;
3645           SourceLocation Loc;
3646           const NamedDecl *Decl = nullptr;
3647           if (VolatileField) {
3648             DiagKind = 2;
3649             Loc = VolatileField->getLocation();
3650             Decl = VolatileField;
3651           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3652             DiagKind = 1;
3653             Loc = VD->getLocation();
3654             Decl = VD;
3655           } else {
3656             DiagKind = 0;
3657             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3658               Loc = E->getExprLoc();
3659           }
3660           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3661               << handler.AccessKind << DiagKind << Decl;
3662           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3663         } else {
3664           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3665         }
3666         return handler.failed();
3667       }
3668 
3669       // If we are reading an object of class type, there may still be more
3670       // things we need to check: if there are any mutable subobjects, we
3671       // cannot perform this read. (This only happens when performing a trivial
3672       // copy or assignment.)
3673       if (ObjType->isRecordType() &&
3674           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3675           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3676         return handler.failed();
3677     }
3678 
3679     if (I == N) {
3680       if (!handler.found(*O, ObjType))
3681         return false;
3682 
3683       // If we modified a bit-field, truncate it to the right width.
3684       if (isModification(handler.AccessKind) &&
3685           LastField && LastField->isBitField() &&
3686           !truncateBitfieldValue(Info, E, *O, LastField))
3687         return false;
3688 
3689       return true;
3690     }
3691 
3692     LastField = nullptr;
3693     if (ObjType->isArrayType()) {
3694       // Next subobject is an array element.
3695       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3696       assert(CAT && "vla in literal type?");
3697       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3698       if (CAT->getSize().ule(Index)) {
3699         // Note, it should not be possible to form a pointer with a valid
3700         // designator which points more than one past the end of the array.
3701         if (Info.getLangOpts().CPlusPlus11)
3702           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3703             << handler.AccessKind;
3704         else
3705           Info.FFDiag(E);
3706         return handler.failed();
3707       }
3708 
3709       ObjType = CAT->getElementType();
3710 
3711       if (O->getArrayInitializedElts() > Index)
3712         O = &O->getArrayInitializedElt(Index);
3713       else if (!isRead(handler.AccessKind)) {
3714         expandArray(*O, Index);
3715         O = &O->getArrayInitializedElt(Index);
3716       } else
3717         O = &O->getArrayFiller();
3718     } else if (ObjType->isAnyComplexType()) {
3719       // Next subobject is a complex number.
3720       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3721       if (Index > 1) {
3722         if (Info.getLangOpts().CPlusPlus11)
3723           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3724             << handler.AccessKind;
3725         else
3726           Info.FFDiag(E);
3727         return handler.failed();
3728       }
3729 
3730       ObjType = getSubobjectType(
3731           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3732 
3733       assert(I == N - 1 && "extracting subobject of scalar?");
3734       if (O->isComplexInt()) {
3735         return handler.found(Index ? O->getComplexIntImag()
3736                                    : O->getComplexIntReal(), ObjType);
3737       } else {
3738         assert(O->isComplexFloat());
3739         return handler.found(Index ? O->getComplexFloatImag()
3740                                    : O->getComplexFloatReal(), ObjType);
3741       }
3742     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3743       if (Field->isMutable() &&
3744           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3745         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3746           << handler.AccessKind << Field;
3747         Info.Note(Field->getLocation(), diag::note_declared_at);
3748         return handler.failed();
3749       }
3750 
3751       // Next subobject is a class, struct or union field.
3752       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3753       if (RD->isUnion()) {
3754         const FieldDecl *UnionField = O->getUnionField();
3755         if (!UnionField ||
3756             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3757           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3758             // Placement new onto an inactive union member makes it active.
3759             O->setUnion(Field, APValue());
3760           } else {
3761             // FIXME: If O->getUnionValue() is absent, report that there's no
3762             // active union member rather than reporting the prior active union
3763             // member. We'll need to fix nullptr_t to not use APValue() as its
3764             // representation first.
3765             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3766                 << handler.AccessKind << Field << !UnionField << UnionField;
3767             return handler.failed();
3768           }
3769         }
3770         O = &O->getUnionValue();
3771       } else
3772         O = &O->getStructField(Field->getFieldIndex());
3773 
3774       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3775       LastField = Field;
3776       if (Field->getType().isVolatileQualified())
3777         VolatileField = Field;
3778     } else {
3779       // Next subobject is a base class.
3780       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3781       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3782       O = &O->getStructBase(getBaseIndex(Derived, Base));
3783 
3784       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3785     }
3786   }
3787 }
3788 
3789 namespace {
3790 struct ExtractSubobjectHandler {
3791   EvalInfo &Info;
3792   const Expr *E;
3793   APValue &Result;
3794   const AccessKinds AccessKind;
3795 
3796   typedef bool result_type;
3797   bool failed() { return false; }
3798   bool found(APValue &Subobj, QualType SubobjType) {
3799     Result = Subobj;
3800     if (AccessKind == AK_ReadObjectRepresentation)
3801       return true;
3802     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3803   }
3804   bool found(APSInt &Value, QualType SubobjType) {
3805     Result = APValue(Value);
3806     return true;
3807   }
3808   bool found(APFloat &Value, QualType SubobjType) {
3809     Result = APValue(Value);
3810     return true;
3811   }
3812 };
3813 } // end anonymous namespace
3814 
3815 /// Extract the designated sub-object of an rvalue.
3816 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3817                              const CompleteObject &Obj,
3818                              const SubobjectDesignator &Sub, APValue &Result,
3819                              AccessKinds AK = AK_Read) {
3820   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3821   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3822   return findSubobject(Info, E, Obj, Sub, Handler);
3823 }
3824 
3825 namespace {
3826 struct ModifySubobjectHandler {
3827   EvalInfo &Info;
3828   APValue &NewVal;
3829   const Expr *E;
3830 
3831   typedef bool result_type;
3832   static const AccessKinds AccessKind = AK_Assign;
3833 
3834   bool checkConst(QualType QT) {
3835     // Assigning to a const object has undefined behavior.
3836     if (QT.isConstQualified()) {
3837       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3838       return false;
3839     }
3840     return true;
3841   }
3842 
3843   bool failed() { return false; }
3844   bool found(APValue &Subobj, QualType SubobjType) {
3845     if (!checkConst(SubobjType))
3846       return false;
3847     // We've been given ownership of NewVal, so just swap it in.
3848     Subobj.swap(NewVal);
3849     return true;
3850   }
3851   bool found(APSInt &Value, QualType SubobjType) {
3852     if (!checkConst(SubobjType))
3853       return false;
3854     if (!NewVal.isInt()) {
3855       // Maybe trying to write a cast pointer value into a complex?
3856       Info.FFDiag(E);
3857       return false;
3858     }
3859     Value = NewVal.getInt();
3860     return true;
3861   }
3862   bool found(APFloat &Value, QualType SubobjType) {
3863     if (!checkConst(SubobjType))
3864       return false;
3865     Value = NewVal.getFloat();
3866     return true;
3867   }
3868 };
3869 } // end anonymous namespace
3870 
3871 const AccessKinds ModifySubobjectHandler::AccessKind;
3872 
3873 /// Update the designated sub-object of an rvalue to the given value.
3874 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3875                             const CompleteObject &Obj,
3876                             const SubobjectDesignator &Sub,
3877                             APValue &NewVal) {
3878   ModifySubobjectHandler Handler = { Info, NewVal, E };
3879   return findSubobject(Info, E, Obj, Sub, Handler);
3880 }
3881 
3882 /// Find the position where two subobject designators diverge, or equivalently
3883 /// the length of the common initial subsequence.
3884 static unsigned FindDesignatorMismatch(QualType ObjType,
3885                                        const SubobjectDesignator &A,
3886                                        const SubobjectDesignator &B,
3887                                        bool &WasArrayIndex) {
3888   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3889   for (/**/; I != N; ++I) {
3890     if (!ObjType.isNull() &&
3891         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3892       // Next subobject is an array element.
3893       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3894         WasArrayIndex = true;
3895         return I;
3896       }
3897       if (ObjType->isAnyComplexType())
3898         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3899       else
3900         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3901     } else {
3902       if (A.Entries[I].getAsBaseOrMember() !=
3903           B.Entries[I].getAsBaseOrMember()) {
3904         WasArrayIndex = false;
3905         return I;
3906       }
3907       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3908         // Next subobject is a field.
3909         ObjType = FD->getType();
3910       else
3911         // Next subobject is a base class.
3912         ObjType = QualType();
3913     }
3914   }
3915   WasArrayIndex = false;
3916   return I;
3917 }
3918 
3919 /// Determine whether the given subobject designators refer to elements of the
3920 /// same array object.
3921 static bool AreElementsOfSameArray(QualType ObjType,
3922                                    const SubobjectDesignator &A,
3923                                    const SubobjectDesignator &B) {
3924   if (A.Entries.size() != B.Entries.size())
3925     return false;
3926 
3927   bool IsArray = A.MostDerivedIsArrayElement;
3928   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3929     // A is a subobject of the array element.
3930     return false;
3931 
3932   // If A (and B) designates an array element, the last entry will be the array
3933   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3934   // of length 1' case, and the entire path must match.
3935   bool WasArrayIndex;
3936   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3937   return CommonLength >= A.Entries.size() - IsArray;
3938 }
3939 
3940 /// Find the complete object to which an LValue refers.
3941 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3942                                          AccessKinds AK, const LValue &LVal,
3943                                          QualType LValType) {
3944   if (LVal.InvalidBase) {
3945     Info.FFDiag(E);
3946     return CompleteObject();
3947   }
3948 
3949   if (!LVal.Base) {
3950     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3951     return CompleteObject();
3952   }
3953 
3954   CallStackFrame *Frame = nullptr;
3955   unsigned Depth = 0;
3956   if (LVal.getLValueCallIndex()) {
3957     std::tie(Frame, Depth) =
3958         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3959     if (!Frame) {
3960       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3961         << AK << LVal.Base.is<const ValueDecl*>();
3962       NoteLValueLocation(Info, LVal.Base);
3963       return CompleteObject();
3964     }
3965   }
3966 
3967   bool IsAccess = isAnyAccess(AK);
3968 
3969   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3970   // is not a constant expression (even if the object is non-volatile). We also
3971   // apply this rule to C++98, in order to conform to the expected 'volatile'
3972   // semantics.
3973   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3974     if (Info.getLangOpts().CPlusPlus)
3975       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3976         << AK << LValType;
3977     else
3978       Info.FFDiag(E);
3979     return CompleteObject();
3980   }
3981 
3982   // Compute value storage location and type of base object.
3983   APValue *BaseVal = nullptr;
3984   QualType BaseType = getType(LVal.Base);
3985 
3986   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3987       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3988     // This is the object whose initializer we're evaluating, so its lifetime
3989     // started in the current evaluation.
3990     BaseVal = Info.EvaluatingDeclValue;
3991   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3992     // Allow reading from a GUID declaration.
3993     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3994       if (isModification(AK)) {
3995         // All the remaining cases do not permit modification of the object.
3996         Info.FFDiag(E, diag::note_constexpr_modify_global);
3997         return CompleteObject();
3998       }
3999       APValue &V = GD->getAsAPValue();
4000       if (V.isAbsent()) {
4001         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4002             << GD->getType();
4003         return CompleteObject();
4004       }
4005       return CompleteObject(LVal.Base, &V, GD->getType());
4006     }
4007 
4008     // Allow reading from template parameter objects.
4009     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4010       if (isModification(AK)) {
4011         Info.FFDiag(E, diag::note_constexpr_modify_global);
4012         return CompleteObject();
4013       }
4014       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4015                             TPO->getType());
4016     }
4017 
4018     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4019     // In C++11, constexpr, non-volatile variables initialized with constant
4020     // expressions are constant expressions too. Inside constexpr functions,
4021     // parameters are constant expressions even if they're non-const.
4022     // In C++1y, objects local to a constant expression (those with a Frame) are
4023     // both readable and writable inside constant expressions.
4024     // In C, such things can also be folded, although they are not ICEs.
4025     const VarDecl *VD = dyn_cast<VarDecl>(D);
4026     if (VD) {
4027       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4028         VD = VDef;
4029     }
4030     if (!VD || VD->isInvalidDecl()) {
4031       Info.FFDiag(E);
4032       return CompleteObject();
4033     }
4034 
4035     bool IsConstant = BaseType.isConstant(Info.Ctx);
4036 
4037     // Unless we're looking at a local variable or argument in a constexpr call,
4038     // the variable we're reading must be const.
4039     if (!Frame) {
4040       if (IsAccess && isa<ParmVarDecl>(VD)) {
4041         // Access of a parameter that's not associated with a frame isn't going
4042         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4043         // suitable diagnostic.
4044       } else if (Info.getLangOpts().CPlusPlus14 &&
4045                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4046         // OK, we can read and modify an object if we're in the process of
4047         // evaluating its initializer, because its lifetime began in this
4048         // evaluation.
4049       } else if (isModification(AK)) {
4050         // All the remaining cases do not permit modification of the object.
4051         Info.FFDiag(E, diag::note_constexpr_modify_global);
4052         return CompleteObject();
4053       } else if (VD->isConstexpr()) {
4054         // OK, we can read this variable.
4055       } else if (BaseType->isIntegralOrEnumerationType()) {
4056         if (!IsConstant) {
4057           if (!IsAccess)
4058             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4059           if (Info.getLangOpts().CPlusPlus) {
4060             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4061             Info.Note(VD->getLocation(), diag::note_declared_at);
4062           } else {
4063             Info.FFDiag(E);
4064           }
4065           return CompleteObject();
4066         }
4067       } else if (!IsAccess) {
4068         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4069       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4070                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4071         // This variable might end up being constexpr. Don't diagnose it yet.
4072       } else if (IsConstant) {
4073         // Keep evaluating to see what we can do. In particular, we support
4074         // folding of const floating-point types, in order to make static const
4075         // data members of such types (supported as an extension) more useful.
4076         if (Info.getLangOpts().CPlusPlus) {
4077           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4078                               ? diag::note_constexpr_ltor_non_constexpr
4079                               : diag::note_constexpr_ltor_non_integral, 1)
4080               << VD << BaseType;
4081           Info.Note(VD->getLocation(), diag::note_declared_at);
4082         } else {
4083           Info.CCEDiag(E);
4084         }
4085       } else {
4086         // Never allow reading a non-const value.
4087         if (Info.getLangOpts().CPlusPlus) {
4088           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4089                              ? diag::note_constexpr_ltor_non_constexpr
4090                              : diag::note_constexpr_ltor_non_integral, 1)
4091               << VD << BaseType;
4092           Info.Note(VD->getLocation(), diag::note_declared_at);
4093         } else {
4094           Info.FFDiag(E);
4095         }
4096         return CompleteObject();
4097       }
4098     }
4099 
4100     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4101       return CompleteObject();
4102   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4103     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4104     if (!Alloc) {
4105       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4106       return CompleteObject();
4107     }
4108     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4109                           LVal.Base.getDynamicAllocType());
4110   } else {
4111     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4112 
4113     if (!Frame) {
4114       if (const MaterializeTemporaryExpr *MTE =
4115               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4116         assert(MTE->getStorageDuration() == SD_Static &&
4117                "should have a frame for a non-global materialized temporary");
4118 
4119         // C++20 [expr.const]p4: [DR2126]
4120         //   An object or reference is usable in constant expressions if it is
4121         //   - a temporary object of non-volatile const-qualified literal type
4122         //     whose lifetime is extended to that of a variable that is usable
4123         //     in constant expressions
4124         //
4125         // C++20 [expr.const]p5:
4126         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4127         //   - a non-volatile glvalue that refers to an object that is usable
4128         //     in constant expressions, or
4129         //   - a non-volatile glvalue of literal type that refers to a
4130         //     non-volatile object whose lifetime began within the evaluation
4131         //     of E;
4132         //
4133         // C++11 misses the 'began within the evaluation of e' check and
4134         // instead allows all temporaries, including things like:
4135         //   int &&r = 1;
4136         //   int x = ++r;
4137         //   constexpr int k = r;
4138         // Therefore we use the C++14-onwards rules in C++11 too.
4139         //
4140         // Note that temporaries whose lifetimes began while evaluating a
4141         // variable's constructor are not usable while evaluating the
4142         // corresponding destructor, not even if they're of const-qualified
4143         // types.
4144         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4145             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4146           if (!IsAccess)
4147             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4148           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4149           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4150           return CompleteObject();
4151         }
4152 
4153         BaseVal = MTE->getOrCreateValue(false);
4154         assert(BaseVal && "got reference to unevaluated temporary");
4155       } else {
4156         if (!IsAccess)
4157           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4158         APValue Val;
4159         LVal.moveInto(Val);
4160         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4161             << AK
4162             << Val.getAsString(Info.Ctx,
4163                                Info.Ctx.getLValueReferenceType(LValType));
4164         NoteLValueLocation(Info, LVal.Base);
4165         return CompleteObject();
4166       }
4167     } else {
4168       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4169       assert(BaseVal && "missing value for temporary");
4170     }
4171   }
4172 
4173   // In C++14, we can't safely access any mutable state when we might be
4174   // evaluating after an unmodeled side effect. Parameters are modeled as state
4175   // in the caller, but aren't visible once the call returns, so they can be
4176   // modified in a speculatively-evaluated call.
4177   //
4178   // FIXME: Not all local state is mutable. Allow local constant subobjects
4179   // to be read here (but take care with 'mutable' fields).
4180   unsigned VisibleDepth = Depth;
4181   if (llvm::isa_and_nonnull<ParmVarDecl>(
4182           LVal.Base.dyn_cast<const ValueDecl *>()))
4183     ++VisibleDepth;
4184   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4185        Info.EvalStatus.HasSideEffects) ||
4186       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4187     return CompleteObject();
4188 
4189   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4190 }
4191 
4192 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4193 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4194 /// glvalue referred to by an entity of reference type.
4195 ///
4196 /// \param Info - Information about the ongoing evaluation.
4197 /// \param Conv - The expression for which we are performing the conversion.
4198 ///               Used for diagnostics.
4199 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4200 ///               case of a non-class type).
4201 /// \param LVal - The glvalue on which we are attempting to perform this action.
4202 /// \param RVal - The produced value will be placed here.
4203 /// \param WantObjectRepresentation - If true, we're looking for the object
4204 ///               representation rather than the value, and in particular,
4205 ///               there is no requirement that the result be fully initialized.
4206 static bool
4207 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4208                                const LValue &LVal, APValue &RVal,
4209                                bool WantObjectRepresentation = false) {
4210   if (LVal.Designator.Invalid)
4211     return false;
4212 
4213   // Check for special cases where there is no existing APValue to look at.
4214   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4215 
4216   AccessKinds AK =
4217       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4218 
4219   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4220     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4221       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4222       // initializer until now for such expressions. Such an expression can't be
4223       // an ICE in C, so this only matters for fold.
4224       if (Type.isVolatileQualified()) {
4225         Info.FFDiag(Conv);
4226         return false;
4227       }
4228       APValue Lit;
4229       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4230         return false;
4231       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4232       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4233     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4234       // Special-case character extraction so we don't have to construct an
4235       // APValue for the whole string.
4236       assert(LVal.Designator.Entries.size() <= 1 &&
4237              "Can only read characters from string literals");
4238       if (LVal.Designator.Entries.empty()) {
4239         // Fail for now for LValue to RValue conversion of an array.
4240         // (This shouldn't show up in C/C++, but it could be triggered by a
4241         // weird EvaluateAsRValue call from a tool.)
4242         Info.FFDiag(Conv);
4243         return false;
4244       }
4245       if (LVal.Designator.isOnePastTheEnd()) {
4246         if (Info.getLangOpts().CPlusPlus11)
4247           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4248         else
4249           Info.FFDiag(Conv);
4250         return false;
4251       }
4252       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4253       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4254       return true;
4255     }
4256   }
4257 
4258   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4259   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4260 }
4261 
4262 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4263 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4264                              QualType LValType, APValue &Val) {
4265   if (LVal.Designator.Invalid)
4266     return false;
4267 
4268   if (!Info.getLangOpts().CPlusPlus14) {
4269     Info.FFDiag(E);
4270     return false;
4271   }
4272 
4273   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4274   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4275 }
4276 
4277 namespace {
4278 struct CompoundAssignSubobjectHandler {
4279   EvalInfo &Info;
4280   const CompoundAssignOperator *E;
4281   QualType PromotedLHSType;
4282   BinaryOperatorKind Opcode;
4283   const APValue &RHS;
4284 
4285   static const AccessKinds AccessKind = AK_Assign;
4286 
4287   typedef bool result_type;
4288 
4289   bool checkConst(QualType QT) {
4290     // Assigning to a const object has undefined behavior.
4291     if (QT.isConstQualified()) {
4292       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4293       return false;
4294     }
4295     return true;
4296   }
4297 
4298   bool failed() { return false; }
4299   bool found(APValue &Subobj, QualType SubobjType) {
4300     switch (Subobj.getKind()) {
4301     case APValue::Int:
4302       return found(Subobj.getInt(), SubobjType);
4303     case APValue::Float:
4304       return found(Subobj.getFloat(), SubobjType);
4305     case APValue::ComplexInt:
4306     case APValue::ComplexFloat:
4307       // FIXME: Implement complex compound assignment.
4308       Info.FFDiag(E);
4309       return false;
4310     case APValue::LValue:
4311       return foundPointer(Subobj, SubobjType);
4312     case APValue::Vector:
4313       return foundVector(Subobj, SubobjType);
4314     default:
4315       // FIXME: can this happen?
4316       Info.FFDiag(E);
4317       return false;
4318     }
4319   }
4320 
4321   bool foundVector(APValue &Value, QualType SubobjType) {
4322     if (!checkConst(SubobjType))
4323       return false;
4324 
4325     if (!SubobjType->isVectorType()) {
4326       Info.FFDiag(E);
4327       return false;
4328     }
4329     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4330   }
4331 
4332   bool found(APSInt &Value, QualType SubobjType) {
4333     if (!checkConst(SubobjType))
4334       return false;
4335 
4336     if (!SubobjType->isIntegerType()) {
4337       // We don't support compound assignment on integer-cast-to-pointer
4338       // values.
4339       Info.FFDiag(E);
4340       return false;
4341     }
4342 
4343     if (RHS.isInt()) {
4344       APSInt LHS =
4345           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4346       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4347         return false;
4348       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4349       return true;
4350     } else if (RHS.isFloat()) {
4351       const FPOptions FPO = E->getFPFeaturesInEffect(
4352                                     Info.Ctx.getLangOpts());
4353       APFloat FValue(0.0);
4354       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4355                                   PromotedLHSType, FValue) &&
4356              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4357              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4358                                   Value);
4359     }
4360 
4361     Info.FFDiag(E);
4362     return false;
4363   }
4364   bool found(APFloat &Value, QualType SubobjType) {
4365     return checkConst(SubobjType) &&
4366            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4367                                   Value) &&
4368            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4369            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4370   }
4371   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4372     if (!checkConst(SubobjType))
4373       return false;
4374 
4375     QualType PointeeType;
4376     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4377       PointeeType = PT->getPointeeType();
4378 
4379     if (PointeeType.isNull() || !RHS.isInt() ||
4380         (Opcode != BO_Add && Opcode != BO_Sub)) {
4381       Info.FFDiag(E);
4382       return false;
4383     }
4384 
4385     APSInt Offset = RHS.getInt();
4386     if (Opcode == BO_Sub)
4387       negateAsSigned(Offset);
4388 
4389     LValue LVal;
4390     LVal.setFrom(Info.Ctx, Subobj);
4391     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4392       return false;
4393     LVal.moveInto(Subobj);
4394     return true;
4395   }
4396 };
4397 } // end anonymous namespace
4398 
4399 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4400 
4401 /// Perform a compound assignment of LVal <op>= RVal.
4402 static bool handleCompoundAssignment(EvalInfo &Info,
4403                                      const CompoundAssignOperator *E,
4404                                      const LValue &LVal, QualType LValType,
4405                                      QualType PromotedLValType,
4406                                      BinaryOperatorKind Opcode,
4407                                      const APValue &RVal) {
4408   if (LVal.Designator.Invalid)
4409     return false;
4410 
4411   if (!Info.getLangOpts().CPlusPlus14) {
4412     Info.FFDiag(E);
4413     return false;
4414   }
4415 
4416   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4417   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4418                                              RVal };
4419   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4420 }
4421 
4422 namespace {
4423 struct IncDecSubobjectHandler {
4424   EvalInfo &Info;
4425   const UnaryOperator *E;
4426   AccessKinds AccessKind;
4427   APValue *Old;
4428 
4429   typedef bool result_type;
4430 
4431   bool checkConst(QualType QT) {
4432     // Assigning to a const object has undefined behavior.
4433     if (QT.isConstQualified()) {
4434       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4435       return false;
4436     }
4437     return true;
4438   }
4439 
4440   bool failed() { return false; }
4441   bool found(APValue &Subobj, QualType SubobjType) {
4442     // Stash the old value. Also clear Old, so we don't clobber it later
4443     // if we're post-incrementing a complex.
4444     if (Old) {
4445       *Old = Subobj;
4446       Old = nullptr;
4447     }
4448 
4449     switch (Subobj.getKind()) {
4450     case APValue::Int:
4451       return found(Subobj.getInt(), SubobjType);
4452     case APValue::Float:
4453       return found(Subobj.getFloat(), SubobjType);
4454     case APValue::ComplexInt:
4455       return found(Subobj.getComplexIntReal(),
4456                    SubobjType->castAs<ComplexType>()->getElementType()
4457                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4458     case APValue::ComplexFloat:
4459       return found(Subobj.getComplexFloatReal(),
4460                    SubobjType->castAs<ComplexType>()->getElementType()
4461                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4462     case APValue::LValue:
4463       return foundPointer(Subobj, SubobjType);
4464     default:
4465       // FIXME: can this happen?
4466       Info.FFDiag(E);
4467       return false;
4468     }
4469   }
4470   bool found(APSInt &Value, QualType SubobjType) {
4471     if (!checkConst(SubobjType))
4472       return false;
4473 
4474     if (!SubobjType->isIntegerType()) {
4475       // We don't support increment / decrement on integer-cast-to-pointer
4476       // values.
4477       Info.FFDiag(E);
4478       return false;
4479     }
4480 
4481     if (Old) *Old = APValue(Value);
4482 
4483     // bool arithmetic promotes to int, and the conversion back to bool
4484     // doesn't reduce mod 2^n, so special-case it.
4485     if (SubobjType->isBooleanType()) {
4486       if (AccessKind == AK_Increment)
4487         Value = 1;
4488       else
4489         Value = !Value;
4490       return true;
4491     }
4492 
4493     bool WasNegative = Value.isNegative();
4494     if (AccessKind == AK_Increment) {
4495       ++Value;
4496 
4497       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4498         APSInt ActualValue(Value, /*IsUnsigned*/true);
4499         return HandleOverflow(Info, E, ActualValue, SubobjType);
4500       }
4501     } else {
4502       --Value;
4503 
4504       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4505         unsigned BitWidth = Value.getBitWidth();
4506         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4507         ActualValue.setBit(BitWidth);
4508         return HandleOverflow(Info, E, ActualValue, SubobjType);
4509       }
4510     }
4511     return true;
4512   }
4513   bool found(APFloat &Value, QualType SubobjType) {
4514     if (!checkConst(SubobjType))
4515       return false;
4516 
4517     if (Old) *Old = APValue(Value);
4518 
4519     APFloat One(Value.getSemantics(), 1);
4520     if (AccessKind == AK_Increment)
4521       Value.add(One, APFloat::rmNearestTiesToEven);
4522     else
4523       Value.subtract(One, APFloat::rmNearestTiesToEven);
4524     return true;
4525   }
4526   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4527     if (!checkConst(SubobjType))
4528       return false;
4529 
4530     QualType PointeeType;
4531     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4532       PointeeType = PT->getPointeeType();
4533     else {
4534       Info.FFDiag(E);
4535       return false;
4536     }
4537 
4538     LValue LVal;
4539     LVal.setFrom(Info.Ctx, Subobj);
4540     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4541                                      AccessKind == AK_Increment ? 1 : -1))
4542       return false;
4543     LVal.moveInto(Subobj);
4544     return true;
4545   }
4546 };
4547 } // end anonymous namespace
4548 
4549 /// Perform an increment or decrement on LVal.
4550 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4551                          QualType LValType, bool IsIncrement, APValue *Old) {
4552   if (LVal.Designator.Invalid)
4553     return false;
4554 
4555   if (!Info.getLangOpts().CPlusPlus14) {
4556     Info.FFDiag(E);
4557     return false;
4558   }
4559 
4560   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4561   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4562   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4563   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4564 }
4565 
4566 /// Build an lvalue for the object argument of a member function call.
4567 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4568                                    LValue &This) {
4569   if (Object->getType()->isPointerType() && Object->isPRValue())
4570     return EvaluatePointer(Object, This, Info);
4571 
4572   if (Object->isGLValue())
4573     return EvaluateLValue(Object, This, Info);
4574 
4575   if (Object->getType()->isLiteralType(Info.Ctx))
4576     return EvaluateTemporary(Object, This, Info);
4577 
4578   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4579   return false;
4580 }
4581 
4582 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4583 /// lvalue referring to the result.
4584 ///
4585 /// \param Info - Information about the ongoing evaluation.
4586 /// \param LV - An lvalue referring to the base of the member pointer.
4587 /// \param RHS - The member pointer expression.
4588 /// \param IncludeMember - Specifies whether the member itself is included in
4589 ///        the resulting LValue subobject designator. This is not possible when
4590 ///        creating a bound member function.
4591 /// \return The field or method declaration to which the member pointer refers,
4592 ///         or 0 if evaluation fails.
4593 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4594                                                   QualType LVType,
4595                                                   LValue &LV,
4596                                                   const Expr *RHS,
4597                                                   bool IncludeMember = true) {
4598   MemberPtr MemPtr;
4599   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4600     return nullptr;
4601 
4602   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4603   // member value, the behavior is undefined.
4604   if (!MemPtr.getDecl()) {
4605     // FIXME: Specific diagnostic.
4606     Info.FFDiag(RHS);
4607     return nullptr;
4608   }
4609 
4610   if (MemPtr.isDerivedMember()) {
4611     // This is a member of some derived class. Truncate LV appropriately.
4612     // The end of the derived-to-base path for the base object must match the
4613     // derived-to-base path for the member pointer.
4614     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4615         LV.Designator.Entries.size()) {
4616       Info.FFDiag(RHS);
4617       return nullptr;
4618     }
4619     unsigned PathLengthToMember =
4620         LV.Designator.Entries.size() - MemPtr.Path.size();
4621     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4622       const CXXRecordDecl *LVDecl = getAsBaseClass(
4623           LV.Designator.Entries[PathLengthToMember + I]);
4624       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4625       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4626         Info.FFDiag(RHS);
4627         return nullptr;
4628       }
4629     }
4630 
4631     // Truncate the lvalue to the appropriate derived class.
4632     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4633                             PathLengthToMember))
4634       return nullptr;
4635   } else if (!MemPtr.Path.empty()) {
4636     // Extend the LValue path with the member pointer's path.
4637     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4638                                   MemPtr.Path.size() + IncludeMember);
4639 
4640     // Walk down to the appropriate base class.
4641     if (const PointerType *PT = LVType->getAs<PointerType>())
4642       LVType = PT->getPointeeType();
4643     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4644     assert(RD && "member pointer access on non-class-type expression");
4645     // The first class in the path is that of the lvalue.
4646     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4647       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4648       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4649         return nullptr;
4650       RD = Base;
4651     }
4652     // Finally cast to the class containing the member.
4653     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4654                                 MemPtr.getContainingRecord()))
4655       return nullptr;
4656   }
4657 
4658   // Add the member. Note that we cannot build bound member functions here.
4659   if (IncludeMember) {
4660     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4661       if (!HandleLValueMember(Info, RHS, LV, FD))
4662         return nullptr;
4663     } else if (const IndirectFieldDecl *IFD =
4664                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4665       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4666         return nullptr;
4667     } else {
4668       llvm_unreachable("can't construct reference to bound member function");
4669     }
4670   }
4671 
4672   return MemPtr.getDecl();
4673 }
4674 
4675 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4676                                                   const BinaryOperator *BO,
4677                                                   LValue &LV,
4678                                                   bool IncludeMember = true) {
4679   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4680 
4681   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4682     if (Info.noteFailure()) {
4683       MemberPtr MemPtr;
4684       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4685     }
4686     return nullptr;
4687   }
4688 
4689   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4690                                    BO->getRHS(), IncludeMember);
4691 }
4692 
4693 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4694 /// the provided lvalue, which currently refers to the base object.
4695 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4696                                     LValue &Result) {
4697   SubobjectDesignator &D = Result.Designator;
4698   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4699     return false;
4700 
4701   QualType TargetQT = E->getType();
4702   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4703     TargetQT = PT->getPointeeType();
4704 
4705   // Check this cast lands within the final derived-to-base subobject path.
4706   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4707     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4708       << D.MostDerivedType << TargetQT;
4709     return false;
4710   }
4711 
4712   // Check the type of the final cast. We don't need to check the path,
4713   // since a cast can only be formed if the path is unique.
4714   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4715   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4716   const CXXRecordDecl *FinalType;
4717   if (NewEntriesSize == D.MostDerivedPathLength)
4718     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4719   else
4720     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4721   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4722     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4723       << D.MostDerivedType << TargetQT;
4724     return false;
4725   }
4726 
4727   // Truncate the lvalue to the appropriate derived class.
4728   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4729 }
4730 
4731 /// Get the value to use for a default-initialized object of type T.
4732 /// Return false if it encounters something invalid.
4733 static bool getDefaultInitValue(QualType T, APValue &Result) {
4734   bool Success = true;
4735   if (auto *RD = T->getAsCXXRecordDecl()) {
4736     if (RD->isInvalidDecl()) {
4737       Result = APValue();
4738       return false;
4739     }
4740     if (RD->isUnion()) {
4741       Result = APValue((const FieldDecl *)nullptr);
4742       return true;
4743     }
4744     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4745                      std::distance(RD->field_begin(), RD->field_end()));
4746 
4747     unsigned Index = 0;
4748     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4749                                                   End = RD->bases_end();
4750          I != End; ++I, ++Index)
4751       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4752 
4753     for (const auto *I : RD->fields()) {
4754       if (I->isUnnamedBitfield())
4755         continue;
4756       Success &= getDefaultInitValue(I->getType(),
4757                                      Result.getStructField(I->getFieldIndex()));
4758     }
4759     return Success;
4760   }
4761 
4762   if (auto *AT =
4763           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4764     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4765     if (Result.hasArrayFiller())
4766       Success &=
4767           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4768 
4769     return Success;
4770   }
4771 
4772   Result = APValue::IndeterminateValue();
4773   return true;
4774 }
4775 
4776 namespace {
4777 enum EvalStmtResult {
4778   /// Evaluation failed.
4779   ESR_Failed,
4780   /// Hit a 'return' statement.
4781   ESR_Returned,
4782   /// Evaluation succeeded.
4783   ESR_Succeeded,
4784   /// Hit a 'continue' statement.
4785   ESR_Continue,
4786   /// Hit a 'break' statement.
4787   ESR_Break,
4788   /// Still scanning for 'case' or 'default' statement.
4789   ESR_CaseNotFound
4790 };
4791 }
4792 
4793 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4794   // We don't need to evaluate the initializer for a static local.
4795   if (!VD->hasLocalStorage())
4796     return true;
4797 
4798   LValue Result;
4799   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4800                                                    ScopeKind::Block, Result);
4801 
4802   const Expr *InitE = VD->getInit();
4803   if (!InitE) {
4804     if (VD->getType()->isDependentType())
4805       return Info.noteSideEffect();
4806     return getDefaultInitValue(VD->getType(), Val);
4807   }
4808   if (InitE->isValueDependent())
4809     return false;
4810 
4811   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4812     // Wipe out any partially-computed value, to allow tracking that this
4813     // evaluation failed.
4814     Val = APValue();
4815     return false;
4816   }
4817 
4818   return true;
4819 }
4820 
4821 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4822   bool OK = true;
4823 
4824   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4825     OK &= EvaluateVarDecl(Info, VD);
4826 
4827   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4828     for (auto *BD : DD->bindings())
4829       if (auto *VD = BD->getHoldingVar())
4830         OK &= EvaluateDecl(Info, VD);
4831 
4832   return OK;
4833 }
4834 
4835 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4836   assert(E->isValueDependent());
4837   if (Info.noteSideEffect())
4838     return true;
4839   assert(E->containsErrors() && "valid value-dependent expression should never "
4840                                 "reach invalid code path.");
4841   return false;
4842 }
4843 
4844 /// Evaluate a condition (either a variable declaration or an expression).
4845 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4846                          const Expr *Cond, bool &Result) {
4847   if (Cond->isValueDependent())
4848     return false;
4849   FullExpressionRAII Scope(Info);
4850   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4851     return false;
4852   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4853     return false;
4854   return Scope.destroy();
4855 }
4856 
4857 namespace {
4858 /// A location where the result (returned value) of evaluating a
4859 /// statement should be stored.
4860 struct StmtResult {
4861   /// The APValue that should be filled in with the returned value.
4862   APValue &Value;
4863   /// The location containing the result, if any (used to support RVO).
4864   const LValue *Slot;
4865 };
4866 
4867 struct TempVersionRAII {
4868   CallStackFrame &Frame;
4869 
4870   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4871     Frame.pushTempVersion();
4872   }
4873 
4874   ~TempVersionRAII() {
4875     Frame.popTempVersion();
4876   }
4877 };
4878 
4879 }
4880 
4881 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4882                                    const Stmt *S,
4883                                    const SwitchCase *SC = nullptr);
4884 
4885 /// Evaluate the body of a loop, and translate the result as appropriate.
4886 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4887                                        const Stmt *Body,
4888                                        const SwitchCase *Case = nullptr) {
4889   BlockScopeRAII Scope(Info);
4890 
4891   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4892   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4893     ESR = ESR_Failed;
4894 
4895   switch (ESR) {
4896   case ESR_Break:
4897     return ESR_Succeeded;
4898   case ESR_Succeeded:
4899   case ESR_Continue:
4900     return ESR_Continue;
4901   case ESR_Failed:
4902   case ESR_Returned:
4903   case ESR_CaseNotFound:
4904     return ESR;
4905   }
4906   llvm_unreachable("Invalid EvalStmtResult!");
4907 }
4908 
4909 /// Evaluate a switch statement.
4910 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4911                                      const SwitchStmt *SS) {
4912   BlockScopeRAII Scope(Info);
4913 
4914   // Evaluate the switch condition.
4915   APSInt Value;
4916   {
4917     if (const Stmt *Init = SS->getInit()) {
4918       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4919       if (ESR != ESR_Succeeded) {
4920         if (ESR != ESR_Failed && !Scope.destroy())
4921           ESR = ESR_Failed;
4922         return ESR;
4923       }
4924     }
4925 
4926     FullExpressionRAII CondScope(Info);
4927     if (SS->getConditionVariable() &&
4928         !EvaluateDecl(Info, SS->getConditionVariable()))
4929       return ESR_Failed;
4930     if (!EvaluateInteger(SS->getCond(), Value, Info))
4931       return ESR_Failed;
4932     if (!CondScope.destroy())
4933       return ESR_Failed;
4934   }
4935 
4936   // Find the switch case corresponding to the value of the condition.
4937   // FIXME: Cache this lookup.
4938   const SwitchCase *Found = nullptr;
4939   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4940        SC = SC->getNextSwitchCase()) {
4941     if (isa<DefaultStmt>(SC)) {
4942       Found = SC;
4943       continue;
4944     }
4945 
4946     const CaseStmt *CS = cast<CaseStmt>(SC);
4947     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4948     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4949                               : LHS;
4950     if (LHS <= Value && Value <= RHS) {
4951       Found = SC;
4952       break;
4953     }
4954   }
4955 
4956   if (!Found)
4957     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4958 
4959   // Search the switch body for the switch case and evaluate it from there.
4960   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4961   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4962     return ESR_Failed;
4963 
4964   switch (ESR) {
4965   case ESR_Break:
4966     return ESR_Succeeded;
4967   case ESR_Succeeded:
4968   case ESR_Continue:
4969   case ESR_Failed:
4970   case ESR_Returned:
4971     return ESR;
4972   case ESR_CaseNotFound:
4973     // This can only happen if the switch case is nested within a statement
4974     // expression. We have no intention of supporting that.
4975     Info.FFDiag(Found->getBeginLoc(),
4976                 diag::note_constexpr_stmt_expr_unsupported);
4977     return ESR_Failed;
4978   }
4979   llvm_unreachable("Invalid EvalStmtResult!");
4980 }
4981 
4982 // Evaluate a statement.
4983 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4984                                    const Stmt *S, const SwitchCase *Case) {
4985   if (!Info.nextStep(S))
4986     return ESR_Failed;
4987 
4988   // If we're hunting down a 'case' or 'default' label, recurse through
4989   // substatements until we hit the label.
4990   if (Case) {
4991     switch (S->getStmtClass()) {
4992     case Stmt::CompoundStmtClass:
4993       // FIXME: Precompute which substatement of a compound statement we
4994       // would jump to, and go straight there rather than performing a
4995       // linear scan each time.
4996     case Stmt::LabelStmtClass:
4997     case Stmt::AttributedStmtClass:
4998     case Stmt::DoStmtClass:
4999       break;
5000 
5001     case Stmt::CaseStmtClass:
5002     case Stmt::DefaultStmtClass:
5003       if (Case == S)
5004         Case = nullptr;
5005       break;
5006 
5007     case Stmt::IfStmtClass: {
5008       // FIXME: Precompute which side of an 'if' we would jump to, and go
5009       // straight there rather than scanning both sides.
5010       const IfStmt *IS = cast<IfStmt>(S);
5011 
5012       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5013       // preceded by our switch label.
5014       BlockScopeRAII Scope(Info);
5015 
5016       // Step into the init statement in case it brings an (uninitialized)
5017       // variable into scope.
5018       if (const Stmt *Init = IS->getInit()) {
5019         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5020         if (ESR != ESR_CaseNotFound) {
5021           assert(ESR != ESR_Succeeded);
5022           return ESR;
5023         }
5024       }
5025 
5026       // Condition variable must be initialized if it exists.
5027       // FIXME: We can skip evaluating the body if there's a condition
5028       // variable, as there can't be any case labels within it.
5029       // (The same is true for 'for' statements.)
5030 
5031       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5032       if (ESR == ESR_Failed)
5033         return ESR;
5034       if (ESR != ESR_CaseNotFound)
5035         return Scope.destroy() ? ESR : ESR_Failed;
5036       if (!IS->getElse())
5037         return ESR_CaseNotFound;
5038 
5039       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5040       if (ESR == ESR_Failed)
5041         return ESR;
5042       if (ESR != ESR_CaseNotFound)
5043         return Scope.destroy() ? ESR : ESR_Failed;
5044       return ESR_CaseNotFound;
5045     }
5046 
5047     case Stmt::WhileStmtClass: {
5048       EvalStmtResult ESR =
5049           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5050       if (ESR != ESR_Continue)
5051         return ESR;
5052       break;
5053     }
5054 
5055     case Stmt::ForStmtClass: {
5056       const ForStmt *FS = cast<ForStmt>(S);
5057       BlockScopeRAII Scope(Info);
5058 
5059       // Step into the init statement in case it brings an (uninitialized)
5060       // variable into scope.
5061       if (const Stmt *Init = FS->getInit()) {
5062         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5063         if (ESR != ESR_CaseNotFound) {
5064           assert(ESR != ESR_Succeeded);
5065           return ESR;
5066         }
5067       }
5068 
5069       EvalStmtResult ESR =
5070           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5071       if (ESR != ESR_Continue)
5072         return ESR;
5073       if (const auto *Inc = FS->getInc()) {
5074         if (Inc->isValueDependent()) {
5075           if (!EvaluateDependentExpr(Inc, Info))
5076             return ESR_Failed;
5077         } else {
5078           FullExpressionRAII IncScope(Info);
5079           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5080             return ESR_Failed;
5081         }
5082       }
5083       break;
5084     }
5085 
5086     case Stmt::DeclStmtClass: {
5087       // Start the lifetime of any uninitialized variables we encounter. They
5088       // might be used by the selected branch of the switch.
5089       const DeclStmt *DS = cast<DeclStmt>(S);
5090       for (const auto *D : DS->decls()) {
5091         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5092           if (VD->hasLocalStorage() && !VD->getInit())
5093             if (!EvaluateVarDecl(Info, VD))
5094               return ESR_Failed;
5095           // FIXME: If the variable has initialization that can't be jumped
5096           // over, bail out of any immediately-surrounding compound-statement
5097           // too. There can't be any case labels here.
5098         }
5099       }
5100       return ESR_CaseNotFound;
5101     }
5102 
5103     default:
5104       return ESR_CaseNotFound;
5105     }
5106   }
5107 
5108   switch (S->getStmtClass()) {
5109   default:
5110     if (const Expr *E = dyn_cast<Expr>(S)) {
5111       if (E->isValueDependent()) {
5112         if (!EvaluateDependentExpr(E, Info))
5113           return ESR_Failed;
5114       } else {
5115         // Don't bother evaluating beyond an expression-statement which couldn't
5116         // be evaluated.
5117         // FIXME: Do we need the FullExpressionRAII object here?
5118         // VisitExprWithCleanups should create one when necessary.
5119         FullExpressionRAII Scope(Info);
5120         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5121           return ESR_Failed;
5122       }
5123       return ESR_Succeeded;
5124     }
5125 
5126     Info.FFDiag(S->getBeginLoc());
5127     return ESR_Failed;
5128 
5129   case Stmt::NullStmtClass:
5130     return ESR_Succeeded;
5131 
5132   case Stmt::DeclStmtClass: {
5133     const DeclStmt *DS = cast<DeclStmt>(S);
5134     for (const auto *D : DS->decls()) {
5135       // Each declaration initialization is its own full-expression.
5136       FullExpressionRAII Scope(Info);
5137       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5138         return ESR_Failed;
5139       if (!Scope.destroy())
5140         return ESR_Failed;
5141     }
5142     return ESR_Succeeded;
5143   }
5144 
5145   case Stmt::ReturnStmtClass: {
5146     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5147     FullExpressionRAII Scope(Info);
5148     if (RetExpr && RetExpr->isValueDependent()) {
5149       EvaluateDependentExpr(RetExpr, Info);
5150       // We know we returned, but we don't know what the value is.
5151       return ESR_Failed;
5152     }
5153     if (RetExpr &&
5154         !(Result.Slot
5155               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5156               : Evaluate(Result.Value, Info, RetExpr)))
5157       return ESR_Failed;
5158     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5159   }
5160 
5161   case Stmt::CompoundStmtClass: {
5162     BlockScopeRAII Scope(Info);
5163 
5164     const CompoundStmt *CS = cast<CompoundStmt>(S);
5165     for (const auto *BI : CS->body()) {
5166       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5167       if (ESR == ESR_Succeeded)
5168         Case = nullptr;
5169       else if (ESR != ESR_CaseNotFound) {
5170         if (ESR != ESR_Failed && !Scope.destroy())
5171           return ESR_Failed;
5172         return ESR;
5173       }
5174     }
5175     if (Case)
5176       return ESR_CaseNotFound;
5177     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5178   }
5179 
5180   case Stmt::IfStmtClass: {
5181     const IfStmt *IS = cast<IfStmt>(S);
5182 
5183     // Evaluate the condition, as either a var decl or as an expression.
5184     BlockScopeRAII Scope(Info);
5185     if (const Stmt *Init = IS->getInit()) {
5186       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5187       if (ESR != ESR_Succeeded) {
5188         if (ESR != ESR_Failed && !Scope.destroy())
5189           return ESR_Failed;
5190         return ESR;
5191       }
5192     }
5193     bool Cond;
5194     if (IS->isConsteval())
5195       Cond = IS->isNonNegatedConsteval();
5196     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5197                            Cond))
5198       return ESR_Failed;
5199 
5200     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5201       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5202       if (ESR != ESR_Succeeded) {
5203         if (ESR != ESR_Failed && !Scope.destroy())
5204           return ESR_Failed;
5205         return ESR;
5206       }
5207     }
5208     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5209   }
5210 
5211   case Stmt::WhileStmtClass: {
5212     const WhileStmt *WS = cast<WhileStmt>(S);
5213     while (true) {
5214       BlockScopeRAII Scope(Info);
5215       bool Continue;
5216       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5217                         Continue))
5218         return ESR_Failed;
5219       if (!Continue)
5220         break;
5221 
5222       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5223       if (ESR != ESR_Continue) {
5224         if (ESR != ESR_Failed && !Scope.destroy())
5225           return ESR_Failed;
5226         return ESR;
5227       }
5228       if (!Scope.destroy())
5229         return ESR_Failed;
5230     }
5231     return ESR_Succeeded;
5232   }
5233 
5234   case Stmt::DoStmtClass: {
5235     const DoStmt *DS = cast<DoStmt>(S);
5236     bool Continue;
5237     do {
5238       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5239       if (ESR != ESR_Continue)
5240         return ESR;
5241       Case = nullptr;
5242 
5243       if (DS->getCond()->isValueDependent()) {
5244         EvaluateDependentExpr(DS->getCond(), Info);
5245         // Bailout as we don't know whether to keep going or terminate the loop.
5246         return ESR_Failed;
5247       }
5248       FullExpressionRAII CondScope(Info);
5249       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5250           !CondScope.destroy())
5251         return ESR_Failed;
5252     } while (Continue);
5253     return ESR_Succeeded;
5254   }
5255 
5256   case Stmt::ForStmtClass: {
5257     const ForStmt *FS = cast<ForStmt>(S);
5258     BlockScopeRAII ForScope(Info);
5259     if (FS->getInit()) {
5260       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5261       if (ESR != ESR_Succeeded) {
5262         if (ESR != ESR_Failed && !ForScope.destroy())
5263           return ESR_Failed;
5264         return ESR;
5265       }
5266     }
5267     while (true) {
5268       BlockScopeRAII IterScope(Info);
5269       bool Continue = true;
5270       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5271                                          FS->getCond(), Continue))
5272         return ESR_Failed;
5273       if (!Continue)
5274         break;
5275 
5276       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5277       if (ESR != ESR_Continue) {
5278         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5279           return ESR_Failed;
5280         return ESR;
5281       }
5282 
5283       if (const auto *Inc = FS->getInc()) {
5284         if (Inc->isValueDependent()) {
5285           if (!EvaluateDependentExpr(Inc, Info))
5286             return ESR_Failed;
5287         } else {
5288           FullExpressionRAII IncScope(Info);
5289           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5290             return ESR_Failed;
5291         }
5292       }
5293 
5294       if (!IterScope.destroy())
5295         return ESR_Failed;
5296     }
5297     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5298   }
5299 
5300   case Stmt::CXXForRangeStmtClass: {
5301     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5302     BlockScopeRAII Scope(Info);
5303 
5304     // Evaluate the init-statement if present.
5305     if (FS->getInit()) {
5306       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5307       if (ESR != ESR_Succeeded) {
5308         if (ESR != ESR_Failed && !Scope.destroy())
5309           return ESR_Failed;
5310         return ESR;
5311       }
5312     }
5313 
5314     // Initialize the __range variable.
5315     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5316     if (ESR != ESR_Succeeded) {
5317       if (ESR != ESR_Failed && !Scope.destroy())
5318         return ESR_Failed;
5319       return ESR;
5320     }
5321 
5322     // Create the __begin and __end iterators.
5323     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5324     if (ESR != ESR_Succeeded) {
5325       if (ESR != ESR_Failed && !Scope.destroy())
5326         return ESR_Failed;
5327       return ESR;
5328     }
5329     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5330     if (ESR != ESR_Succeeded) {
5331       if (ESR != ESR_Failed && !Scope.destroy())
5332         return ESR_Failed;
5333       return ESR;
5334     }
5335 
5336     while (true) {
5337       // Condition: __begin != __end.
5338       {
5339         if (FS->getCond()->isValueDependent()) {
5340           EvaluateDependentExpr(FS->getCond(), Info);
5341           // We don't know whether to keep going or terminate the loop.
5342           return ESR_Failed;
5343         }
5344         bool Continue = true;
5345         FullExpressionRAII CondExpr(Info);
5346         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5347           return ESR_Failed;
5348         if (!Continue)
5349           break;
5350       }
5351 
5352       // User's variable declaration, initialized by *__begin.
5353       BlockScopeRAII InnerScope(Info);
5354       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5355       if (ESR != ESR_Succeeded) {
5356         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5357           return ESR_Failed;
5358         return ESR;
5359       }
5360 
5361       // Loop body.
5362       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5363       if (ESR != ESR_Continue) {
5364         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5365           return ESR_Failed;
5366         return ESR;
5367       }
5368       if (FS->getInc()->isValueDependent()) {
5369         if (!EvaluateDependentExpr(FS->getInc(), Info))
5370           return ESR_Failed;
5371       } else {
5372         // Increment: ++__begin
5373         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5374           return ESR_Failed;
5375       }
5376 
5377       if (!InnerScope.destroy())
5378         return ESR_Failed;
5379     }
5380 
5381     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5382   }
5383 
5384   case Stmt::SwitchStmtClass:
5385     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5386 
5387   case Stmt::ContinueStmtClass:
5388     return ESR_Continue;
5389 
5390   case Stmt::BreakStmtClass:
5391     return ESR_Break;
5392 
5393   case Stmt::LabelStmtClass:
5394     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5395 
5396   case Stmt::AttributedStmtClass:
5397     // As a general principle, C++11 attributes can be ignored without
5398     // any semantic impact.
5399     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5400                         Case);
5401 
5402   case Stmt::CaseStmtClass:
5403   case Stmt::DefaultStmtClass:
5404     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5405   case Stmt::CXXTryStmtClass:
5406     // Evaluate try blocks by evaluating all sub statements.
5407     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5408   }
5409 }
5410 
5411 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5412 /// default constructor. If so, we'll fold it whether or not it's marked as
5413 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5414 /// so we need special handling.
5415 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5416                                            const CXXConstructorDecl *CD,
5417                                            bool IsValueInitialization) {
5418   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5419     return false;
5420 
5421   // Value-initialization does not call a trivial default constructor, so such a
5422   // call is a core constant expression whether or not the constructor is
5423   // constexpr.
5424   if (!CD->isConstexpr() && !IsValueInitialization) {
5425     if (Info.getLangOpts().CPlusPlus11) {
5426       // FIXME: If DiagDecl is an implicitly-declared special member function,
5427       // we should be much more explicit about why it's not constexpr.
5428       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5429         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5430       Info.Note(CD->getLocation(), diag::note_declared_at);
5431     } else {
5432       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5433     }
5434   }
5435   return true;
5436 }
5437 
5438 /// CheckConstexprFunction - Check that a function can be called in a constant
5439 /// expression.
5440 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5441                                    const FunctionDecl *Declaration,
5442                                    const FunctionDecl *Definition,
5443                                    const Stmt *Body) {
5444   // Potential constant expressions can contain calls to declared, but not yet
5445   // defined, constexpr functions.
5446   if (Info.checkingPotentialConstantExpression() && !Definition &&
5447       Declaration->isConstexpr())
5448     return false;
5449 
5450   // Bail out if the function declaration itself is invalid.  We will
5451   // have produced a relevant diagnostic while parsing it, so just
5452   // note the problematic sub-expression.
5453   if (Declaration->isInvalidDecl()) {
5454     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5455     return false;
5456   }
5457 
5458   // DR1872: An instantiated virtual constexpr function can't be called in a
5459   // constant expression (prior to C++20). We can still constant-fold such a
5460   // call.
5461   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5462       cast<CXXMethodDecl>(Declaration)->isVirtual())
5463     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5464 
5465   if (Definition && Definition->isInvalidDecl()) {
5466     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5467     return false;
5468   }
5469 
5470   // Can we evaluate this function call?
5471   if (Definition && Definition->isConstexpr() && Body)
5472     return true;
5473 
5474   if (Info.getLangOpts().CPlusPlus11) {
5475     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5476 
5477     // If this function is not constexpr because it is an inherited
5478     // non-constexpr constructor, diagnose that directly.
5479     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5480     if (CD && CD->isInheritingConstructor()) {
5481       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5482       if (!Inherited->isConstexpr())
5483         DiagDecl = CD = Inherited;
5484     }
5485 
5486     // FIXME: If DiagDecl is an implicitly-declared special member function
5487     // or an inheriting constructor, we should be much more explicit about why
5488     // it's not constexpr.
5489     if (CD && CD->isInheritingConstructor())
5490       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5491         << CD->getInheritedConstructor().getConstructor()->getParent();
5492     else
5493       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5494         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5495     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5496   } else {
5497     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5498   }
5499   return false;
5500 }
5501 
5502 namespace {
5503 struct CheckDynamicTypeHandler {
5504   AccessKinds AccessKind;
5505   typedef bool result_type;
5506   bool failed() { return false; }
5507   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5508   bool found(APSInt &Value, QualType SubobjType) { return true; }
5509   bool found(APFloat &Value, QualType SubobjType) { return true; }
5510 };
5511 } // end anonymous namespace
5512 
5513 /// Check that we can access the notional vptr of an object / determine its
5514 /// dynamic type.
5515 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5516                              AccessKinds AK, bool Polymorphic) {
5517   if (This.Designator.Invalid)
5518     return false;
5519 
5520   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5521 
5522   if (!Obj)
5523     return false;
5524 
5525   if (!Obj.Value) {
5526     // The object is not usable in constant expressions, so we can't inspect
5527     // its value to see if it's in-lifetime or what the active union members
5528     // are. We can still check for a one-past-the-end lvalue.
5529     if (This.Designator.isOnePastTheEnd() ||
5530         This.Designator.isMostDerivedAnUnsizedArray()) {
5531       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5532                          ? diag::note_constexpr_access_past_end
5533                          : diag::note_constexpr_access_unsized_array)
5534           << AK;
5535       return false;
5536     } else if (Polymorphic) {
5537       // Conservatively refuse to perform a polymorphic operation if we would
5538       // not be able to read a notional 'vptr' value.
5539       APValue Val;
5540       This.moveInto(Val);
5541       QualType StarThisType =
5542           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5543       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5544           << AK << Val.getAsString(Info.Ctx, StarThisType);
5545       return false;
5546     }
5547     return true;
5548   }
5549 
5550   CheckDynamicTypeHandler Handler{AK};
5551   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5552 }
5553 
5554 /// Check that the pointee of the 'this' pointer in a member function call is
5555 /// either within its lifetime or in its period of construction or destruction.
5556 static bool
5557 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5558                                      const LValue &This,
5559                                      const CXXMethodDecl *NamedMember) {
5560   return checkDynamicType(
5561       Info, E, This,
5562       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5563 }
5564 
5565 struct DynamicType {
5566   /// The dynamic class type of the object.
5567   const CXXRecordDecl *Type;
5568   /// The corresponding path length in the lvalue.
5569   unsigned PathLength;
5570 };
5571 
5572 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5573                                              unsigned PathLength) {
5574   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5575       Designator.Entries.size() && "invalid path length");
5576   return (PathLength == Designator.MostDerivedPathLength)
5577              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5578              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5579 }
5580 
5581 /// Determine the dynamic type of an object.
5582 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5583                                                 LValue &This, AccessKinds AK) {
5584   // If we don't have an lvalue denoting an object of class type, there is no
5585   // meaningful dynamic type. (We consider objects of non-class type to have no
5586   // dynamic type.)
5587   if (!checkDynamicType(Info, E, This, AK, true))
5588     return None;
5589 
5590   // Refuse to compute a dynamic type in the presence of virtual bases. This
5591   // shouldn't happen other than in constant-folding situations, since literal
5592   // types can't have virtual bases.
5593   //
5594   // Note that consumers of DynamicType assume that the type has no virtual
5595   // bases, and will need modifications if this restriction is relaxed.
5596   const CXXRecordDecl *Class =
5597       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5598   if (!Class || Class->getNumVBases()) {
5599     Info.FFDiag(E);
5600     return None;
5601   }
5602 
5603   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5604   // binary search here instead. But the overwhelmingly common case is that
5605   // we're not in the middle of a constructor, so it probably doesn't matter
5606   // in practice.
5607   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5608   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5609        PathLength <= Path.size(); ++PathLength) {
5610     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5611                                       Path.slice(0, PathLength))) {
5612     case ConstructionPhase::Bases:
5613     case ConstructionPhase::DestroyingBases:
5614       // We're constructing or destroying a base class. This is not the dynamic
5615       // type.
5616       break;
5617 
5618     case ConstructionPhase::None:
5619     case ConstructionPhase::AfterBases:
5620     case ConstructionPhase::AfterFields:
5621     case ConstructionPhase::Destroying:
5622       // We've finished constructing the base classes and not yet started
5623       // destroying them again, so this is the dynamic type.
5624       return DynamicType{getBaseClassType(This.Designator, PathLength),
5625                          PathLength};
5626     }
5627   }
5628 
5629   // CWG issue 1517: we're constructing a base class of the object described by
5630   // 'This', so that object has not yet begun its period of construction and
5631   // any polymorphic operation on it results in undefined behavior.
5632   Info.FFDiag(E);
5633   return None;
5634 }
5635 
5636 /// Perform virtual dispatch.
5637 static const CXXMethodDecl *HandleVirtualDispatch(
5638     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5639     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5640   Optional<DynamicType> DynType = ComputeDynamicType(
5641       Info, E, This,
5642       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5643   if (!DynType)
5644     return nullptr;
5645 
5646   // Find the final overrider. It must be declared in one of the classes on the
5647   // path from the dynamic type to the static type.
5648   // FIXME: If we ever allow literal types to have virtual base classes, that
5649   // won't be true.
5650   const CXXMethodDecl *Callee = Found;
5651   unsigned PathLength = DynType->PathLength;
5652   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5653     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5654     const CXXMethodDecl *Overrider =
5655         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5656     if (Overrider) {
5657       Callee = Overrider;
5658       break;
5659     }
5660   }
5661 
5662   // C++2a [class.abstract]p6:
5663   //   the effect of making a virtual call to a pure virtual function [...] is
5664   //   undefined
5665   if (Callee->isPure()) {
5666     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5667     Info.Note(Callee->getLocation(), diag::note_declared_at);
5668     return nullptr;
5669   }
5670 
5671   // If necessary, walk the rest of the path to determine the sequence of
5672   // covariant adjustment steps to apply.
5673   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5674                                        Found->getReturnType())) {
5675     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5676     for (unsigned CovariantPathLength = PathLength + 1;
5677          CovariantPathLength != This.Designator.Entries.size();
5678          ++CovariantPathLength) {
5679       const CXXRecordDecl *NextClass =
5680           getBaseClassType(This.Designator, CovariantPathLength);
5681       const CXXMethodDecl *Next =
5682           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5683       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5684                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5685         CovariantAdjustmentPath.push_back(Next->getReturnType());
5686     }
5687     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5688                                          CovariantAdjustmentPath.back()))
5689       CovariantAdjustmentPath.push_back(Found->getReturnType());
5690   }
5691 
5692   // Perform 'this' adjustment.
5693   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5694     return nullptr;
5695 
5696   return Callee;
5697 }
5698 
5699 /// Perform the adjustment from a value returned by a virtual function to
5700 /// a value of the statically expected type, which may be a pointer or
5701 /// reference to a base class of the returned type.
5702 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5703                                             APValue &Result,
5704                                             ArrayRef<QualType> Path) {
5705   assert(Result.isLValue() &&
5706          "unexpected kind of APValue for covariant return");
5707   if (Result.isNullPointer())
5708     return true;
5709 
5710   LValue LVal;
5711   LVal.setFrom(Info.Ctx, Result);
5712 
5713   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5714   for (unsigned I = 1; I != Path.size(); ++I) {
5715     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5716     assert(OldClass && NewClass && "unexpected kind of covariant return");
5717     if (OldClass != NewClass &&
5718         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5719       return false;
5720     OldClass = NewClass;
5721   }
5722 
5723   LVal.moveInto(Result);
5724   return true;
5725 }
5726 
5727 /// Determine whether \p Base, which is known to be a direct base class of
5728 /// \p Derived, is a public base class.
5729 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5730                               const CXXRecordDecl *Base) {
5731   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5732     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5733     if (BaseClass && declaresSameEntity(BaseClass, Base))
5734       return BaseSpec.getAccessSpecifier() == AS_public;
5735   }
5736   llvm_unreachable("Base is not a direct base of Derived");
5737 }
5738 
5739 /// Apply the given dynamic cast operation on the provided lvalue.
5740 ///
5741 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5742 /// to find a suitable target subobject.
5743 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5744                               LValue &Ptr) {
5745   // We can't do anything with a non-symbolic pointer value.
5746   SubobjectDesignator &D = Ptr.Designator;
5747   if (D.Invalid)
5748     return false;
5749 
5750   // C++ [expr.dynamic.cast]p6:
5751   //   If v is a null pointer value, the result is a null pointer value.
5752   if (Ptr.isNullPointer() && !E->isGLValue())
5753     return true;
5754 
5755   // For all the other cases, we need the pointer to point to an object within
5756   // its lifetime / period of construction / destruction, and we need to know
5757   // its dynamic type.
5758   Optional<DynamicType> DynType =
5759       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5760   if (!DynType)
5761     return false;
5762 
5763   // C++ [expr.dynamic.cast]p7:
5764   //   If T is "pointer to cv void", then the result is a pointer to the most
5765   //   derived object
5766   if (E->getType()->isVoidPointerType())
5767     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5768 
5769   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5770   assert(C && "dynamic_cast target is not void pointer nor class");
5771   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5772 
5773   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5774     // C++ [expr.dynamic.cast]p9:
5775     if (!E->isGLValue()) {
5776       //   The value of a failed cast to pointer type is the null pointer value
5777       //   of the required result type.
5778       Ptr.setNull(Info.Ctx, E->getType());
5779       return true;
5780     }
5781 
5782     //   A failed cast to reference type throws [...] std::bad_cast.
5783     unsigned DiagKind;
5784     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5785                    DynType->Type->isDerivedFrom(C)))
5786       DiagKind = 0;
5787     else if (!Paths || Paths->begin() == Paths->end())
5788       DiagKind = 1;
5789     else if (Paths->isAmbiguous(CQT))
5790       DiagKind = 2;
5791     else {
5792       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5793       DiagKind = 3;
5794     }
5795     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5796         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5797         << Info.Ctx.getRecordType(DynType->Type)
5798         << E->getType().getUnqualifiedType();
5799     return false;
5800   };
5801 
5802   // Runtime check, phase 1:
5803   //   Walk from the base subobject towards the derived object looking for the
5804   //   target type.
5805   for (int PathLength = Ptr.Designator.Entries.size();
5806        PathLength >= (int)DynType->PathLength; --PathLength) {
5807     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5808     if (declaresSameEntity(Class, C))
5809       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5810     // We can only walk across public inheritance edges.
5811     if (PathLength > (int)DynType->PathLength &&
5812         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5813                            Class))
5814       return RuntimeCheckFailed(nullptr);
5815   }
5816 
5817   // Runtime check, phase 2:
5818   //   Search the dynamic type for an unambiguous public base of type C.
5819   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5820                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5821   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5822       Paths.front().Access == AS_public) {
5823     // Downcast to the dynamic type...
5824     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5825       return false;
5826     // ... then upcast to the chosen base class subobject.
5827     for (CXXBasePathElement &Elem : Paths.front())
5828       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5829         return false;
5830     return true;
5831   }
5832 
5833   // Otherwise, the runtime check fails.
5834   return RuntimeCheckFailed(&Paths);
5835 }
5836 
5837 namespace {
5838 struct StartLifetimeOfUnionMemberHandler {
5839   EvalInfo &Info;
5840   const Expr *LHSExpr;
5841   const FieldDecl *Field;
5842   bool DuringInit;
5843   bool Failed = false;
5844   static const AccessKinds AccessKind = AK_Assign;
5845 
5846   typedef bool result_type;
5847   bool failed() { return Failed; }
5848   bool found(APValue &Subobj, QualType SubobjType) {
5849     // We are supposed to perform no initialization but begin the lifetime of
5850     // the object. We interpret that as meaning to do what default
5851     // initialization of the object would do if all constructors involved were
5852     // trivial:
5853     //  * All base, non-variant member, and array element subobjects' lifetimes
5854     //    begin
5855     //  * No variant members' lifetimes begin
5856     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5857     assert(SubobjType->isUnionType());
5858     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5859       // This union member is already active. If it's also in-lifetime, there's
5860       // nothing to do.
5861       if (Subobj.getUnionValue().hasValue())
5862         return true;
5863     } else if (DuringInit) {
5864       // We're currently in the process of initializing a different union
5865       // member.  If we carried on, that initialization would attempt to
5866       // store to an inactive union member, resulting in undefined behavior.
5867       Info.FFDiag(LHSExpr,
5868                   diag::note_constexpr_union_member_change_during_init);
5869       return false;
5870     }
5871     APValue Result;
5872     Failed = !getDefaultInitValue(Field->getType(), Result);
5873     Subobj.setUnion(Field, Result);
5874     return true;
5875   }
5876   bool found(APSInt &Value, QualType SubobjType) {
5877     llvm_unreachable("wrong value kind for union object");
5878   }
5879   bool found(APFloat &Value, QualType SubobjType) {
5880     llvm_unreachable("wrong value kind for union object");
5881   }
5882 };
5883 } // end anonymous namespace
5884 
5885 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5886 
5887 /// Handle a builtin simple-assignment or a call to a trivial assignment
5888 /// operator whose left-hand side might involve a union member access. If it
5889 /// does, implicitly start the lifetime of any accessed union elements per
5890 /// C++20 [class.union]5.
5891 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5892                                           const LValue &LHS) {
5893   if (LHS.InvalidBase || LHS.Designator.Invalid)
5894     return false;
5895 
5896   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5897   // C++ [class.union]p5:
5898   //   define the set S(E) of subexpressions of E as follows:
5899   unsigned PathLength = LHS.Designator.Entries.size();
5900   for (const Expr *E = LHSExpr; E != nullptr;) {
5901     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5902     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5903       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5904       // Note that we can't implicitly start the lifetime of a reference,
5905       // so we don't need to proceed any further if we reach one.
5906       if (!FD || FD->getType()->isReferenceType())
5907         break;
5908 
5909       //    ... and also contains A.B if B names a union member ...
5910       if (FD->getParent()->isUnion()) {
5911         //    ... of a non-class, non-array type, or of a class type with a
5912         //    trivial default constructor that is not deleted, or an array of
5913         //    such types.
5914         auto *RD =
5915             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5916         if (!RD || RD->hasTrivialDefaultConstructor())
5917           UnionPathLengths.push_back({PathLength - 1, FD});
5918       }
5919 
5920       E = ME->getBase();
5921       --PathLength;
5922       assert(declaresSameEntity(FD,
5923                                 LHS.Designator.Entries[PathLength]
5924                                     .getAsBaseOrMember().getPointer()));
5925 
5926       //   -- If E is of the form A[B] and is interpreted as a built-in array
5927       //      subscripting operator, S(E) is [S(the array operand, if any)].
5928     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5929       // Step over an ArrayToPointerDecay implicit cast.
5930       auto *Base = ASE->getBase()->IgnoreImplicit();
5931       if (!Base->getType()->isArrayType())
5932         break;
5933 
5934       E = Base;
5935       --PathLength;
5936 
5937     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5938       // Step over a derived-to-base conversion.
5939       E = ICE->getSubExpr();
5940       if (ICE->getCastKind() == CK_NoOp)
5941         continue;
5942       if (ICE->getCastKind() != CK_DerivedToBase &&
5943           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5944         break;
5945       // Walk path backwards as we walk up from the base to the derived class.
5946       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5947         --PathLength;
5948         (void)Elt;
5949         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5950                                   LHS.Designator.Entries[PathLength]
5951                                       .getAsBaseOrMember().getPointer()));
5952       }
5953 
5954     //   -- Otherwise, S(E) is empty.
5955     } else {
5956       break;
5957     }
5958   }
5959 
5960   // Common case: no unions' lifetimes are started.
5961   if (UnionPathLengths.empty())
5962     return true;
5963 
5964   //   if modification of X [would access an inactive union member], an object
5965   //   of the type of X is implicitly created
5966   CompleteObject Obj =
5967       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5968   if (!Obj)
5969     return false;
5970   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5971            llvm::reverse(UnionPathLengths)) {
5972     // Form a designator for the union object.
5973     SubobjectDesignator D = LHS.Designator;
5974     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5975 
5976     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5977                       ConstructionPhase::AfterBases;
5978     StartLifetimeOfUnionMemberHandler StartLifetime{
5979         Info, LHSExpr, LengthAndField.second, DuringInit};
5980     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5981       return false;
5982   }
5983 
5984   return true;
5985 }
5986 
5987 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5988                             CallRef Call, EvalInfo &Info,
5989                             bool NonNull = false) {
5990   LValue LV;
5991   // Create the parameter slot and register its destruction. For a vararg
5992   // argument, create a temporary.
5993   // FIXME: For calling conventions that destroy parameters in the callee,
5994   // should we consider performing destruction when the function returns
5995   // instead?
5996   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5997                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5998                                                        ScopeKind::Call, LV);
5999   if (!EvaluateInPlace(V, Info, LV, Arg))
6000     return false;
6001 
6002   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6003   // undefined behavior, so is non-constant.
6004   if (NonNull && V.isLValue() && V.isNullPointer()) {
6005     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6006     return false;
6007   }
6008 
6009   return true;
6010 }
6011 
6012 /// Evaluate the arguments to a function call.
6013 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6014                          EvalInfo &Info, const FunctionDecl *Callee,
6015                          bool RightToLeft = false) {
6016   bool Success = true;
6017   llvm::SmallBitVector ForbiddenNullArgs;
6018   if (Callee->hasAttr<NonNullAttr>()) {
6019     ForbiddenNullArgs.resize(Args.size());
6020     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6021       if (!Attr->args_size()) {
6022         ForbiddenNullArgs.set();
6023         break;
6024       } else
6025         for (auto Idx : Attr->args()) {
6026           unsigned ASTIdx = Idx.getASTIndex();
6027           if (ASTIdx >= Args.size())
6028             continue;
6029           ForbiddenNullArgs[ASTIdx] = 1;
6030         }
6031     }
6032   }
6033   for (unsigned I = 0; I < Args.size(); I++) {
6034     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6035     const ParmVarDecl *PVD =
6036         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6037     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6038     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6039       // If we're checking for a potential constant expression, evaluate all
6040       // initializers even if some of them fail.
6041       if (!Info.noteFailure())
6042         return false;
6043       Success = false;
6044     }
6045   }
6046   return Success;
6047 }
6048 
6049 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6050 /// constructor or assignment operator.
6051 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6052                               const Expr *E, APValue &Result,
6053                               bool CopyObjectRepresentation) {
6054   // Find the reference argument.
6055   CallStackFrame *Frame = Info.CurrentCall;
6056   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6057   if (!RefValue) {
6058     Info.FFDiag(E);
6059     return false;
6060   }
6061 
6062   // Copy out the contents of the RHS object.
6063   LValue RefLValue;
6064   RefLValue.setFrom(Info.Ctx, *RefValue);
6065   return handleLValueToRValueConversion(
6066       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6067       CopyObjectRepresentation);
6068 }
6069 
6070 /// Evaluate a function call.
6071 static bool HandleFunctionCall(SourceLocation CallLoc,
6072                                const FunctionDecl *Callee, const LValue *This,
6073                                ArrayRef<const Expr *> Args, CallRef Call,
6074                                const Stmt *Body, EvalInfo &Info,
6075                                APValue &Result, const LValue *ResultSlot) {
6076   if (!Info.CheckCallLimit(CallLoc))
6077     return false;
6078 
6079   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6080 
6081   // For a trivial copy or move assignment, perform an APValue copy. This is
6082   // essential for unions, where the operations performed by the assignment
6083   // operator cannot be represented as statements.
6084   //
6085   // Skip this for non-union classes with no fields; in that case, the defaulted
6086   // copy/move does not actually read the object.
6087   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6088   if (MD && MD->isDefaulted() &&
6089       (MD->getParent()->isUnion() ||
6090        (MD->isTrivial() &&
6091         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6092     assert(This &&
6093            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6094     APValue RHSValue;
6095     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6096                            MD->getParent()->isUnion()))
6097       return false;
6098     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6099         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6100       return false;
6101     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6102                           RHSValue))
6103       return false;
6104     This->moveInto(Result);
6105     return true;
6106   } else if (MD && isLambdaCallOperator(MD)) {
6107     // We're in a lambda; determine the lambda capture field maps unless we're
6108     // just constexpr checking a lambda's call operator. constexpr checking is
6109     // done before the captures have been added to the closure object (unless
6110     // we're inferring constexpr-ness), so we don't have access to them in this
6111     // case. But since we don't need the captures to constexpr check, we can
6112     // just ignore them.
6113     if (!Info.checkingPotentialConstantExpression())
6114       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6115                                         Frame.LambdaThisCaptureField);
6116   }
6117 
6118   StmtResult Ret = {Result, ResultSlot};
6119   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6120   if (ESR == ESR_Succeeded) {
6121     if (Callee->getReturnType()->isVoidType())
6122       return true;
6123     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6124   }
6125   return ESR == ESR_Returned;
6126 }
6127 
6128 /// Evaluate a constructor call.
6129 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6130                                   CallRef Call,
6131                                   const CXXConstructorDecl *Definition,
6132                                   EvalInfo &Info, APValue &Result) {
6133   SourceLocation CallLoc = E->getExprLoc();
6134   if (!Info.CheckCallLimit(CallLoc))
6135     return false;
6136 
6137   const CXXRecordDecl *RD = Definition->getParent();
6138   if (RD->getNumVBases()) {
6139     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6140     return false;
6141   }
6142 
6143   EvalInfo::EvaluatingConstructorRAII EvalObj(
6144       Info,
6145       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6146       RD->getNumBases());
6147   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6148 
6149   // FIXME: Creating an APValue just to hold a nonexistent return value is
6150   // wasteful.
6151   APValue RetVal;
6152   StmtResult Ret = {RetVal, nullptr};
6153 
6154   // If it's a delegating constructor, delegate.
6155   if (Definition->isDelegatingConstructor()) {
6156     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6157     if ((*I)->getInit()->isValueDependent()) {
6158       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6159         return false;
6160     } else {
6161       FullExpressionRAII InitScope(Info);
6162       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6163           !InitScope.destroy())
6164         return false;
6165     }
6166     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6167   }
6168 
6169   // For a trivial copy or move constructor, perform an APValue copy. This is
6170   // essential for unions (or classes with anonymous union members), where the
6171   // operations performed by the constructor cannot be represented by
6172   // ctor-initializers.
6173   //
6174   // Skip this for empty non-union classes; we should not perform an
6175   // lvalue-to-rvalue conversion on them because their copy constructor does not
6176   // actually read them.
6177   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6178       (Definition->getParent()->isUnion() ||
6179        (Definition->isTrivial() &&
6180         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6181     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6182                              Definition->getParent()->isUnion());
6183   }
6184 
6185   // Reserve space for the struct members.
6186   if (!Result.hasValue()) {
6187     if (!RD->isUnion())
6188       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6189                        std::distance(RD->field_begin(), RD->field_end()));
6190     else
6191       // A union starts with no active member.
6192       Result = APValue((const FieldDecl*)nullptr);
6193   }
6194 
6195   if (RD->isInvalidDecl()) return false;
6196   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6197 
6198   // A scope for temporaries lifetime-extended by reference members.
6199   BlockScopeRAII LifetimeExtendedScope(Info);
6200 
6201   bool Success = true;
6202   unsigned BasesSeen = 0;
6203 #ifndef NDEBUG
6204   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6205 #endif
6206   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6207   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6208     // We might be initializing the same field again if this is an indirect
6209     // field initialization.
6210     if (FieldIt == RD->field_end() ||
6211         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6212       assert(Indirect && "fields out of order?");
6213       return;
6214     }
6215 
6216     // Default-initialize any fields with no explicit initializer.
6217     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6218       assert(FieldIt != RD->field_end() && "missing field?");
6219       if (!FieldIt->isUnnamedBitfield())
6220         Success &= getDefaultInitValue(
6221             FieldIt->getType(),
6222             Result.getStructField(FieldIt->getFieldIndex()));
6223     }
6224     ++FieldIt;
6225   };
6226   for (const auto *I : Definition->inits()) {
6227     LValue Subobject = This;
6228     LValue SubobjectParent = This;
6229     APValue *Value = &Result;
6230 
6231     // Determine the subobject to initialize.
6232     FieldDecl *FD = nullptr;
6233     if (I->isBaseInitializer()) {
6234       QualType BaseType(I->getBaseClass(), 0);
6235 #ifndef NDEBUG
6236       // Non-virtual base classes are initialized in the order in the class
6237       // definition. We have already checked for virtual base classes.
6238       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6239       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6240              "base class initializers not in expected order");
6241       ++BaseIt;
6242 #endif
6243       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6244                                   BaseType->getAsCXXRecordDecl(), &Layout))
6245         return false;
6246       Value = &Result.getStructBase(BasesSeen++);
6247     } else if ((FD = I->getMember())) {
6248       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6249         return false;
6250       if (RD->isUnion()) {
6251         Result = APValue(FD);
6252         Value = &Result.getUnionValue();
6253       } else {
6254         SkipToField(FD, false);
6255         Value = &Result.getStructField(FD->getFieldIndex());
6256       }
6257     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6258       // Walk the indirect field decl's chain to find the object to initialize,
6259       // and make sure we've initialized every step along it.
6260       auto IndirectFieldChain = IFD->chain();
6261       for (auto *C : IndirectFieldChain) {
6262         FD = cast<FieldDecl>(C);
6263         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6264         // Switch the union field if it differs. This happens if we had
6265         // preceding zero-initialization, and we're now initializing a union
6266         // subobject other than the first.
6267         // FIXME: In this case, the values of the other subobjects are
6268         // specified, since zero-initialization sets all padding bits to zero.
6269         if (!Value->hasValue() ||
6270             (Value->isUnion() && Value->getUnionField() != FD)) {
6271           if (CD->isUnion())
6272             *Value = APValue(FD);
6273           else
6274             // FIXME: This immediately starts the lifetime of all members of
6275             // an anonymous struct. It would be preferable to strictly start
6276             // member lifetime in initialization order.
6277             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6278         }
6279         // Store Subobject as its parent before updating it for the last element
6280         // in the chain.
6281         if (C == IndirectFieldChain.back())
6282           SubobjectParent = Subobject;
6283         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6284           return false;
6285         if (CD->isUnion())
6286           Value = &Value->getUnionValue();
6287         else {
6288           if (C == IndirectFieldChain.front() && !RD->isUnion())
6289             SkipToField(FD, true);
6290           Value = &Value->getStructField(FD->getFieldIndex());
6291         }
6292       }
6293     } else {
6294       llvm_unreachable("unknown base initializer kind");
6295     }
6296 
6297     // Need to override This for implicit field initializers as in this case
6298     // This refers to innermost anonymous struct/union containing initializer,
6299     // not to currently constructed class.
6300     const Expr *Init = I->getInit();
6301     if (Init->isValueDependent()) {
6302       if (!EvaluateDependentExpr(Init, Info))
6303         return false;
6304     } else {
6305       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6306                                     isa<CXXDefaultInitExpr>(Init));
6307       FullExpressionRAII InitScope(Info);
6308       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6309           (FD && FD->isBitField() &&
6310            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6311         // If we're checking for a potential constant expression, evaluate all
6312         // initializers even if some of them fail.
6313         if (!Info.noteFailure())
6314           return false;
6315         Success = false;
6316       }
6317     }
6318 
6319     // This is the point at which the dynamic type of the object becomes this
6320     // class type.
6321     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6322       EvalObj.finishedConstructingBases();
6323   }
6324 
6325   // Default-initialize any remaining fields.
6326   if (!RD->isUnion()) {
6327     for (; FieldIt != RD->field_end(); ++FieldIt) {
6328       if (!FieldIt->isUnnamedBitfield())
6329         Success &= getDefaultInitValue(
6330             FieldIt->getType(),
6331             Result.getStructField(FieldIt->getFieldIndex()));
6332     }
6333   }
6334 
6335   EvalObj.finishedConstructingFields();
6336 
6337   return Success &&
6338          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6339          LifetimeExtendedScope.destroy();
6340 }
6341 
6342 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6343                                   ArrayRef<const Expr*> Args,
6344                                   const CXXConstructorDecl *Definition,
6345                                   EvalInfo &Info, APValue &Result) {
6346   CallScopeRAII CallScope(Info);
6347   CallRef Call = Info.CurrentCall->createCall(Definition);
6348   if (!EvaluateArgs(Args, Call, Info, Definition))
6349     return false;
6350 
6351   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6352          CallScope.destroy();
6353 }
6354 
6355 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6356                                   const LValue &This, APValue &Value,
6357                                   QualType T) {
6358   // Objects can only be destroyed while they're within their lifetimes.
6359   // FIXME: We have no representation for whether an object of type nullptr_t
6360   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6361   // as indeterminate instead?
6362   if (Value.isAbsent() && !T->isNullPtrType()) {
6363     APValue Printable;
6364     This.moveInto(Printable);
6365     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6366       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6367     return false;
6368   }
6369 
6370   // Invent an expression for location purposes.
6371   // FIXME: We shouldn't need to do this.
6372   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6373 
6374   // For arrays, destroy elements right-to-left.
6375   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6376     uint64_t Size = CAT->getSize().getZExtValue();
6377     QualType ElemT = CAT->getElementType();
6378 
6379     LValue ElemLV = This;
6380     ElemLV.addArray(Info, &LocE, CAT);
6381     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6382       return false;
6383 
6384     // Ensure that we have actual array elements available to destroy; the
6385     // destructors might mutate the value, so we can't run them on the array
6386     // filler.
6387     if (Size && Size > Value.getArrayInitializedElts())
6388       expandArray(Value, Value.getArraySize() - 1);
6389 
6390     for (; Size != 0; --Size) {
6391       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6392       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6393           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6394         return false;
6395     }
6396 
6397     // End the lifetime of this array now.
6398     Value = APValue();
6399     return true;
6400   }
6401 
6402   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6403   if (!RD) {
6404     if (T.isDestructedType()) {
6405       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6406       return false;
6407     }
6408 
6409     Value = APValue();
6410     return true;
6411   }
6412 
6413   if (RD->getNumVBases()) {
6414     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6415     return false;
6416   }
6417 
6418   const CXXDestructorDecl *DD = RD->getDestructor();
6419   if (!DD && !RD->hasTrivialDestructor()) {
6420     Info.FFDiag(CallLoc);
6421     return false;
6422   }
6423 
6424   if (!DD || DD->isTrivial() ||
6425       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6426     // A trivial destructor just ends the lifetime of the object. Check for
6427     // this case before checking for a body, because we might not bother
6428     // building a body for a trivial destructor. Note that it doesn't matter
6429     // whether the destructor is constexpr in this case; all trivial
6430     // destructors are constexpr.
6431     //
6432     // If an anonymous union would be destroyed, some enclosing destructor must
6433     // have been explicitly defined, and the anonymous union destruction should
6434     // have no effect.
6435     Value = APValue();
6436     return true;
6437   }
6438 
6439   if (!Info.CheckCallLimit(CallLoc))
6440     return false;
6441 
6442   const FunctionDecl *Definition = nullptr;
6443   const Stmt *Body = DD->getBody(Definition);
6444 
6445   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6446     return false;
6447 
6448   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6449 
6450   // We're now in the period of destruction of this object.
6451   unsigned BasesLeft = RD->getNumBases();
6452   EvalInfo::EvaluatingDestructorRAII EvalObj(
6453       Info,
6454       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6455   if (!EvalObj.DidInsert) {
6456     // C++2a [class.dtor]p19:
6457     //   the behavior is undefined if the destructor is invoked for an object
6458     //   whose lifetime has ended
6459     // (Note that formally the lifetime ends when the period of destruction
6460     // begins, even though certain uses of the object remain valid until the
6461     // period of destruction ends.)
6462     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6463     return false;
6464   }
6465 
6466   // FIXME: Creating an APValue just to hold a nonexistent return value is
6467   // wasteful.
6468   APValue RetVal;
6469   StmtResult Ret = {RetVal, nullptr};
6470   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6471     return false;
6472 
6473   // A union destructor does not implicitly destroy its members.
6474   if (RD->isUnion())
6475     return true;
6476 
6477   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6478 
6479   // We don't have a good way to iterate fields in reverse, so collect all the
6480   // fields first and then walk them backwards.
6481   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6482   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6483     if (FD->isUnnamedBitfield())
6484       continue;
6485 
6486     LValue Subobject = This;
6487     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6488       return false;
6489 
6490     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6491     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6492                                FD->getType()))
6493       return false;
6494   }
6495 
6496   if (BasesLeft != 0)
6497     EvalObj.startedDestroyingBases();
6498 
6499   // Destroy base classes in reverse order.
6500   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6501     --BasesLeft;
6502 
6503     QualType BaseType = Base.getType();
6504     LValue Subobject = This;
6505     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6506                                 BaseType->getAsCXXRecordDecl(), &Layout))
6507       return false;
6508 
6509     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6510     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6511                                BaseType))
6512       return false;
6513   }
6514   assert(BasesLeft == 0 && "NumBases was wrong?");
6515 
6516   // The period of destruction ends now. The object is gone.
6517   Value = APValue();
6518   return true;
6519 }
6520 
6521 namespace {
6522 struct DestroyObjectHandler {
6523   EvalInfo &Info;
6524   const Expr *E;
6525   const LValue &This;
6526   const AccessKinds AccessKind;
6527 
6528   typedef bool result_type;
6529   bool failed() { return false; }
6530   bool found(APValue &Subobj, QualType SubobjType) {
6531     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6532                                  SubobjType);
6533   }
6534   bool found(APSInt &Value, QualType SubobjType) {
6535     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6536     return false;
6537   }
6538   bool found(APFloat &Value, QualType SubobjType) {
6539     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6540     return false;
6541   }
6542 };
6543 }
6544 
6545 /// Perform a destructor or pseudo-destructor call on the given object, which
6546 /// might in general not be a complete object.
6547 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6548                               const LValue &This, QualType ThisType) {
6549   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6550   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6551   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6552 }
6553 
6554 /// Destroy and end the lifetime of the given complete object.
6555 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6556                               APValue::LValueBase LVBase, APValue &Value,
6557                               QualType T) {
6558   // If we've had an unmodeled side-effect, we can't rely on mutable state
6559   // (such as the object we're about to destroy) being correct.
6560   if (Info.EvalStatus.HasSideEffects)
6561     return false;
6562 
6563   LValue LV;
6564   LV.set({LVBase});
6565   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6566 }
6567 
6568 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6569 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6570                                   LValue &Result) {
6571   if (Info.checkingPotentialConstantExpression() ||
6572       Info.SpeculativeEvaluationDepth)
6573     return false;
6574 
6575   // This is permitted only within a call to std::allocator<T>::allocate.
6576   auto Caller = Info.getStdAllocatorCaller("allocate");
6577   if (!Caller) {
6578     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6579                                      ? diag::note_constexpr_new_untyped
6580                                      : diag::note_constexpr_new);
6581     return false;
6582   }
6583 
6584   QualType ElemType = Caller.ElemType;
6585   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6586     Info.FFDiag(E->getExprLoc(),
6587                 diag::note_constexpr_new_not_complete_object_type)
6588         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6589     return false;
6590   }
6591 
6592   APSInt ByteSize;
6593   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6594     return false;
6595   bool IsNothrow = false;
6596   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6597     EvaluateIgnoredValue(Info, E->getArg(I));
6598     IsNothrow |= E->getType()->isNothrowT();
6599   }
6600 
6601   CharUnits ElemSize;
6602   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6603     return false;
6604   APInt Size, Remainder;
6605   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6606   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6607   if (Remainder != 0) {
6608     // This likely indicates a bug in the implementation of 'std::allocator'.
6609     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6610         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6611     return false;
6612   }
6613 
6614   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6615     if (IsNothrow) {
6616       Result.setNull(Info.Ctx, E->getType());
6617       return true;
6618     }
6619 
6620     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6621     return false;
6622   }
6623 
6624   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6625                                                      ArrayType::Normal, 0);
6626   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6627   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6628   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6629   return true;
6630 }
6631 
6632 static bool hasVirtualDestructor(QualType T) {
6633   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6634     if (CXXDestructorDecl *DD = RD->getDestructor())
6635       return DD->isVirtual();
6636   return false;
6637 }
6638 
6639 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6640   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6641     if (CXXDestructorDecl *DD = RD->getDestructor())
6642       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6643   return nullptr;
6644 }
6645 
6646 /// Check that the given object is a suitable pointer to a heap allocation that
6647 /// still exists and is of the right kind for the purpose of a deletion.
6648 ///
6649 /// On success, returns the heap allocation to deallocate. On failure, produces
6650 /// a diagnostic and returns None.
6651 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6652                                             const LValue &Pointer,
6653                                             DynAlloc::Kind DeallocKind) {
6654   auto PointerAsString = [&] {
6655     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6656   };
6657 
6658   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6659   if (!DA) {
6660     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6661         << PointerAsString();
6662     if (Pointer.Base)
6663       NoteLValueLocation(Info, Pointer.Base);
6664     return None;
6665   }
6666 
6667   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6668   if (!Alloc) {
6669     Info.FFDiag(E, diag::note_constexpr_double_delete);
6670     return None;
6671   }
6672 
6673   QualType AllocType = Pointer.Base.getDynamicAllocType();
6674   if (DeallocKind != (*Alloc)->getKind()) {
6675     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6676         << DeallocKind << (*Alloc)->getKind() << AllocType;
6677     NoteLValueLocation(Info, Pointer.Base);
6678     return None;
6679   }
6680 
6681   bool Subobject = false;
6682   if (DeallocKind == DynAlloc::New) {
6683     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6684                 Pointer.Designator.isOnePastTheEnd();
6685   } else {
6686     Subobject = Pointer.Designator.Entries.size() != 1 ||
6687                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6688   }
6689   if (Subobject) {
6690     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6691         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6692     return None;
6693   }
6694 
6695   return Alloc;
6696 }
6697 
6698 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6699 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6700   if (Info.checkingPotentialConstantExpression() ||
6701       Info.SpeculativeEvaluationDepth)
6702     return false;
6703 
6704   // This is permitted only within a call to std::allocator<T>::deallocate.
6705   if (!Info.getStdAllocatorCaller("deallocate")) {
6706     Info.FFDiag(E->getExprLoc());
6707     return true;
6708   }
6709 
6710   LValue Pointer;
6711   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6712     return false;
6713   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6714     EvaluateIgnoredValue(Info, E->getArg(I));
6715 
6716   if (Pointer.Designator.Invalid)
6717     return false;
6718 
6719   // Deleting a null pointer would have no effect, but it's not permitted by
6720   // std::allocator<T>::deallocate's contract.
6721   if (Pointer.isNullPointer()) {
6722     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6723     return true;
6724   }
6725 
6726   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6727     return false;
6728 
6729   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6730   return true;
6731 }
6732 
6733 //===----------------------------------------------------------------------===//
6734 // Generic Evaluation
6735 //===----------------------------------------------------------------------===//
6736 namespace {
6737 
6738 class BitCastBuffer {
6739   // FIXME: We're going to need bit-level granularity when we support
6740   // bit-fields.
6741   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6742   // we don't support a host or target where that is the case. Still, we should
6743   // use a more generic type in case we ever do.
6744   SmallVector<Optional<unsigned char>, 32> Bytes;
6745 
6746   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6747                 "Need at least 8 bit unsigned char");
6748 
6749   bool TargetIsLittleEndian;
6750 
6751 public:
6752   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6753       : Bytes(Width.getQuantity()),
6754         TargetIsLittleEndian(TargetIsLittleEndian) {}
6755 
6756   LLVM_NODISCARD
6757   bool readObject(CharUnits Offset, CharUnits Width,
6758                   SmallVectorImpl<unsigned char> &Output) const {
6759     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6760       // If a byte of an integer is uninitialized, then the whole integer is
6761       // uninitialized.
6762       if (!Bytes[I.getQuantity()])
6763         return false;
6764       Output.push_back(*Bytes[I.getQuantity()]);
6765     }
6766     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6767       std::reverse(Output.begin(), Output.end());
6768     return true;
6769   }
6770 
6771   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6772     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6773       std::reverse(Input.begin(), Input.end());
6774 
6775     size_t Index = 0;
6776     for (unsigned char Byte : Input) {
6777       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6778       Bytes[Offset.getQuantity() + Index] = Byte;
6779       ++Index;
6780     }
6781   }
6782 
6783   size_t size() { return Bytes.size(); }
6784 };
6785 
6786 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6787 /// target would represent the value at runtime.
6788 class APValueToBufferConverter {
6789   EvalInfo &Info;
6790   BitCastBuffer Buffer;
6791   const CastExpr *BCE;
6792 
6793   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6794                            const CastExpr *BCE)
6795       : Info(Info),
6796         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6797         BCE(BCE) {}
6798 
6799   bool visit(const APValue &Val, QualType Ty) {
6800     return visit(Val, Ty, CharUnits::fromQuantity(0));
6801   }
6802 
6803   // Write out Val with type Ty into Buffer starting at Offset.
6804   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6805     assert((size_t)Offset.getQuantity() <= Buffer.size());
6806 
6807     // As a special case, nullptr_t has an indeterminate value.
6808     if (Ty->isNullPtrType())
6809       return true;
6810 
6811     // Dig through Src to find the byte at SrcOffset.
6812     switch (Val.getKind()) {
6813     case APValue::Indeterminate:
6814     case APValue::None:
6815       return true;
6816 
6817     case APValue::Int:
6818       return visitInt(Val.getInt(), Ty, Offset);
6819     case APValue::Float:
6820       return visitFloat(Val.getFloat(), Ty, Offset);
6821     case APValue::Array:
6822       return visitArray(Val, Ty, Offset);
6823     case APValue::Struct:
6824       return visitRecord(Val, Ty, Offset);
6825 
6826     case APValue::ComplexInt:
6827     case APValue::ComplexFloat:
6828     case APValue::Vector:
6829     case APValue::FixedPoint:
6830       // FIXME: We should support these.
6831 
6832     case APValue::Union:
6833     case APValue::MemberPointer:
6834     case APValue::AddrLabelDiff: {
6835       Info.FFDiag(BCE->getBeginLoc(),
6836                   diag::note_constexpr_bit_cast_unsupported_type)
6837           << Ty;
6838       return false;
6839     }
6840 
6841     case APValue::LValue:
6842       llvm_unreachable("LValue subobject in bit_cast?");
6843     }
6844     llvm_unreachable("Unhandled APValue::ValueKind");
6845   }
6846 
6847   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6848     const RecordDecl *RD = Ty->getAsRecordDecl();
6849     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6850 
6851     // Visit the base classes.
6852     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6853       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6854         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6855         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6856 
6857         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6858                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6859           return false;
6860       }
6861     }
6862 
6863     // Visit the fields.
6864     unsigned FieldIdx = 0;
6865     for (FieldDecl *FD : RD->fields()) {
6866       if (FD->isBitField()) {
6867         Info.FFDiag(BCE->getBeginLoc(),
6868                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6869         return false;
6870       }
6871 
6872       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6873 
6874       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6875              "only bit-fields can have sub-char alignment");
6876       CharUnits FieldOffset =
6877           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6878       QualType FieldTy = FD->getType();
6879       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6880         return false;
6881       ++FieldIdx;
6882     }
6883 
6884     return true;
6885   }
6886 
6887   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6888     const auto *CAT =
6889         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6890     if (!CAT)
6891       return false;
6892 
6893     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6894     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6895     unsigned ArraySize = Val.getArraySize();
6896     // First, initialize the initialized elements.
6897     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6898       const APValue &SubObj = Val.getArrayInitializedElt(I);
6899       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6900         return false;
6901     }
6902 
6903     // Next, initialize the rest of the array using the filler.
6904     if (Val.hasArrayFiller()) {
6905       const APValue &Filler = Val.getArrayFiller();
6906       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6907         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6908           return false;
6909       }
6910     }
6911 
6912     return true;
6913   }
6914 
6915   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6916     APSInt AdjustedVal = Val;
6917     unsigned Width = AdjustedVal.getBitWidth();
6918     if (Ty->isBooleanType()) {
6919       Width = Info.Ctx.getTypeSize(Ty);
6920       AdjustedVal = AdjustedVal.extend(Width);
6921     }
6922 
6923     SmallVector<unsigned char, 8> Bytes(Width / 8);
6924     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6925     Buffer.writeObject(Offset, Bytes);
6926     return true;
6927   }
6928 
6929   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6930     APSInt AsInt(Val.bitcastToAPInt());
6931     return visitInt(AsInt, Ty, Offset);
6932   }
6933 
6934 public:
6935   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6936                                          const CastExpr *BCE) {
6937     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6938     APValueToBufferConverter Converter(Info, DstSize, BCE);
6939     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6940       return None;
6941     return Converter.Buffer;
6942   }
6943 };
6944 
6945 /// Write an BitCastBuffer into an APValue.
6946 class BufferToAPValueConverter {
6947   EvalInfo &Info;
6948   const BitCastBuffer &Buffer;
6949   const CastExpr *BCE;
6950 
6951   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6952                            const CastExpr *BCE)
6953       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6954 
6955   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6956   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6957   // Ideally this will be unreachable.
6958   llvm::NoneType unsupportedType(QualType Ty) {
6959     Info.FFDiag(BCE->getBeginLoc(),
6960                 diag::note_constexpr_bit_cast_unsupported_type)
6961         << Ty;
6962     return None;
6963   }
6964 
6965   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6966     Info.FFDiag(BCE->getBeginLoc(),
6967                 diag::note_constexpr_bit_cast_unrepresentable_value)
6968         << Ty << toString(Val, /*Radix=*/10);
6969     return None;
6970   }
6971 
6972   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6973                           const EnumType *EnumSugar = nullptr) {
6974     if (T->isNullPtrType()) {
6975       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6976       return APValue((Expr *)nullptr,
6977                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6978                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6979     }
6980 
6981     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6982 
6983     // Work around floating point types that contain unused padding bytes. This
6984     // is really just `long double` on x86, which is the only fundamental type
6985     // with padding bytes.
6986     if (T->isRealFloatingType()) {
6987       const llvm::fltSemantics &Semantics =
6988           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6989       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6990       assert(NumBits % 8 == 0);
6991       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6992       if (NumBytes != SizeOf)
6993         SizeOf = NumBytes;
6994     }
6995 
6996     SmallVector<uint8_t, 8> Bytes;
6997     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6998       // If this is std::byte or unsigned char, then its okay to store an
6999       // indeterminate value.
7000       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7001       bool IsUChar =
7002           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7003                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7004       if (!IsStdByte && !IsUChar) {
7005         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7006         Info.FFDiag(BCE->getExprLoc(),
7007                     diag::note_constexpr_bit_cast_indet_dest)
7008             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7009         return None;
7010       }
7011 
7012       return APValue::IndeterminateValue();
7013     }
7014 
7015     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7016     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7017 
7018     if (T->isIntegralOrEnumerationType()) {
7019       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7020 
7021       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7022       if (IntWidth != Val.getBitWidth()) {
7023         APSInt Truncated = Val.trunc(IntWidth);
7024         if (Truncated.extend(Val.getBitWidth()) != Val)
7025           return unrepresentableValue(QualType(T, 0), Val);
7026         Val = Truncated;
7027       }
7028 
7029       return APValue(Val);
7030     }
7031 
7032     if (T->isRealFloatingType()) {
7033       const llvm::fltSemantics &Semantics =
7034           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7035       return APValue(APFloat(Semantics, Val));
7036     }
7037 
7038     return unsupportedType(QualType(T, 0));
7039   }
7040 
7041   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7042     const RecordDecl *RD = RTy->getAsRecordDecl();
7043     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7044 
7045     unsigned NumBases = 0;
7046     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7047       NumBases = CXXRD->getNumBases();
7048 
7049     APValue ResultVal(APValue::UninitStruct(), NumBases,
7050                       std::distance(RD->field_begin(), RD->field_end()));
7051 
7052     // Visit the base classes.
7053     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7054       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7055         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7056         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7057         if (BaseDecl->isEmpty() ||
7058             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7059           continue;
7060 
7061         Optional<APValue> SubObj = visitType(
7062             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7063         if (!SubObj)
7064           return None;
7065         ResultVal.getStructBase(I) = *SubObj;
7066       }
7067     }
7068 
7069     // Visit the fields.
7070     unsigned FieldIdx = 0;
7071     for (FieldDecl *FD : RD->fields()) {
7072       // FIXME: We don't currently support bit-fields. A lot of the logic for
7073       // this is in CodeGen, so we need to factor it around.
7074       if (FD->isBitField()) {
7075         Info.FFDiag(BCE->getBeginLoc(),
7076                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7077         return None;
7078       }
7079 
7080       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7081       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7082 
7083       CharUnits FieldOffset =
7084           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7085           Offset;
7086       QualType FieldTy = FD->getType();
7087       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7088       if (!SubObj)
7089         return None;
7090       ResultVal.getStructField(FieldIdx) = *SubObj;
7091       ++FieldIdx;
7092     }
7093 
7094     return ResultVal;
7095   }
7096 
7097   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7098     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7099     assert(!RepresentationType.isNull() &&
7100            "enum forward decl should be caught by Sema");
7101     const auto *AsBuiltin =
7102         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7103     // Recurse into the underlying type. Treat std::byte transparently as
7104     // unsigned char.
7105     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7106   }
7107 
7108   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7109     size_t Size = Ty->getSize().getLimitedValue();
7110     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7111 
7112     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7113     for (size_t I = 0; I != Size; ++I) {
7114       Optional<APValue> ElementValue =
7115           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7116       if (!ElementValue)
7117         return None;
7118       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7119     }
7120 
7121     return ArrayValue;
7122   }
7123 
7124   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7125     return unsupportedType(QualType(Ty, 0));
7126   }
7127 
7128   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7129     QualType Can = Ty.getCanonicalType();
7130 
7131     switch (Can->getTypeClass()) {
7132 #define TYPE(Class, Base)                                                      \
7133   case Type::Class:                                                            \
7134     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7135 #define ABSTRACT_TYPE(Class, Base)
7136 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7137   case Type::Class:                                                            \
7138     llvm_unreachable("non-canonical type should be impossible!");
7139 #define DEPENDENT_TYPE(Class, Base)                                            \
7140   case Type::Class:                                                            \
7141     llvm_unreachable(                                                          \
7142         "dependent types aren't supported in the constant evaluator!");
7143 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7144   case Type::Class:                                                            \
7145     llvm_unreachable("either dependent or not canonical!");
7146 #include "clang/AST/TypeNodes.inc"
7147     }
7148     llvm_unreachable("Unhandled Type::TypeClass");
7149   }
7150 
7151 public:
7152   // Pull out a full value of type DstType.
7153   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7154                                    const CastExpr *BCE) {
7155     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7156     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7157   }
7158 };
7159 
7160 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7161                                                  QualType Ty, EvalInfo *Info,
7162                                                  const ASTContext &Ctx,
7163                                                  bool CheckingDest) {
7164   Ty = Ty.getCanonicalType();
7165 
7166   auto diag = [&](int Reason) {
7167     if (Info)
7168       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7169           << CheckingDest << (Reason == 4) << Reason;
7170     return false;
7171   };
7172   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7173     if (Info)
7174       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7175           << NoteTy << Construct << Ty;
7176     return false;
7177   };
7178 
7179   if (Ty->isUnionType())
7180     return diag(0);
7181   if (Ty->isPointerType())
7182     return diag(1);
7183   if (Ty->isMemberPointerType())
7184     return diag(2);
7185   if (Ty.isVolatileQualified())
7186     return diag(3);
7187 
7188   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7189     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7190       for (CXXBaseSpecifier &BS : CXXRD->bases())
7191         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7192                                                   CheckingDest))
7193           return note(1, BS.getType(), BS.getBeginLoc());
7194     }
7195     for (FieldDecl *FD : Record->fields()) {
7196       if (FD->getType()->isReferenceType())
7197         return diag(4);
7198       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7199                                                 CheckingDest))
7200         return note(0, FD->getType(), FD->getBeginLoc());
7201     }
7202   }
7203 
7204   if (Ty->isArrayType() &&
7205       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7206                                             Info, Ctx, CheckingDest))
7207     return false;
7208 
7209   return true;
7210 }
7211 
7212 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7213                                              const ASTContext &Ctx,
7214                                              const CastExpr *BCE) {
7215   bool DestOK = checkBitCastConstexprEligibilityType(
7216       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7217   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7218                                 BCE->getBeginLoc(),
7219                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7220   return SourceOK;
7221 }
7222 
7223 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7224                                         APValue &SourceValue,
7225                                         const CastExpr *BCE) {
7226   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7227          "no host or target supports non 8-bit chars");
7228   assert(SourceValue.isLValue() &&
7229          "LValueToRValueBitcast requires an lvalue operand!");
7230 
7231   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7232     return false;
7233 
7234   LValue SourceLValue;
7235   APValue SourceRValue;
7236   SourceLValue.setFrom(Info.Ctx, SourceValue);
7237   if (!handleLValueToRValueConversion(
7238           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7239           SourceRValue, /*WantObjectRepresentation=*/true))
7240     return false;
7241 
7242   // Read out SourceValue into a char buffer.
7243   Optional<BitCastBuffer> Buffer =
7244       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7245   if (!Buffer)
7246     return false;
7247 
7248   // Write out the buffer into a new APValue.
7249   Optional<APValue> MaybeDestValue =
7250       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7251   if (!MaybeDestValue)
7252     return false;
7253 
7254   DestValue = std::move(*MaybeDestValue);
7255   return true;
7256 }
7257 
7258 template <class Derived>
7259 class ExprEvaluatorBase
7260   : public ConstStmtVisitor<Derived, bool> {
7261 private:
7262   Derived &getDerived() { return static_cast<Derived&>(*this); }
7263   bool DerivedSuccess(const APValue &V, const Expr *E) {
7264     return getDerived().Success(V, E);
7265   }
7266   bool DerivedZeroInitialization(const Expr *E) {
7267     return getDerived().ZeroInitialization(E);
7268   }
7269 
7270   // Check whether a conditional operator with a non-constant condition is a
7271   // potential constant expression. If neither arm is a potential constant
7272   // expression, then the conditional operator is not either.
7273   template<typename ConditionalOperator>
7274   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7275     assert(Info.checkingPotentialConstantExpression());
7276 
7277     // Speculatively evaluate both arms.
7278     SmallVector<PartialDiagnosticAt, 8> Diag;
7279     {
7280       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7281       StmtVisitorTy::Visit(E->getFalseExpr());
7282       if (Diag.empty())
7283         return;
7284     }
7285 
7286     {
7287       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7288       Diag.clear();
7289       StmtVisitorTy::Visit(E->getTrueExpr());
7290       if (Diag.empty())
7291         return;
7292     }
7293 
7294     Error(E, diag::note_constexpr_conditional_never_const);
7295   }
7296 
7297 
7298   template<typename ConditionalOperator>
7299   bool HandleConditionalOperator(const ConditionalOperator *E) {
7300     bool BoolResult;
7301     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7302       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7303         CheckPotentialConstantConditional(E);
7304         return false;
7305       }
7306       if (Info.noteFailure()) {
7307         StmtVisitorTy::Visit(E->getTrueExpr());
7308         StmtVisitorTy::Visit(E->getFalseExpr());
7309       }
7310       return false;
7311     }
7312 
7313     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7314     return StmtVisitorTy::Visit(EvalExpr);
7315   }
7316 
7317 protected:
7318   EvalInfo &Info;
7319   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7320   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7321 
7322   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7323     return Info.CCEDiag(E, D);
7324   }
7325 
7326   bool ZeroInitialization(const Expr *E) { return Error(E); }
7327 
7328 public:
7329   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7330 
7331   EvalInfo &getEvalInfo() { return Info; }
7332 
7333   /// Report an evaluation error. This should only be called when an error is
7334   /// first discovered. When propagating an error, just return false.
7335   bool Error(const Expr *E, diag::kind D) {
7336     Info.FFDiag(E, D);
7337     return false;
7338   }
7339   bool Error(const Expr *E) {
7340     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7341   }
7342 
7343   bool VisitStmt(const Stmt *) {
7344     llvm_unreachable("Expression evaluator should not be called on stmts");
7345   }
7346   bool VisitExpr(const Expr *E) {
7347     return Error(E);
7348   }
7349 
7350   bool VisitConstantExpr(const ConstantExpr *E) {
7351     if (E->hasAPValueResult())
7352       return DerivedSuccess(E->getAPValueResult(), E);
7353 
7354     return StmtVisitorTy::Visit(E->getSubExpr());
7355   }
7356 
7357   bool VisitParenExpr(const ParenExpr *E)
7358     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7359   bool VisitUnaryExtension(const UnaryOperator *E)
7360     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7361   bool VisitUnaryPlus(const UnaryOperator *E)
7362     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7363   bool VisitChooseExpr(const ChooseExpr *E)
7364     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7365   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7366     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7367   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7368     { return StmtVisitorTy::Visit(E->getReplacement()); }
7369   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7370     TempVersionRAII RAII(*Info.CurrentCall);
7371     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7372     return StmtVisitorTy::Visit(E->getExpr());
7373   }
7374   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7375     TempVersionRAII RAII(*Info.CurrentCall);
7376     // The initializer may not have been parsed yet, or might be erroneous.
7377     if (!E->getExpr())
7378       return Error(E);
7379     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7380     return StmtVisitorTy::Visit(E->getExpr());
7381   }
7382 
7383   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7384     FullExpressionRAII Scope(Info);
7385     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7386   }
7387 
7388   // Temporaries are registered when created, so we don't care about
7389   // CXXBindTemporaryExpr.
7390   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7391     return StmtVisitorTy::Visit(E->getSubExpr());
7392   }
7393 
7394   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7395     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7396     return static_cast<Derived*>(this)->VisitCastExpr(E);
7397   }
7398   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7399     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7400       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7401     return static_cast<Derived*>(this)->VisitCastExpr(E);
7402   }
7403   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7404     return static_cast<Derived*>(this)->VisitCastExpr(E);
7405   }
7406 
7407   bool VisitBinaryOperator(const BinaryOperator *E) {
7408     switch (E->getOpcode()) {
7409     default:
7410       return Error(E);
7411 
7412     case BO_Comma:
7413       VisitIgnoredValue(E->getLHS());
7414       return StmtVisitorTy::Visit(E->getRHS());
7415 
7416     case BO_PtrMemD:
7417     case BO_PtrMemI: {
7418       LValue Obj;
7419       if (!HandleMemberPointerAccess(Info, E, Obj))
7420         return false;
7421       APValue Result;
7422       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7423         return false;
7424       return DerivedSuccess(Result, E);
7425     }
7426     }
7427   }
7428 
7429   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7430     return StmtVisitorTy::Visit(E->getSemanticForm());
7431   }
7432 
7433   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7434     // Evaluate and cache the common expression. We treat it as a temporary,
7435     // even though it's not quite the same thing.
7436     LValue CommonLV;
7437     if (!Evaluate(Info.CurrentCall->createTemporary(
7438                       E->getOpaqueValue(),
7439                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7440                       ScopeKind::FullExpression, CommonLV),
7441                   Info, E->getCommon()))
7442       return false;
7443 
7444     return HandleConditionalOperator(E);
7445   }
7446 
7447   bool VisitConditionalOperator(const ConditionalOperator *E) {
7448     bool IsBcpCall = false;
7449     // If the condition (ignoring parens) is a __builtin_constant_p call,
7450     // the result is a constant expression if it can be folded without
7451     // side-effects. This is an important GNU extension. See GCC PR38377
7452     // for discussion.
7453     if (const CallExpr *CallCE =
7454           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7455       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7456         IsBcpCall = true;
7457 
7458     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7459     // constant expression; we can't check whether it's potentially foldable.
7460     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7461     // it would return 'false' in this mode.
7462     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7463       return false;
7464 
7465     FoldConstant Fold(Info, IsBcpCall);
7466     if (!HandleConditionalOperator(E)) {
7467       Fold.keepDiagnostics();
7468       return false;
7469     }
7470 
7471     return true;
7472   }
7473 
7474   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7475     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7476       return DerivedSuccess(*Value, E);
7477 
7478     const Expr *Source = E->getSourceExpr();
7479     if (!Source)
7480       return Error(E);
7481     if (Source == E) { // sanity checking.
7482       assert(0 && "OpaqueValueExpr recursively refers to itself");
7483       return Error(E);
7484     }
7485     return StmtVisitorTy::Visit(Source);
7486   }
7487 
7488   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7489     for (const Expr *SemE : E->semantics()) {
7490       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7491         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7492         // result expression: there could be two different LValues that would
7493         // refer to the same object in that case, and we can't model that.
7494         if (SemE == E->getResultExpr())
7495           return Error(E);
7496 
7497         // Unique OVEs get evaluated if and when we encounter them when
7498         // emitting the rest of the semantic form, rather than eagerly.
7499         if (OVE->isUnique())
7500           continue;
7501 
7502         LValue LV;
7503         if (!Evaluate(Info.CurrentCall->createTemporary(
7504                           OVE, getStorageType(Info.Ctx, OVE),
7505                           ScopeKind::FullExpression, LV),
7506                       Info, OVE->getSourceExpr()))
7507           return false;
7508       } else if (SemE == E->getResultExpr()) {
7509         if (!StmtVisitorTy::Visit(SemE))
7510           return false;
7511       } else {
7512         if (!EvaluateIgnoredValue(Info, SemE))
7513           return false;
7514       }
7515     }
7516     return true;
7517   }
7518 
7519   bool VisitCallExpr(const CallExpr *E) {
7520     APValue Result;
7521     if (!handleCallExpr(E, Result, nullptr))
7522       return false;
7523     return DerivedSuccess(Result, E);
7524   }
7525 
7526   bool handleCallExpr(const CallExpr *E, APValue &Result,
7527                      const LValue *ResultSlot) {
7528     CallScopeRAII CallScope(Info);
7529 
7530     const Expr *Callee = E->getCallee()->IgnoreParens();
7531     QualType CalleeType = Callee->getType();
7532 
7533     const FunctionDecl *FD = nullptr;
7534     LValue *This = nullptr, ThisVal;
7535     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7536     bool HasQualifier = false;
7537 
7538     CallRef Call;
7539 
7540     // Extract function decl and 'this' pointer from the callee.
7541     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7542       const CXXMethodDecl *Member = nullptr;
7543       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7544         // Explicit bound member calls, such as x.f() or p->g();
7545         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7546           return false;
7547         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7548         if (!Member)
7549           return Error(Callee);
7550         This = &ThisVal;
7551         HasQualifier = ME->hasQualifier();
7552       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7553         // Indirect bound member calls ('.*' or '->*').
7554         const ValueDecl *D =
7555             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7556         if (!D)
7557           return false;
7558         Member = dyn_cast<CXXMethodDecl>(D);
7559         if (!Member)
7560           return Error(Callee);
7561         This = &ThisVal;
7562       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7563         if (!Info.getLangOpts().CPlusPlus20)
7564           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7565         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7566                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7567       } else
7568         return Error(Callee);
7569       FD = Member;
7570     } else if (CalleeType->isFunctionPointerType()) {
7571       LValue CalleeLV;
7572       if (!EvaluatePointer(Callee, CalleeLV, Info))
7573         return false;
7574 
7575       if (!CalleeLV.getLValueOffset().isZero())
7576         return Error(Callee);
7577       FD = dyn_cast_or_null<FunctionDecl>(
7578           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7579       if (!FD)
7580         return Error(Callee);
7581       // Don't call function pointers which have been cast to some other type.
7582       // Per DR (no number yet), the caller and callee can differ in noexcept.
7583       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7584         CalleeType->getPointeeType(), FD->getType())) {
7585         return Error(E);
7586       }
7587 
7588       // For an (overloaded) assignment expression, evaluate the RHS before the
7589       // LHS.
7590       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7591       if (OCE && OCE->isAssignmentOp()) {
7592         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7593         Call = Info.CurrentCall->createCall(FD);
7594         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7595                           Info, FD, /*RightToLeft=*/true))
7596           return false;
7597       }
7598 
7599       // Overloaded operator calls to member functions are represented as normal
7600       // calls with '*this' as the first argument.
7601       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7602       if (MD && !MD->isStatic()) {
7603         // FIXME: When selecting an implicit conversion for an overloaded
7604         // operator delete, we sometimes try to evaluate calls to conversion
7605         // operators without a 'this' parameter!
7606         if (Args.empty())
7607           return Error(E);
7608 
7609         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7610           return false;
7611         This = &ThisVal;
7612         Args = Args.slice(1);
7613       } else if (MD && MD->isLambdaStaticInvoker()) {
7614         // Map the static invoker for the lambda back to the call operator.
7615         // Conveniently, we don't have to slice out the 'this' argument (as is
7616         // being done for the non-static case), since a static member function
7617         // doesn't have an implicit argument passed in.
7618         const CXXRecordDecl *ClosureClass = MD->getParent();
7619         assert(
7620             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7621             "Number of captures must be zero for conversion to function-ptr");
7622 
7623         const CXXMethodDecl *LambdaCallOp =
7624             ClosureClass->getLambdaCallOperator();
7625 
7626         // Set 'FD', the function that will be called below, to the call
7627         // operator.  If the closure object represents a generic lambda, find
7628         // the corresponding specialization of the call operator.
7629 
7630         if (ClosureClass->isGenericLambda()) {
7631           assert(MD->isFunctionTemplateSpecialization() &&
7632                  "A generic lambda's static-invoker function must be a "
7633                  "template specialization");
7634           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7635           FunctionTemplateDecl *CallOpTemplate =
7636               LambdaCallOp->getDescribedFunctionTemplate();
7637           void *InsertPos = nullptr;
7638           FunctionDecl *CorrespondingCallOpSpecialization =
7639               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7640           assert(CorrespondingCallOpSpecialization &&
7641                  "We must always have a function call operator specialization "
7642                  "that corresponds to our static invoker specialization");
7643           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7644         } else
7645           FD = LambdaCallOp;
7646       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7647         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7648             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7649           LValue Ptr;
7650           if (!HandleOperatorNewCall(Info, E, Ptr))
7651             return false;
7652           Ptr.moveInto(Result);
7653           return CallScope.destroy();
7654         } else {
7655           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7656         }
7657       }
7658     } else
7659       return Error(E);
7660 
7661     // Evaluate the arguments now if we've not already done so.
7662     if (!Call) {
7663       Call = Info.CurrentCall->createCall(FD);
7664       if (!EvaluateArgs(Args, Call, Info, FD))
7665         return false;
7666     }
7667 
7668     SmallVector<QualType, 4> CovariantAdjustmentPath;
7669     if (This) {
7670       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7671       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7672         // Perform virtual dispatch, if necessary.
7673         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7674                                    CovariantAdjustmentPath);
7675         if (!FD)
7676           return false;
7677       } else {
7678         // Check that the 'this' pointer points to an object of the right type.
7679         // FIXME: If this is an assignment operator call, we may need to change
7680         // the active union member before we check this.
7681         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7682           return false;
7683       }
7684     }
7685 
7686     // Destructor calls are different enough that they have their own codepath.
7687     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7688       assert(This && "no 'this' pointer for destructor call");
7689       return HandleDestruction(Info, E, *This,
7690                                Info.Ctx.getRecordType(DD->getParent())) &&
7691              CallScope.destroy();
7692     }
7693 
7694     const FunctionDecl *Definition = nullptr;
7695     Stmt *Body = FD->getBody(Definition);
7696 
7697     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7698         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7699                             Body, Info, Result, ResultSlot))
7700       return false;
7701 
7702     if (!CovariantAdjustmentPath.empty() &&
7703         !HandleCovariantReturnAdjustment(Info, E, Result,
7704                                          CovariantAdjustmentPath))
7705       return false;
7706 
7707     return CallScope.destroy();
7708   }
7709 
7710   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7711     return StmtVisitorTy::Visit(E->getInitializer());
7712   }
7713   bool VisitInitListExpr(const InitListExpr *E) {
7714     if (E->getNumInits() == 0)
7715       return DerivedZeroInitialization(E);
7716     if (E->getNumInits() == 1)
7717       return StmtVisitorTy::Visit(E->getInit(0));
7718     return Error(E);
7719   }
7720   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7721     return DerivedZeroInitialization(E);
7722   }
7723   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7724     return DerivedZeroInitialization(E);
7725   }
7726   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7727     return DerivedZeroInitialization(E);
7728   }
7729 
7730   /// A member expression where the object is a prvalue is itself a prvalue.
7731   bool VisitMemberExpr(const MemberExpr *E) {
7732     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7733            "missing temporary materialization conversion");
7734     assert(!E->isArrow() && "missing call to bound member function?");
7735 
7736     APValue Val;
7737     if (!Evaluate(Val, Info, E->getBase()))
7738       return false;
7739 
7740     QualType BaseTy = E->getBase()->getType();
7741 
7742     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7743     if (!FD) return Error(E);
7744     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7745     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7746            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7747 
7748     // Note: there is no lvalue base here. But this case should only ever
7749     // happen in C or in C++98, where we cannot be evaluating a constexpr
7750     // constructor, which is the only case the base matters.
7751     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7752     SubobjectDesignator Designator(BaseTy);
7753     Designator.addDeclUnchecked(FD);
7754 
7755     APValue Result;
7756     return extractSubobject(Info, E, Obj, Designator, Result) &&
7757            DerivedSuccess(Result, E);
7758   }
7759 
7760   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7761     APValue Val;
7762     if (!Evaluate(Val, Info, E->getBase()))
7763       return false;
7764 
7765     if (Val.isVector()) {
7766       SmallVector<uint32_t, 4> Indices;
7767       E->getEncodedElementAccess(Indices);
7768       if (Indices.size() == 1) {
7769         // Return scalar.
7770         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7771       } else {
7772         // Construct new APValue vector.
7773         SmallVector<APValue, 4> Elts;
7774         for (unsigned I = 0; I < Indices.size(); ++I) {
7775           Elts.push_back(Val.getVectorElt(Indices[I]));
7776         }
7777         APValue VecResult(Elts.data(), Indices.size());
7778         return DerivedSuccess(VecResult, E);
7779       }
7780     }
7781 
7782     return false;
7783   }
7784 
7785   bool VisitCastExpr(const CastExpr *E) {
7786     switch (E->getCastKind()) {
7787     default:
7788       break;
7789 
7790     case CK_AtomicToNonAtomic: {
7791       APValue AtomicVal;
7792       // This does not need to be done in place even for class/array types:
7793       // atomic-to-non-atomic conversion implies copying the object
7794       // representation.
7795       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7796         return false;
7797       return DerivedSuccess(AtomicVal, E);
7798     }
7799 
7800     case CK_NoOp:
7801     case CK_UserDefinedConversion:
7802       return StmtVisitorTy::Visit(E->getSubExpr());
7803 
7804     case CK_LValueToRValue: {
7805       LValue LVal;
7806       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7807         return false;
7808       APValue RVal;
7809       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7810       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7811                                           LVal, RVal))
7812         return false;
7813       return DerivedSuccess(RVal, E);
7814     }
7815     case CK_LValueToRValueBitCast: {
7816       APValue DestValue, SourceValue;
7817       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7818         return false;
7819       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7820         return false;
7821       return DerivedSuccess(DestValue, E);
7822     }
7823 
7824     case CK_AddressSpaceConversion: {
7825       APValue Value;
7826       if (!Evaluate(Value, Info, E->getSubExpr()))
7827         return false;
7828       return DerivedSuccess(Value, E);
7829     }
7830     }
7831 
7832     return Error(E);
7833   }
7834 
7835   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7836     return VisitUnaryPostIncDec(UO);
7837   }
7838   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7839     return VisitUnaryPostIncDec(UO);
7840   }
7841   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7842     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7843       return Error(UO);
7844 
7845     LValue LVal;
7846     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7847       return false;
7848     APValue RVal;
7849     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7850                       UO->isIncrementOp(), &RVal))
7851       return false;
7852     return DerivedSuccess(RVal, UO);
7853   }
7854 
7855   bool VisitStmtExpr(const StmtExpr *E) {
7856     // We will have checked the full-expressions inside the statement expression
7857     // when they were completed, and don't need to check them again now.
7858     llvm::SaveAndRestore<bool> NotCheckingForUB(
7859         Info.CheckingForUndefinedBehavior, false);
7860 
7861     const CompoundStmt *CS = E->getSubStmt();
7862     if (CS->body_empty())
7863       return true;
7864 
7865     BlockScopeRAII Scope(Info);
7866     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7867                                            BE = CS->body_end();
7868          /**/; ++BI) {
7869       if (BI + 1 == BE) {
7870         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7871         if (!FinalExpr) {
7872           Info.FFDiag((*BI)->getBeginLoc(),
7873                       diag::note_constexpr_stmt_expr_unsupported);
7874           return false;
7875         }
7876         return this->Visit(FinalExpr) && Scope.destroy();
7877       }
7878 
7879       APValue ReturnValue;
7880       StmtResult Result = { ReturnValue, nullptr };
7881       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7882       if (ESR != ESR_Succeeded) {
7883         // FIXME: If the statement-expression terminated due to 'return',
7884         // 'break', or 'continue', it would be nice to propagate that to
7885         // the outer statement evaluation rather than bailing out.
7886         if (ESR != ESR_Failed)
7887           Info.FFDiag((*BI)->getBeginLoc(),
7888                       diag::note_constexpr_stmt_expr_unsupported);
7889         return false;
7890       }
7891     }
7892 
7893     llvm_unreachable("Return from function from the loop above.");
7894   }
7895 
7896   /// Visit a value which is evaluated, but whose value is ignored.
7897   void VisitIgnoredValue(const Expr *E) {
7898     EvaluateIgnoredValue(Info, E);
7899   }
7900 
7901   /// Potentially visit a MemberExpr's base expression.
7902   void VisitIgnoredBaseExpression(const Expr *E) {
7903     // While MSVC doesn't evaluate the base expression, it does diagnose the
7904     // presence of side-effecting behavior.
7905     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7906       return;
7907     VisitIgnoredValue(E);
7908   }
7909 };
7910 
7911 } // namespace
7912 
7913 //===----------------------------------------------------------------------===//
7914 // Common base class for lvalue and temporary evaluation.
7915 //===----------------------------------------------------------------------===//
7916 namespace {
7917 template<class Derived>
7918 class LValueExprEvaluatorBase
7919   : public ExprEvaluatorBase<Derived> {
7920 protected:
7921   LValue &Result;
7922   bool InvalidBaseOK;
7923   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7924   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7925 
7926   bool Success(APValue::LValueBase B) {
7927     Result.set(B);
7928     return true;
7929   }
7930 
7931   bool evaluatePointer(const Expr *E, LValue &Result) {
7932     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7933   }
7934 
7935 public:
7936   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7937       : ExprEvaluatorBaseTy(Info), Result(Result),
7938         InvalidBaseOK(InvalidBaseOK) {}
7939 
7940   bool Success(const APValue &V, const Expr *E) {
7941     Result.setFrom(this->Info.Ctx, V);
7942     return true;
7943   }
7944 
7945   bool VisitMemberExpr(const MemberExpr *E) {
7946     // Handle non-static data members.
7947     QualType BaseTy;
7948     bool EvalOK;
7949     if (E->isArrow()) {
7950       EvalOK = evaluatePointer(E->getBase(), Result);
7951       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7952     } else if (E->getBase()->isPRValue()) {
7953       assert(E->getBase()->getType()->isRecordType());
7954       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7955       BaseTy = E->getBase()->getType();
7956     } else {
7957       EvalOK = this->Visit(E->getBase());
7958       BaseTy = E->getBase()->getType();
7959     }
7960     if (!EvalOK) {
7961       if (!InvalidBaseOK)
7962         return false;
7963       Result.setInvalid(E);
7964       return true;
7965     }
7966 
7967     const ValueDecl *MD = E->getMemberDecl();
7968     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7969       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7970              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7971       (void)BaseTy;
7972       if (!HandleLValueMember(this->Info, E, Result, FD))
7973         return false;
7974     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7975       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7976         return false;
7977     } else
7978       return this->Error(E);
7979 
7980     if (MD->getType()->isReferenceType()) {
7981       APValue RefValue;
7982       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7983                                           RefValue))
7984         return false;
7985       return Success(RefValue, E);
7986     }
7987     return true;
7988   }
7989 
7990   bool VisitBinaryOperator(const BinaryOperator *E) {
7991     switch (E->getOpcode()) {
7992     default:
7993       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7994 
7995     case BO_PtrMemD:
7996     case BO_PtrMemI:
7997       return HandleMemberPointerAccess(this->Info, E, Result);
7998     }
7999   }
8000 
8001   bool VisitCastExpr(const CastExpr *E) {
8002     switch (E->getCastKind()) {
8003     default:
8004       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8005 
8006     case CK_DerivedToBase:
8007     case CK_UncheckedDerivedToBase:
8008       if (!this->Visit(E->getSubExpr()))
8009         return false;
8010 
8011       // Now figure out the necessary offset to add to the base LV to get from
8012       // the derived class to the base class.
8013       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8014                                   Result);
8015     }
8016   }
8017 };
8018 }
8019 
8020 //===----------------------------------------------------------------------===//
8021 // LValue Evaluation
8022 //
8023 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8024 // function designators (in C), decl references to void objects (in C), and
8025 // temporaries (if building with -Wno-address-of-temporary).
8026 //
8027 // LValue evaluation produces values comprising a base expression of one of the
8028 // following types:
8029 // - Declarations
8030 //  * VarDecl
8031 //  * FunctionDecl
8032 // - Literals
8033 //  * CompoundLiteralExpr in C (and in global scope in C++)
8034 //  * StringLiteral
8035 //  * PredefinedExpr
8036 //  * ObjCStringLiteralExpr
8037 //  * ObjCEncodeExpr
8038 //  * AddrLabelExpr
8039 //  * BlockExpr
8040 //  * CallExpr for a MakeStringConstant builtin
8041 // - typeid(T) expressions, as TypeInfoLValues
8042 // - Locals and temporaries
8043 //  * MaterializeTemporaryExpr
8044 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8045 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8046 //    from the AST (FIXME).
8047 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8048 //    CallIndex, for a lifetime-extended temporary.
8049 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8050 //    immediate invocation.
8051 // plus an offset in bytes.
8052 //===----------------------------------------------------------------------===//
8053 namespace {
8054 class LValueExprEvaluator
8055   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8056 public:
8057   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8058     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8059 
8060   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8061   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8062 
8063   bool VisitDeclRefExpr(const DeclRefExpr *E);
8064   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8065   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8066   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8067   bool VisitMemberExpr(const MemberExpr *E);
8068   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8069   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8070   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8071   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8072   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8073   bool VisitUnaryDeref(const UnaryOperator *E);
8074   bool VisitUnaryReal(const UnaryOperator *E);
8075   bool VisitUnaryImag(const UnaryOperator *E);
8076   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8077     return VisitUnaryPreIncDec(UO);
8078   }
8079   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8080     return VisitUnaryPreIncDec(UO);
8081   }
8082   bool VisitBinAssign(const BinaryOperator *BO);
8083   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8084 
8085   bool VisitCastExpr(const CastExpr *E) {
8086     switch (E->getCastKind()) {
8087     default:
8088       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8089 
8090     case CK_LValueBitCast:
8091       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8092       if (!Visit(E->getSubExpr()))
8093         return false;
8094       Result.Designator.setInvalid();
8095       return true;
8096 
8097     case CK_BaseToDerived:
8098       if (!Visit(E->getSubExpr()))
8099         return false;
8100       return HandleBaseToDerivedCast(Info, E, Result);
8101 
8102     case CK_Dynamic:
8103       if (!Visit(E->getSubExpr()))
8104         return false;
8105       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8106     }
8107   }
8108 };
8109 } // end anonymous namespace
8110 
8111 /// Evaluate an expression as an lvalue. This can be legitimately called on
8112 /// expressions which are not glvalues, in three cases:
8113 ///  * function designators in C, and
8114 ///  * "extern void" objects
8115 ///  * @selector() expressions in Objective-C
8116 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8117                            bool InvalidBaseOK) {
8118   assert(!E->isValueDependent());
8119   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8120          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8121   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8122 }
8123 
8124 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8125   const NamedDecl *D = E->getDecl();
8126   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8127     return Success(cast<ValueDecl>(D));
8128   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8129     return VisitVarDecl(E, VD);
8130   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8131     return Visit(BD->getBinding());
8132   return Error(E);
8133 }
8134 
8135 
8136 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8137 
8138   // If we are within a lambda's call operator, check whether the 'VD' referred
8139   // to within 'E' actually represents a lambda-capture that maps to a
8140   // data-member/field within the closure object, and if so, evaluate to the
8141   // field or what the field refers to.
8142   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8143       isa<DeclRefExpr>(E) &&
8144       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8145     // We don't always have a complete capture-map when checking or inferring if
8146     // the function call operator meets the requirements of a constexpr function
8147     // - but we don't need to evaluate the captures to determine constexprness
8148     // (dcl.constexpr C++17).
8149     if (Info.checkingPotentialConstantExpression())
8150       return false;
8151 
8152     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8153       // Start with 'Result' referring to the complete closure object...
8154       Result = *Info.CurrentCall->This;
8155       // ... then update it to refer to the field of the closure object
8156       // that represents the capture.
8157       if (!HandleLValueMember(Info, E, Result, FD))
8158         return false;
8159       // And if the field is of reference type, update 'Result' to refer to what
8160       // the field refers to.
8161       if (FD->getType()->isReferenceType()) {
8162         APValue RVal;
8163         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8164                                             RVal))
8165           return false;
8166         Result.setFrom(Info.Ctx, RVal);
8167       }
8168       return true;
8169     }
8170   }
8171 
8172   CallStackFrame *Frame = nullptr;
8173   unsigned Version = 0;
8174   if (VD->hasLocalStorage()) {
8175     // Only if a local variable was declared in the function currently being
8176     // evaluated, do we expect to be able to find its value in the current
8177     // frame. (Otherwise it was likely declared in an enclosing context and
8178     // could either have a valid evaluatable value (for e.g. a constexpr
8179     // variable) or be ill-formed (and trigger an appropriate evaluation
8180     // diagnostic)).
8181     CallStackFrame *CurrFrame = Info.CurrentCall;
8182     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8183       // Function parameters are stored in some caller's frame. (Usually the
8184       // immediate caller, but for an inherited constructor they may be more
8185       // distant.)
8186       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8187         if (CurrFrame->Arguments) {
8188           VD = CurrFrame->Arguments.getOrigParam(PVD);
8189           Frame =
8190               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8191           Version = CurrFrame->Arguments.Version;
8192         }
8193       } else {
8194         Frame = CurrFrame;
8195         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8196       }
8197     }
8198   }
8199 
8200   if (!VD->getType()->isReferenceType()) {
8201     if (Frame) {
8202       Result.set({VD, Frame->Index, Version});
8203       return true;
8204     }
8205     return Success(VD);
8206   }
8207 
8208   if (!Info.getLangOpts().CPlusPlus11) {
8209     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8210         << VD << VD->getType();
8211     Info.Note(VD->getLocation(), diag::note_declared_at);
8212   }
8213 
8214   APValue *V;
8215   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8216     return false;
8217   if (!V->hasValue()) {
8218     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8219     // adjust the diagnostic to say that.
8220     if (!Info.checkingPotentialConstantExpression())
8221       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8222     return false;
8223   }
8224   return Success(*V, E);
8225 }
8226 
8227 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8228     const MaterializeTemporaryExpr *E) {
8229   // Walk through the expression to find the materialized temporary itself.
8230   SmallVector<const Expr *, 2> CommaLHSs;
8231   SmallVector<SubobjectAdjustment, 2> Adjustments;
8232   const Expr *Inner =
8233       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8234 
8235   // If we passed any comma operators, evaluate their LHSs.
8236   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8237     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8238       return false;
8239 
8240   // A materialized temporary with static storage duration can appear within the
8241   // result of a constant expression evaluation, so we need to preserve its
8242   // value for use outside this evaluation.
8243   APValue *Value;
8244   if (E->getStorageDuration() == SD_Static) {
8245     // FIXME: What about SD_Thread?
8246     Value = E->getOrCreateValue(true);
8247     *Value = APValue();
8248     Result.set(E);
8249   } else {
8250     Value = &Info.CurrentCall->createTemporary(
8251         E, E->getType(),
8252         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8253                                                      : ScopeKind::Block,
8254         Result);
8255   }
8256 
8257   QualType Type = Inner->getType();
8258 
8259   // Materialize the temporary itself.
8260   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8261     *Value = APValue();
8262     return false;
8263   }
8264 
8265   // Adjust our lvalue to refer to the desired subobject.
8266   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8267     --I;
8268     switch (Adjustments[I].Kind) {
8269     case SubobjectAdjustment::DerivedToBaseAdjustment:
8270       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8271                                 Type, Result))
8272         return false;
8273       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8274       break;
8275 
8276     case SubobjectAdjustment::FieldAdjustment:
8277       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8278         return false;
8279       Type = Adjustments[I].Field->getType();
8280       break;
8281 
8282     case SubobjectAdjustment::MemberPointerAdjustment:
8283       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8284                                      Adjustments[I].Ptr.RHS))
8285         return false;
8286       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8287       break;
8288     }
8289   }
8290 
8291   return true;
8292 }
8293 
8294 bool
8295 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8296   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8297          "lvalue compound literal in c++?");
8298   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8299   // only see this when folding in C, so there's no standard to follow here.
8300   return Success(E);
8301 }
8302 
8303 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8304   TypeInfoLValue TypeInfo;
8305 
8306   if (!E->isPotentiallyEvaluated()) {
8307     if (E->isTypeOperand())
8308       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8309     else
8310       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8311   } else {
8312     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8313       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8314         << E->getExprOperand()->getType()
8315         << E->getExprOperand()->getSourceRange();
8316     }
8317 
8318     if (!Visit(E->getExprOperand()))
8319       return false;
8320 
8321     Optional<DynamicType> DynType =
8322         ComputeDynamicType(Info, E, Result, AK_TypeId);
8323     if (!DynType)
8324       return false;
8325 
8326     TypeInfo =
8327         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8328   }
8329 
8330   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8331 }
8332 
8333 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8334   return Success(E->getGuidDecl());
8335 }
8336 
8337 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8338   // Handle static data members.
8339   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8340     VisitIgnoredBaseExpression(E->getBase());
8341     return VisitVarDecl(E, VD);
8342   }
8343 
8344   // Handle static member functions.
8345   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8346     if (MD->isStatic()) {
8347       VisitIgnoredBaseExpression(E->getBase());
8348       return Success(MD);
8349     }
8350   }
8351 
8352   // Handle non-static data members.
8353   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8354 }
8355 
8356 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8357   // FIXME: Deal with vectors as array subscript bases.
8358   if (E->getBase()->getType()->isVectorType())
8359     return Error(E);
8360 
8361   APSInt Index;
8362   bool Success = true;
8363 
8364   // C++17's rules require us to evaluate the LHS first, regardless of which
8365   // side is the base.
8366   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8367     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8368                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8369       if (!Info.noteFailure())
8370         return false;
8371       Success = false;
8372     }
8373   }
8374 
8375   return Success &&
8376          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8377 }
8378 
8379 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8380   return evaluatePointer(E->getSubExpr(), Result);
8381 }
8382 
8383 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8384   if (!Visit(E->getSubExpr()))
8385     return false;
8386   // __real is a no-op on scalar lvalues.
8387   if (E->getSubExpr()->getType()->isAnyComplexType())
8388     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8389   return true;
8390 }
8391 
8392 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8393   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8394          "lvalue __imag__ on scalar?");
8395   if (!Visit(E->getSubExpr()))
8396     return false;
8397   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8398   return true;
8399 }
8400 
8401 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8402   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8403     return Error(UO);
8404 
8405   if (!this->Visit(UO->getSubExpr()))
8406     return false;
8407 
8408   return handleIncDec(
8409       this->Info, UO, Result, UO->getSubExpr()->getType(),
8410       UO->isIncrementOp(), nullptr);
8411 }
8412 
8413 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8414     const CompoundAssignOperator *CAO) {
8415   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8416     return Error(CAO);
8417 
8418   bool Success = true;
8419 
8420   // C++17 onwards require that we evaluate the RHS first.
8421   APValue RHS;
8422   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8423     if (!Info.noteFailure())
8424       return false;
8425     Success = false;
8426   }
8427 
8428   // The overall lvalue result is the result of evaluating the LHS.
8429   if (!this->Visit(CAO->getLHS()) || !Success)
8430     return false;
8431 
8432   return handleCompoundAssignment(
8433       this->Info, CAO,
8434       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8435       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8436 }
8437 
8438 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8439   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8440     return Error(E);
8441 
8442   bool Success = true;
8443 
8444   // C++17 onwards require that we evaluate the RHS first.
8445   APValue NewVal;
8446   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8447     if (!Info.noteFailure())
8448       return false;
8449     Success = false;
8450   }
8451 
8452   if (!this->Visit(E->getLHS()) || !Success)
8453     return false;
8454 
8455   if (Info.getLangOpts().CPlusPlus20 &&
8456       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8457     return false;
8458 
8459   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8460                           NewVal);
8461 }
8462 
8463 //===----------------------------------------------------------------------===//
8464 // Pointer Evaluation
8465 //===----------------------------------------------------------------------===//
8466 
8467 /// Attempts to compute the number of bytes available at the pointer
8468 /// returned by a function with the alloc_size attribute. Returns true if we
8469 /// were successful. Places an unsigned number into `Result`.
8470 ///
8471 /// This expects the given CallExpr to be a call to a function with an
8472 /// alloc_size attribute.
8473 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8474                                             const CallExpr *Call,
8475                                             llvm::APInt &Result) {
8476   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8477 
8478   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8479   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8480   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8481   if (Call->getNumArgs() <= SizeArgNo)
8482     return false;
8483 
8484   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8485     Expr::EvalResult ExprResult;
8486     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8487       return false;
8488     Into = ExprResult.Val.getInt();
8489     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8490       return false;
8491     Into = Into.zextOrSelf(BitsInSizeT);
8492     return true;
8493   };
8494 
8495   APSInt SizeOfElem;
8496   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8497     return false;
8498 
8499   if (!AllocSize->getNumElemsParam().isValid()) {
8500     Result = std::move(SizeOfElem);
8501     return true;
8502   }
8503 
8504   APSInt NumberOfElems;
8505   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8506   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8507     return false;
8508 
8509   bool Overflow;
8510   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8511   if (Overflow)
8512     return false;
8513 
8514   Result = std::move(BytesAvailable);
8515   return true;
8516 }
8517 
8518 /// Convenience function. LVal's base must be a call to an alloc_size
8519 /// function.
8520 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8521                                             const LValue &LVal,
8522                                             llvm::APInt &Result) {
8523   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8524          "Can't get the size of a non alloc_size function");
8525   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8526   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8527   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8528 }
8529 
8530 /// Attempts to evaluate the given LValueBase as the result of a call to
8531 /// a function with the alloc_size attribute. If it was possible to do so, this
8532 /// function will return true, make Result's Base point to said function call,
8533 /// and mark Result's Base as invalid.
8534 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8535                                       LValue &Result) {
8536   if (Base.isNull())
8537     return false;
8538 
8539   // Because we do no form of static analysis, we only support const variables.
8540   //
8541   // Additionally, we can't support parameters, nor can we support static
8542   // variables (in the latter case, use-before-assign isn't UB; in the former,
8543   // we have no clue what they'll be assigned to).
8544   const auto *VD =
8545       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8546   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8547     return false;
8548 
8549   const Expr *Init = VD->getAnyInitializer();
8550   if (!Init)
8551     return false;
8552 
8553   const Expr *E = Init->IgnoreParens();
8554   if (!tryUnwrapAllocSizeCall(E))
8555     return false;
8556 
8557   // Store E instead of E unwrapped so that the type of the LValue's base is
8558   // what the user wanted.
8559   Result.setInvalid(E);
8560 
8561   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8562   Result.addUnsizedArray(Info, E, Pointee);
8563   return true;
8564 }
8565 
8566 namespace {
8567 class PointerExprEvaluator
8568   : public ExprEvaluatorBase<PointerExprEvaluator> {
8569   LValue &Result;
8570   bool InvalidBaseOK;
8571 
8572   bool Success(const Expr *E) {
8573     Result.set(E);
8574     return true;
8575   }
8576 
8577   bool evaluateLValue(const Expr *E, LValue &Result) {
8578     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8579   }
8580 
8581   bool evaluatePointer(const Expr *E, LValue &Result) {
8582     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8583   }
8584 
8585   bool visitNonBuiltinCallExpr(const CallExpr *E);
8586 public:
8587 
8588   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8589       : ExprEvaluatorBaseTy(info), Result(Result),
8590         InvalidBaseOK(InvalidBaseOK) {}
8591 
8592   bool Success(const APValue &V, const Expr *E) {
8593     Result.setFrom(Info.Ctx, V);
8594     return true;
8595   }
8596   bool ZeroInitialization(const Expr *E) {
8597     Result.setNull(Info.Ctx, E->getType());
8598     return true;
8599   }
8600 
8601   bool VisitBinaryOperator(const BinaryOperator *E);
8602   bool VisitCastExpr(const CastExpr* E);
8603   bool VisitUnaryAddrOf(const UnaryOperator *E);
8604   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8605       { return Success(E); }
8606   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8607     if (E->isExpressibleAsConstantInitializer())
8608       return Success(E);
8609     if (Info.noteFailure())
8610       EvaluateIgnoredValue(Info, E->getSubExpr());
8611     return Error(E);
8612   }
8613   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8614       { return Success(E); }
8615   bool VisitCallExpr(const CallExpr *E);
8616   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8617   bool VisitBlockExpr(const BlockExpr *E) {
8618     if (!E->getBlockDecl()->hasCaptures())
8619       return Success(E);
8620     return Error(E);
8621   }
8622   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8623     // Can't look at 'this' when checking a potential constant expression.
8624     if (Info.checkingPotentialConstantExpression())
8625       return false;
8626     if (!Info.CurrentCall->This) {
8627       if (Info.getLangOpts().CPlusPlus11)
8628         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8629       else
8630         Info.FFDiag(E);
8631       return false;
8632     }
8633     Result = *Info.CurrentCall->This;
8634     // If we are inside a lambda's call operator, the 'this' expression refers
8635     // to the enclosing '*this' object (either by value or reference) which is
8636     // either copied into the closure object's field that represents the '*this'
8637     // or refers to '*this'.
8638     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8639       // Ensure we actually have captured 'this'. (an error will have
8640       // been previously reported if not).
8641       if (!Info.CurrentCall->LambdaThisCaptureField)
8642         return false;
8643 
8644       // Update 'Result' to refer to the data member/field of the closure object
8645       // that represents the '*this' capture.
8646       if (!HandleLValueMember(Info, E, Result,
8647                              Info.CurrentCall->LambdaThisCaptureField))
8648         return false;
8649       // If we captured '*this' by reference, replace the field with its referent.
8650       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8651               ->isPointerType()) {
8652         APValue RVal;
8653         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8654                                             RVal))
8655           return false;
8656 
8657         Result.setFrom(Info.Ctx, RVal);
8658       }
8659     }
8660     return true;
8661   }
8662 
8663   bool VisitCXXNewExpr(const CXXNewExpr *E);
8664 
8665   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8666     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8667     APValue LValResult = E->EvaluateInContext(
8668         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8669     Result.setFrom(Info.Ctx, LValResult);
8670     return true;
8671   }
8672 
8673   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8674     std::string ResultStr = E->ComputeName(Info.Ctx);
8675 
8676     QualType CharTy = Info.Ctx.CharTy.withConst();
8677     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8678                ResultStr.size() + 1);
8679     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8680                                                      ArrayType::Normal, 0);
8681 
8682     StringLiteral *SL =
8683         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8684                               /*Pascal*/ false, ArrayTy, E->getLocation());
8685 
8686     evaluateLValue(SL, Result);
8687     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8688     return true;
8689   }
8690 
8691   // FIXME: Missing: @protocol, @selector
8692 };
8693 } // end anonymous namespace
8694 
8695 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8696                             bool InvalidBaseOK) {
8697   assert(!E->isValueDependent());
8698   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8699   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8700 }
8701 
8702 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8703   if (E->getOpcode() != BO_Add &&
8704       E->getOpcode() != BO_Sub)
8705     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8706 
8707   const Expr *PExp = E->getLHS();
8708   const Expr *IExp = E->getRHS();
8709   if (IExp->getType()->isPointerType())
8710     std::swap(PExp, IExp);
8711 
8712   bool EvalPtrOK = evaluatePointer(PExp, Result);
8713   if (!EvalPtrOK && !Info.noteFailure())
8714     return false;
8715 
8716   llvm::APSInt Offset;
8717   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8718     return false;
8719 
8720   if (E->getOpcode() == BO_Sub)
8721     negateAsSigned(Offset);
8722 
8723   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8724   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8725 }
8726 
8727 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8728   return evaluateLValue(E->getSubExpr(), Result);
8729 }
8730 
8731 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8732   const Expr *SubExpr = E->getSubExpr();
8733 
8734   switch (E->getCastKind()) {
8735   default:
8736     break;
8737   case CK_BitCast:
8738   case CK_CPointerToObjCPointerCast:
8739   case CK_BlockPointerToObjCPointerCast:
8740   case CK_AnyPointerToBlockPointerCast:
8741   case CK_AddressSpaceConversion:
8742     if (!Visit(SubExpr))
8743       return false;
8744     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8745     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8746     // also static_casts, but we disallow them as a resolution to DR1312.
8747     if (!E->getType()->isVoidPointerType()) {
8748       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8749           !Result.IsNullPtr &&
8750           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8751                                           E->getType()->getPointeeType()) &&
8752           Info.getStdAllocatorCaller("allocate")) {
8753         // Inside a call to std::allocator::allocate and friends, we permit
8754         // casting from void* back to cv1 T* for a pointer that points to a
8755         // cv2 T.
8756       } else {
8757         Result.Designator.setInvalid();
8758         if (SubExpr->getType()->isVoidPointerType())
8759           CCEDiag(E, diag::note_constexpr_invalid_cast)
8760             << 3 << SubExpr->getType();
8761         else
8762           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8763       }
8764     }
8765     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8766       ZeroInitialization(E);
8767     return true;
8768 
8769   case CK_DerivedToBase:
8770   case CK_UncheckedDerivedToBase:
8771     if (!evaluatePointer(E->getSubExpr(), Result))
8772       return false;
8773     if (!Result.Base && Result.Offset.isZero())
8774       return true;
8775 
8776     // Now figure out the necessary offset to add to the base LV to get from
8777     // the derived class to the base class.
8778     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8779                                   castAs<PointerType>()->getPointeeType(),
8780                                 Result);
8781 
8782   case CK_BaseToDerived:
8783     if (!Visit(E->getSubExpr()))
8784       return false;
8785     if (!Result.Base && Result.Offset.isZero())
8786       return true;
8787     return HandleBaseToDerivedCast(Info, E, Result);
8788 
8789   case CK_Dynamic:
8790     if (!Visit(E->getSubExpr()))
8791       return false;
8792     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8793 
8794   case CK_NullToPointer:
8795     VisitIgnoredValue(E->getSubExpr());
8796     return ZeroInitialization(E);
8797 
8798   case CK_IntegralToPointer: {
8799     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8800 
8801     APValue Value;
8802     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8803       break;
8804 
8805     if (Value.isInt()) {
8806       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8807       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8808       Result.Base = (Expr*)nullptr;
8809       Result.InvalidBase = false;
8810       Result.Offset = CharUnits::fromQuantity(N);
8811       Result.Designator.setInvalid();
8812       Result.IsNullPtr = false;
8813       return true;
8814     } else {
8815       // Cast is of an lvalue, no need to change value.
8816       Result.setFrom(Info.Ctx, Value);
8817       return true;
8818     }
8819   }
8820 
8821   case CK_ArrayToPointerDecay: {
8822     if (SubExpr->isGLValue()) {
8823       if (!evaluateLValue(SubExpr, Result))
8824         return false;
8825     } else {
8826       APValue &Value = Info.CurrentCall->createTemporary(
8827           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8828       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8829         return false;
8830     }
8831     // The result is a pointer to the first element of the array.
8832     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8833     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8834       Result.addArray(Info, E, CAT);
8835     else
8836       Result.addUnsizedArray(Info, E, AT->getElementType());
8837     return true;
8838   }
8839 
8840   case CK_FunctionToPointerDecay:
8841     return evaluateLValue(SubExpr, Result);
8842 
8843   case CK_LValueToRValue: {
8844     LValue LVal;
8845     if (!evaluateLValue(E->getSubExpr(), LVal))
8846       return false;
8847 
8848     APValue RVal;
8849     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8850     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8851                                         LVal, RVal))
8852       return InvalidBaseOK &&
8853              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8854     return Success(RVal, E);
8855   }
8856   }
8857 
8858   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8859 }
8860 
8861 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8862                                 UnaryExprOrTypeTrait ExprKind) {
8863   // C++ [expr.alignof]p3:
8864   //     When alignof is applied to a reference type, the result is the
8865   //     alignment of the referenced type.
8866   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8867     T = Ref->getPointeeType();
8868 
8869   if (T.getQualifiers().hasUnaligned())
8870     return CharUnits::One();
8871 
8872   const bool AlignOfReturnsPreferred =
8873       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8874 
8875   // __alignof is defined to return the preferred alignment.
8876   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8877   // as well.
8878   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8879     return Info.Ctx.toCharUnitsFromBits(
8880       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8881   // alignof and _Alignof are defined to return the ABI alignment.
8882   else if (ExprKind == UETT_AlignOf)
8883     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8884   else
8885     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8886 }
8887 
8888 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8889                                 UnaryExprOrTypeTrait ExprKind) {
8890   E = E->IgnoreParens();
8891 
8892   // The kinds of expressions that we have special-case logic here for
8893   // should be kept up to date with the special checks for those
8894   // expressions in Sema.
8895 
8896   // alignof decl is always accepted, even if it doesn't make sense: we default
8897   // to 1 in those cases.
8898   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8899     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8900                                  /*RefAsPointee*/true);
8901 
8902   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8903     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8904                                  /*RefAsPointee*/true);
8905 
8906   return GetAlignOfType(Info, E->getType(), ExprKind);
8907 }
8908 
8909 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8910   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8911     return Info.Ctx.getDeclAlign(VD);
8912   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8913     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8914   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8915 }
8916 
8917 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8918 /// __builtin_is_aligned and __builtin_assume_aligned.
8919 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8920                                  EvalInfo &Info, APSInt &Alignment) {
8921   if (!EvaluateInteger(E, Alignment, Info))
8922     return false;
8923   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8924     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8925     return false;
8926   }
8927   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8928   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8929   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8930     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8931         << MaxValue << ForType << Alignment;
8932     return false;
8933   }
8934   // Ensure both alignment and source value have the same bit width so that we
8935   // don't assert when computing the resulting value.
8936   APSInt ExtAlignment =
8937       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8938   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8939          "Alignment should not be changed by ext/trunc");
8940   Alignment = ExtAlignment;
8941   assert(Alignment.getBitWidth() == SrcWidth);
8942   return true;
8943 }
8944 
8945 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8946 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8947   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8948     return true;
8949 
8950   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8951     return false;
8952 
8953   Result.setInvalid(E);
8954   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8955   Result.addUnsizedArray(Info, E, PointeeTy);
8956   return true;
8957 }
8958 
8959 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8960   if (IsStringLiteralCall(E))
8961     return Success(E);
8962 
8963   if (unsigned BuiltinOp = E->getBuiltinCallee())
8964     return VisitBuiltinCallExpr(E, BuiltinOp);
8965 
8966   return visitNonBuiltinCallExpr(E);
8967 }
8968 
8969 // Determine if T is a character type for which we guarantee that
8970 // sizeof(T) == 1.
8971 static bool isOneByteCharacterType(QualType T) {
8972   return T->isCharType() || T->isChar8Type();
8973 }
8974 
8975 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8976                                                 unsigned BuiltinOp) {
8977   switch (BuiltinOp) {
8978   case Builtin::BI__builtin_addressof:
8979     return evaluateLValue(E->getArg(0), Result);
8980   case Builtin::BI__builtin_assume_aligned: {
8981     // We need to be very careful here because: if the pointer does not have the
8982     // asserted alignment, then the behavior is undefined, and undefined
8983     // behavior is non-constant.
8984     if (!evaluatePointer(E->getArg(0), Result))
8985       return false;
8986 
8987     LValue OffsetResult(Result);
8988     APSInt Alignment;
8989     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8990                               Alignment))
8991       return false;
8992     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8993 
8994     if (E->getNumArgs() > 2) {
8995       APSInt Offset;
8996       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8997         return false;
8998 
8999       int64_t AdditionalOffset = -Offset.getZExtValue();
9000       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9001     }
9002 
9003     // If there is a base object, then it must have the correct alignment.
9004     if (OffsetResult.Base) {
9005       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9006 
9007       if (BaseAlignment < Align) {
9008         Result.Designator.setInvalid();
9009         // FIXME: Add support to Diagnostic for long / long long.
9010         CCEDiag(E->getArg(0),
9011                 diag::note_constexpr_baa_insufficient_alignment) << 0
9012           << (unsigned)BaseAlignment.getQuantity()
9013           << (unsigned)Align.getQuantity();
9014         return false;
9015       }
9016     }
9017 
9018     // The offset must also have the correct alignment.
9019     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9020       Result.Designator.setInvalid();
9021 
9022       (OffsetResult.Base
9023            ? CCEDiag(E->getArg(0),
9024                      diag::note_constexpr_baa_insufficient_alignment) << 1
9025            : CCEDiag(E->getArg(0),
9026                      diag::note_constexpr_baa_value_insufficient_alignment))
9027         << (int)OffsetResult.Offset.getQuantity()
9028         << (unsigned)Align.getQuantity();
9029       return false;
9030     }
9031 
9032     return true;
9033   }
9034   case Builtin::BI__builtin_align_up:
9035   case Builtin::BI__builtin_align_down: {
9036     if (!evaluatePointer(E->getArg(0), Result))
9037       return false;
9038     APSInt Alignment;
9039     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9040                               Alignment))
9041       return false;
9042     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9043     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9044     // For align_up/align_down, we can return the same value if the alignment
9045     // is known to be greater or equal to the requested value.
9046     if (PtrAlign.getQuantity() >= Alignment)
9047       return true;
9048 
9049     // The alignment could be greater than the minimum at run-time, so we cannot
9050     // infer much about the resulting pointer value. One case is possible:
9051     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9052     // can infer the correct index if the requested alignment is smaller than
9053     // the base alignment so we can perform the computation on the offset.
9054     if (BaseAlignment.getQuantity() >= Alignment) {
9055       assert(Alignment.getBitWidth() <= 64 &&
9056              "Cannot handle > 64-bit address-space");
9057       uint64_t Alignment64 = Alignment.getZExtValue();
9058       CharUnits NewOffset = CharUnits::fromQuantity(
9059           BuiltinOp == Builtin::BI__builtin_align_down
9060               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9061               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9062       Result.adjustOffset(NewOffset - Result.Offset);
9063       // TODO: diagnose out-of-bounds values/only allow for arrays?
9064       return true;
9065     }
9066     // Otherwise, we cannot constant-evaluate the result.
9067     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9068         << Alignment;
9069     return false;
9070   }
9071   case Builtin::BI__builtin_operator_new:
9072     return HandleOperatorNewCall(Info, E, Result);
9073   case Builtin::BI__builtin_launder:
9074     return evaluatePointer(E->getArg(0), Result);
9075   case Builtin::BIstrchr:
9076   case Builtin::BIwcschr:
9077   case Builtin::BImemchr:
9078   case Builtin::BIwmemchr:
9079     if (Info.getLangOpts().CPlusPlus11)
9080       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9081         << /*isConstexpr*/0 << /*isConstructor*/0
9082         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9083     else
9084       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9085     LLVM_FALLTHROUGH;
9086   case Builtin::BI__builtin_strchr:
9087   case Builtin::BI__builtin_wcschr:
9088   case Builtin::BI__builtin_memchr:
9089   case Builtin::BI__builtin_char_memchr:
9090   case Builtin::BI__builtin_wmemchr: {
9091     if (!Visit(E->getArg(0)))
9092       return false;
9093     APSInt Desired;
9094     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9095       return false;
9096     uint64_t MaxLength = uint64_t(-1);
9097     if (BuiltinOp != Builtin::BIstrchr &&
9098         BuiltinOp != Builtin::BIwcschr &&
9099         BuiltinOp != Builtin::BI__builtin_strchr &&
9100         BuiltinOp != Builtin::BI__builtin_wcschr) {
9101       APSInt N;
9102       if (!EvaluateInteger(E->getArg(2), N, Info))
9103         return false;
9104       MaxLength = N.getExtValue();
9105     }
9106     // We cannot find the value if there are no candidates to match against.
9107     if (MaxLength == 0u)
9108       return ZeroInitialization(E);
9109     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9110         Result.Designator.Invalid)
9111       return false;
9112     QualType CharTy = Result.Designator.getType(Info.Ctx);
9113     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9114                      BuiltinOp == Builtin::BI__builtin_memchr;
9115     assert(IsRawByte ||
9116            Info.Ctx.hasSameUnqualifiedType(
9117                CharTy, E->getArg(0)->getType()->getPointeeType()));
9118     // Pointers to const void may point to objects of incomplete type.
9119     if (IsRawByte && CharTy->isIncompleteType()) {
9120       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9121       return false;
9122     }
9123     // Give up on byte-oriented matching against multibyte elements.
9124     // FIXME: We can compare the bytes in the correct order.
9125     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9126       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9127           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9128           << CharTy;
9129       return false;
9130     }
9131     // Figure out what value we're actually looking for (after converting to
9132     // the corresponding unsigned type if necessary).
9133     uint64_t DesiredVal;
9134     bool StopAtNull = false;
9135     switch (BuiltinOp) {
9136     case Builtin::BIstrchr:
9137     case Builtin::BI__builtin_strchr:
9138       // strchr compares directly to the passed integer, and therefore
9139       // always fails if given an int that is not a char.
9140       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9141                                                   E->getArg(1)->getType(),
9142                                                   Desired),
9143                                Desired))
9144         return ZeroInitialization(E);
9145       StopAtNull = true;
9146       LLVM_FALLTHROUGH;
9147     case Builtin::BImemchr:
9148     case Builtin::BI__builtin_memchr:
9149     case Builtin::BI__builtin_char_memchr:
9150       // memchr compares by converting both sides to unsigned char. That's also
9151       // correct for strchr if we get this far (to cope with plain char being
9152       // unsigned in the strchr case).
9153       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9154       break;
9155 
9156     case Builtin::BIwcschr:
9157     case Builtin::BI__builtin_wcschr:
9158       StopAtNull = true;
9159       LLVM_FALLTHROUGH;
9160     case Builtin::BIwmemchr:
9161     case Builtin::BI__builtin_wmemchr:
9162       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9163       DesiredVal = Desired.getZExtValue();
9164       break;
9165     }
9166 
9167     for (; MaxLength; --MaxLength) {
9168       APValue Char;
9169       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9170           !Char.isInt())
9171         return false;
9172       if (Char.getInt().getZExtValue() == DesiredVal)
9173         return true;
9174       if (StopAtNull && !Char.getInt())
9175         break;
9176       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9177         return false;
9178     }
9179     // Not found: return nullptr.
9180     return ZeroInitialization(E);
9181   }
9182 
9183   case Builtin::BImemcpy:
9184   case Builtin::BImemmove:
9185   case Builtin::BIwmemcpy:
9186   case Builtin::BIwmemmove:
9187     if (Info.getLangOpts().CPlusPlus11)
9188       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9189         << /*isConstexpr*/0 << /*isConstructor*/0
9190         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9191     else
9192       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9193     LLVM_FALLTHROUGH;
9194   case Builtin::BI__builtin_memcpy:
9195   case Builtin::BI__builtin_memmove:
9196   case Builtin::BI__builtin_wmemcpy:
9197   case Builtin::BI__builtin_wmemmove: {
9198     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9199                  BuiltinOp == Builtin::BIwmemmove ||
9200                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9201                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9202     bool Move = BuiltinOp == Builtin::BImemmove ||
9203                 BuiltinOp == Builtin::BIwmemmove ||
9204                 BuiltinOp == Builtin::BI__builtin_memmove ||
9205                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9206 
9207     // The result of mem* is the first argument.
9208     if (!Visit(E->getArg(0)))
9209       return false;
9210     LValue Dest = Result;
9211 
9212     LValue Src;
9213     if (!EvaluatePointer(E->getArg(1), Src, Info))
9214       return false;
9215 
9216     APSInt N;
9217     if (!EvaluateInteger(E->getArg(2), N, Info))
9218       return false;
9219     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9220 
9221     // If the size is zero, we treat this as always being a valid no-op.
9222     // (Even if one of the src and dest pointers is null.)
9223     if (!N)
9224       return true;
9225 
9226     // Otherwise, if either of the operands is null, we can't proceed. Don't
9227     // try to determine the type of the copied objects, because there aren't
9228     // any.
9229     if (!Src.Base || !Dest.Base) {
9230       APValue Val;
9231       (!Src.Base ? Src : Dest).moveInto(Val);
9232       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9233           << Move << WChar << !!Src.Base
9234           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9235       return false;
9236     }
9237     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9238       return false;
9239 
9240     // We require that Src and Dest are both pointers to arrays of
9241     // trivially-copyable type. (For the wide version, the designator will be
9242     // invalid if the designated object is not a wchar_t.)
9243     QualType T = Dest.Designator.getType(Info.Ctx);
9244     QualType SrcT = Src.Designator.getType(Info.Ctx);
9245     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9246       // FIXME: Consider using our bit_cast implementation to support this.
9247       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9248       return false;
9249     }
9250     if (T->isIncompleteType()) {
9251       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9252       return false;
9253     }
9254     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9255       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9256       return false;
9257     }
9258 
9259     // Figure out how many T's we're copying.
9260     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9261     if (!WChar) {
9262       uint64_t Remainder;
9263       llvm::APInt OrigN = N;
9264       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9265       if (Remainder) {
9266         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9267             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9268             << (unsigned)TSize;
9269         return false;
9270       }
9271     }
9272 
9273     // Check that the copying will remain within the arrays, just so that we
9274     // can give a more meaningful diagnostic. This implicitly also checks that
9275     // N fits into 64 bits.
9276     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9277     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9278     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9279       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9280           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9281           << toString(N, 10, /*Signed*/false);
9282       return false;
9283     }
9284     uint64_t NElems = N.getZExtValue();
9285     uint64_t NBytes = NElems * TSize;
9286 
9287     // Check for overlap.
9288     int Direction = 1;
9289     if (HasSameBase(Src, Dest)) {
9290       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9291       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9292       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9293         // Dest is inside the source region.
9294         if (!Move) {
9295           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9296           return false;
9297         }
9298         // For memmove and friends, copy backwards.
9299         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9300             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9301           return false;
9302         Direction = -1;
9303       } else if (!Move && SrcOffset >= DestOffset &&
9304                  SrcOffset - DestOffset < NBytes) {
9305         // Src is inside the destination region for memcpy: invalid.
9306         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9307         return false;
9308       }
9309     }
9310 
9311     while (true) {
9312       APValue Val;
9313       // FIXME: Set WantObjectRepresentation to true if we're copying a
9314       // char-like type?
9315       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9316           !handleAssignment(Info, E, Dest, T, Val))
9317         return false;
9318       // Do not iterate past the last element; if we're copying backwards, that
9319       // might take us off the start of the array.
9320       if (--NElems == 0)
9321         return true;
9322       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9323           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9324         return false;
9325     }
9326   }
9327 
9328   default:
9329     break;
9330   }
9331 
9332   return visitNonBuiltinCallExpr(E);
9333 }
9334 
9335 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9336                                      APValue &Result, const InitListExpr *ILE,
9337                                      QualType AllocType);
9338 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9339                                           APValue &Result,
9340                                           const CXXConstructExpr *CCE,
9341                                           QualType AllocType);
9342 
9343 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9344   if (!Info.getLangOpts().CPlusPlus20)
9345     Info.CCEDiag(E, diag::note_constexpr_new);
9346 
9347   // We cannot speculatively evaluate a delete expression.
9348   if (Info.SpeculativeEvaluationDepth)
9349     return false;
9350 
9351   FunctionDecl *OperatorNew = E->getOperatorNew();
9352 
9353   bool IsNothrow = false;
9354   bool IsPlacement = false;
9355   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9356       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9357     // FIXME Support array placement new.
9358     assert(E->getNumPlacementArgs() == 1);
9359     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9360       return false;
9361     if (Result.Designator.Invalid)
9362       return false;
9363     IsPlacement = true;
9364   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9365     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9366         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9367     return false;
9368   } else if (E->getNumPlacementArgs()) {
9369     // The only new-placement list we support is of the form (std::nothrow).
9370     //
9371     // FIXME: There is no restriction on this, but it's not clear that any
9372     // other form makes any sense. We get here for cases such as:
9373     //
9374     //   new (std::align_val_t{N}) X(int)
9375     //
9376     // (which should presumably be valid only if N is a multiple of
9377     // alignof(int), and in any case can't be deallocated unless N is
9378     // alignof(X) and X has new-extended alignment).
9379     if (E->getNumPlacementArgs() != 1 ||
9380         !E->getPlacementArg(0)->getType()->isNothrowT())
9381       return Error(E, diag::note_constexpr_new_placement);
9382 
9383     LValue Nothrow;
9384     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9385       return false;
9386     IsNothrow = true;
9387   }
9388 
9389   const Expr *Init = E->getInitializer();
9390   const InitListExpr *ResizedArrayILE = nullptr;
9391   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9392   bool ValueInit = false;
9393 
9394   QualType AllocType = E->getAllocatedType();
9395   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9396     const Expr *Stripped = *ArraySize;
9397     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9398          Stripped = ICE->getSubExpr())
9399       if (ICE->getCastKind() != CK_NoOp &&
9400           ICE->getCastKind() != CK_IntegralCast)
9401         break;
9402 
9403     llvm::APSInt ArrayBound;
9404     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9405       return false;
9406 
9407     // C++ [expr.new]p9:
9408     //   The expression is erroneous if:
9409     //   -- [...] its value before converting to size_t [or] applying the
9410     //      second standard conversion sequence is less than zero
9411     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9412       if (IsNothrow)
9413         return ZeroInitialization(E);
9414 
9415       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9416           << ArrayBound << (*ArraySize)->getSourceRange();
9417       return false;
9418     }
9419 
9420     //   -- its value is such that the size of the allocated object would
9421     //      exceed the implementation-defined limit
9422     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9423                                                 ArrayBound) >
9424         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9425       if (IsNothrow)
9426         return ZeroInitialization(E);
9427 
9428       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9429         << ArrayBound << (*ArraySize)->getSourceRange();
9430       return false;
9431     }
9432 
9433     //   -- the new-initializer is a braced-init-list and the number of
9434     //      array elements for which initializers are provided [...]
9435     //      exceeds the number of elements to initialize
9436     if (!Init) {
9437       // No initialization is performed.
9438     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9439                isa<ImplicitValueInitExpr>(Init)) {
9440       ValueInit = true;
9441     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9442       ResizedArrayCCE = CCE;
9443     } else {
9444       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9445       assert(CAT && "unexpected type for array initializer");
9446 
9447       unsigned Bits =
9448           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9449       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9450       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9451       if (InitBound.ugt(AllocBound)) {
9452         if (IsNothrow)
9453           return ZeroInitialization(E);
9454 
9455         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9456             << toString(AllocBound, 10, /*Signed=*/false)
9457             << toString(InitBound, 10, /*Signed=*/false)
9458             << (*ArraySize)->getSourceRange();
9459         return false;
9460       }
9461 
9462       // If the sizes differ, we must have an initializer list, and we need
9463       // special handling for this case when we initialize.
9464       if (InitBound != AllocBound)
9465         ResizedArrayILE = cast<InitListExpr>(Init);
9466     }
9467 
9468     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9469                                               ArrayType::Normal, 0);
9470   } else {
9471     assert(!AllocType->isArrayType() &&
9472            "array allocation with non-array new");
9473   }
9474 
9475   APValue *Val;
9476   if (IsPlacement) {
9477     AccessKinds AK = AK_Construct;
9478     struct FindObjectHandler {
9479       EvalInfo &Info;
9480       const Expr *E;
9481       QualType AllocType;
9482       const AccessKinds AccessKind;
9483       APValue *Value;
9484 
9485       typedef bool result_type;
9486       bool failed() { return false; }
9487       bool found(APValue &Subobj, QualType SubobjType) {
9488         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9489         // old name of the object to be used to name the new object.
9490         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9491           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9492             SubobjType << AllocType;
9493           return false;
9494         }
9495         Value = &Subobj;
9496         return true;
9497       }
9498       bool found(APSInt &Value, QualType SubobjType) {
9499         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9500         return false;
9501       }
9502       bool found(APFloat &Value, QualType SubobjType) {
9503         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9504         return false;
9505       }
9506     } Handler = {Info, E, AllocType, AK, nullptr};
9507 
9508     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9509     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9510       return false;
9511 
9512     Val = Handler.Value;
9513 
9514     // [basic.life]p1:
9515     //   The lifetime of an object o of type T ends when [...] the storage
9516     //   which the object occupies is [...] reused by an object that is not
9517     //   nested within o (6.6.2).
9518     *Val = APValue();
9519   } else {
9520     // Perform the allocation and obtain a pointer to the resulting object.
9521     Val = Info.createHeapAlloc(E, AllocType, Result);
9522     if (!Val)
9523       return false;
9524   }
9525 
9526   if (ValueInit) {
9527     ImplicitValueInitExpr VIE(AllocType);
9528     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9529       return false;
9530   } else if (ResizedArrayILE) {
9531     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9532                                   AllocType))
9533       return false;
9534   } else if (ResizedArrayCCE) {
9535     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9536                                        AllocType))
9537       return false;
9538   } else if (Init) {
9539     if (!EvaluateInPlace(*Val, Info, Result, Init))
9540       return false;
9541   } else if (!getDefaultInitValue(AllocType, *Val)) {
9542     return false;
9543   }
9544 
9545   // Array new returns a pointer to the first element, not a pointer to the
9546   // array.
9547   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9548     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9549 
9550   return true;
9551 }
9552 //===----------------------------------------------------------------------===//
9553 // Member Pointer Evaluation
9554 //===----------------------------------------------------------------------===//
9555 
9556 namespace {
9557 class MemberPointerExprEvaluator
9558   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9559   MemberPtr &Result;
9560 
9561   bool Success(const ValueDecl *D) {
9562     Result = MemberPtr(D);
9563     return true;
9564   }
9565 public:
9566 
9567   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9568     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9569 
9570   bool Success(const APValue &V, const Expr *E) {
9571     Result.setFrom(V);
9572     return true;
9573   }
9574   bool ZeroInitialization(const Expr *E) {
9575     return Success((const ValueDecl*)nullptr);
9576   }
9577 
9578   bool VisitCastExpr(const CastExpr *E);
9579   bool VisitUnaryAddrOf(const UnaryOperator *E);
9580 };
9581 } // end anonymous namespace
9582 
9583 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9584                                   EvalInfo &Info) {
9585   assert(!E->isValueDependent());
9586   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9587   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9588 }
9589 
9590 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9591   switch (E->getCastKind()) {
9592   default:
9593     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9594 
9595   case CK_NullToMemberPointer:
9596     VisitIgnoredValue(E->getSubExpr());
9597     return ZeroInitialization(E);
9598 
9599   case CK_BaseToDerivedMemberPointer: {
9600     if (!Visit(E->getSubExpr()))
9601       return false;
9602     if (E->path_empty())
9603       return true;
9604     // Base-to-derived member pointer casts store the path in derived-to-base
9605     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9606     // the wrong end of the derived->base arc, so stagger the path by one class.
9607     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9608     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9609          PathI != PathE; ++PathI) {
9610       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9611       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9612       if (!Result.castToDerived(Derived))
9613         return Error(E);
9614     }
9615     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9616     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9617       return Error(E);
9618     return true;
9619   }
9620 
9621   case CK_DerivedToBaseMemberPointer:
9622     if (!Visit(E->getSubExpr()))
9623       return false;
9624     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9625          PathE = E->path_end(); PathI != PathE; ++PathI) {
9626       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9627       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9628       if (!Result.castToBase(Base))
9629         return Error(E);
9630     }
9631     return true;
9632   }
9633 }
9634 
9635 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9636   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9637   // member can be formed.
9638   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9639 }
9640 
9641 //===----------------------------------------------------------------------===//
9642 // Record Evaluation
9643 //===----------------------------------------------------------------------===//
9644 
9645 namespace {
9646   class RecordExprEvaluator
9647   : public ExprEvaluatorBase<RecordExprEvaluator> {
9648     const LValue &This;
9649     APValue &Result;
9650   public:
9651 
9652     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9653       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9654 
9655     bool Success(const APValue &V, const Expr *E) {
9656       Result = V;
9657       return true;
9658     }
9659     bool ZeroInitialization(const Expr *E) {
9660       return ZeroInitialization(E, E->getType());
9661     }
9662     bool ZeroInitialization(const Expr *E, QualType T);
9663 
9664     bool VisitCallExpr(const CallExpr *E) {
9665       return handleCallExpr(E, Result, &This);
9666     }
9667     bool VisitCastExpr(const CastExpr *E);
9668     bool VisitInitListExpr(const InitListExpr *E);
9669     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9670       return VisitCXXConstructExpr(E, E->getType());
9671     }
9672     bool VisitLambdaExpr(const LambdaExpr *E);
9673     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9674     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9675     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9676     bool VisitBinCmp(const BinaryOperator *E);
9677   };
9678 }
9679 
9680 /// Perform zero-initialization on an object of non-union class type.
9681 /// C++11 [dcl.init]p5:
9682 ///  To zero-initialize an object or reference of type T means:
9683 ///    [...]
9684 ///    -- if T is a (possibly cv-qualified) non-union class type,
9685 ///       each non-static data member and each base-class subobject is
9686 ///       zero-initialized
9687 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9688                                           const RecordDecl *RD,
9689                                           const LValue &This, APValue &Result) {
9690   assert(!RD->isUnion() && "Expected non-union class type");
9691   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9692   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9693                    std::distance(RD->field_begin(), RD->field_end()));
9694 
9695   if (RD->isInvalidDecl()) return false;
9696   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9697 
9698   if (CD) {
9699     unsigned Index = 0;
9700     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9701            End = CD->bases_end(); I != End; ++I, ++Index) {
9702       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9703       LValue Subobject = This;
9704       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9705         return false;
9706       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9707                                          Result.getStructBase(Index)))
9708         return false;
9709     }
9710   }
9711 
9712   for (const auto *I : RD->fields()) {
9713     // -- if T is a reference type, no initialization is performed.
9714     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9715       continue;
9716 
9717     LValue Subobject = This;
9718     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9719       return false;
9720 
9721     ImplicitValueInitExpr VIE(I->getType());
9722     if (!EvaluateInPlace(
9723           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9724       return false;
9725   }
9726 
9727   return true;
9728 }
9729 
9730 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9731   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9732   if (RD->isInvalidDecl()) return false;
9733   if (RD->isUnion()) {
9734     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9735     // object's first non-static named data member is zero-initialized
9736     RecordDecl::field_iterator I = RD->field_begin();
9737     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9738       ++I;
9739     if (I == RD->field_end()) {
9740       Result = APValue((const FieldDecl*)nullptr);
9741       return true;
9742     }
9743 
9744     LValue Subobject = This;
9745     if (!HandleLValueMember(Info, E, Subobject, *I))
9746       return false;
9747     Result = APValue(*I);
9748     ImplicitValueInitExpr VIE(I->getType());
9749     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9750   }
9751 
9752   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9753     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9754     return false;
9755   }
9756 
9757   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9758 }
9759 
9760 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9761   switch (E->getCastKind()) {
9762   default:
9763     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9764 
9765   case CK_ConstructorConversion:
9766     return Visit(E->getSubExpr());
9767 
9768   case CK_DerivedToBase:
9769   case CK_UncheckedDerivedToBase: {
9770     APValue DerivedObject;
9771     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9772       return false;
9773     if (!DerivedObject.isStruct())
9774       return Error(E->getSubExpr());
9775 
9776     // Derived-to-base rvalue conversion: just slice off the derived part.
9777     APValue *Value = &DerivedObject;
9778     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9779     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9780          PathE = E->path_end(); PathI != PathE; ++PathI) {
9781       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9782       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9783       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9784       RD = Base;
9785     }
9786     Result = *Value;
9787     return true;
9788   }
9789   }
9790 }
9791 
9792 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9793   if (E->isTransparent())
9794     return Visit(E->getInit(0));
9795 
9796   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9797   if (RD->isInvalidDecl()) return false;
9798   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9799   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9800 
9801   EvalInfo::EvaluatingConstructorRAII EvalObj(
9802       Info,
9803       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9804       CXXRD && CXXRD->getNumBases());
9805 
9806   if (RD->isUnion()) {
9807     const FieldDecl *Field = E->getInitializedFieldInUnion();
9808     Result = APValue(Field);
9809     if (!Field)
9810       return true;
9811 
9812     // If the initializer list for a union does not contain any elements, the
9813     // first element of the union is value-initialized.
9814     // FIXME: The element should be initialized from an initializer list.
9815     //        Is this difference ever observable for initializer lists which
9816     //        we don't build?
9817     ImplicitValueInitExpr VIE(Field->getType());
9818     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9819 
9820     LValue Subobject = This;
9821     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9822       return false;
9823 
9824     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9825     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9826                                   isa<CXXDefaultInitExpr>(InitExpr));
9827 
9828     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9829       if (Field->isBitField())
9830         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9831                                      Field);
9832       return true;
9833     }
9834 
9835     return false;
9836   }
9837 
9838   if (!Result.hasValue())
9839     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9840                      std::distance(RD->field_begin(), RD->field_end()));
9841   unsigned ElementNo = 0;
9842   bool Success = true;
9843 
9844   // Initialize base classes.
9845   if (CXXRD && CXXRD->getNumBases()) {
9846     for (const auto &Base : CXXRD->bases()) {
9847       assert(ElementNo < E->getNumInits() && "missing init for base class");
9848       const Expr *Init = E->getInit(ElementNo);
9849 
9850       LValue Subobject = This;
9851       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9852         return false;
9853 
9854       APValue &FieldVal = Result.getStructBase(ElementNo);
9855       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9856         if (!Info.noteFailure())
9857           return false;
9858         Success = false;
9859       }
9860       ++ElementNo;
9861     }
9862 
9863     EvalObj.finishedConstructingBases();
9864   }
9865 
9866   // Initialize members.
9867   for (const auto *Field : RD->fields()) {
9868     // Anonymous bit-fields are not considered members of the class for
9869     // purposes of aggregate initialization.
9870     if (Field->isUnnamedBitfield())
9871       continue;
9872 
9873     LValue Subobject = This;
9874 
9875     bool HaveInit = ElementNo < E->getNumInits();
9876 
9877     // FIXME: Diagnostics here should point to the end of the initializer
9878     // list, not the start.
9879     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9880                             Subobject, Field, &Layout))
9881       return false;
9882 
9883     // Perform an implicit value-initialization for members beyond the end of
9884     // the initializer list.
9885     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9886     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9887 
9888     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9889     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9890                                   isa<CXXDefaultInitExpr>(Init));
9891 
9892     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9893     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9894         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9895                                                        FieldVal, Field))) {
9896       if (!Info.noteFailure())
9897         return false;
9898       Success = false;
9899     }
9900   }
9901 
9902   EvalObj.finishedConstructingFields();
9903 
9904   return Success;
9905 }
9906 
9907 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9908                                                 QualType T) {
9909   // Note that E's type is not necessarily the type of our class here; we might
9910   // be initializing an array element instead.
9911   const CXXConstructorDecl *FD = E->getConstructor();
9912   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9913 
9914   bool ZeroInit = E->requiresZeroInitialization();
9915   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9916     // If we've already performed zero-initialization, we're already done.
9917     if (Result.hasValue())
9918       return true;
9919 
9920     if (ZeroInit)
9921       return ZeroInitialization(E, T);
9922 
9923     return getDefaultInitValue(T, Result);
9924   }
9925 
9926   const FunctionDecl *Definition = nullptr;
9927   auto Body = FD->getBody(Definition);
9928 
9929   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9930     return false;
9931 
9932   // Avoid materializing a temporary for an elidable copy/move constructor.
9933   if (E->isElidable() && !ZeroInit) {
9934     // FIXME: This only handles the simplest case, where the source object
9935     //        is passed directly as the first argument to the constructor.
9936     //        This should also handle stepping though implicit casts and
9937     //        and conversion sequences which involve two steps, with a
9938     //        conversion operator followed by a converting constructor.
9939     const Expr *SrcObj = E->getArg(0);
9940     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9941     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9942     if (const MaterializeTemporaryExpr *ME =
9943             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9944       return Visit(ME->getSubExpr());
9945   }
9946 
9947   if (ZeroInit && !ZeroInitialization(E, T))
9948     return false;
9949 
9950   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9951   return HandleConstructorCall(E, This, Args,
9952                                cast<CXXConstructorDecl>(Definition), Info,
9953                                Result);
9954 }
9955 
9956 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9957     const CXXInheritedCtorInitExpr *E) {
9958   if (!Info.CurrentCall) {
9959     assert(Info.checkingPotentialConstantExpression());
9960     return false;
9961   }
9962 
9963   const CXXConstructorDecl *FD = E->getConstructor();
9964   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9965     return false;
9966 
9967   const FunctionDecl *Definition = nullptr;
9968   auto Body = FD->getBody(Definition);
9969 
9970   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9971     return false;
9972 
9973   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9974                                cast<CXXConstructorDecl>(Definition), Info,
9975                                Result);
9976 }
9977 
9978 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9979     const CXXStdInitializerListExpr *E) {
9980   const ConstantArrayType *ArrayType =
9981       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9982 
9983   LValue Array;
9984   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9985     return false;
9986 
9987   // Get a pointer to the first element of the array.
9988   Array.addArray(Info, E, ArrayType);
9989 
9990   auto InvalidType = [&] {
9991     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9992       << E->getType();
9993     return false;
9994   };
9995 
9996   // FIXME: Perform the checks on the field types in SemaInit.
9997   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9998   RecordDecl::field_iterator Field = Record->field_begin();
9999   if (Field == Record->field_end())
10000     return InvalidType();
10001 
10002   // Start pointer.
10003   if (!Field->getType()->isPointerType() ||
10004       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10005                             ArrayType->getElementType()))
10006     return InvalidType();
10007 
10008   // FIXME: What if the initializer_list type has base classes, etc?
10009   Result = APValue(APValue::UninitStruct(), 0, 2);
10010   Array.moveInto(Result.getStructField(0));
10011 
10012   if (++Field == Record->field_end())
10013     return InvalidType();
10014 
10015   if (Field->getType()->isPointerType() &&
10016       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10017                            ArrayType->getElementType())) {
10018     // End pointer.
10019     if (!HandleLValueArrayAdjustment(Info, E, Array,
10020                                      ArrayType->getElementType(),
10021                                      ArrayType->getSize().getZExtValue()))
10022       return false;
10023     Array.moveInto(Result.getStructField(1));
10024   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10025     // Length.
10026     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10027   else
10028     return InvalidType();
10029 
10030   if (++Field != Record->field_end())
10031     return InvalidType();
10032 
10033   return true;
10034 }
10035 
10036 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10037   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10038   if (ClosureClass->isInvalidDecl())
10039     return false;
10040 
10041   const size_t NumFields =
10042       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10043 
10044   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10045                                             E->capture_init_end()) &&
10046          "The number of lambda capture initializers should equal the number of "
10047          "fields within the closure type");
10048 
10049   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10050   // Iterate through all the lambda's closure object's fields and initialize
10051   // them.
10052   auto *CaptureInitIt = E->capture_init_begin();
10053   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10054   bool Success = true;
10055   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10056   for (const auto *Field : ClosureClass->fields()) {
10057     assert(CaptureInitIt != E->capture_init_end());
10058     // Get the initializer for this field
10059     Expr *const CurFieldInit = *CaptureInitIt++;
10060 
10061     // If there is no initializer, either this is a VLA or an error has
10062     // occurred.
10063     if (!CurFieldInit)
10064       return Error(E);
10065 
10066     LValue Subobject = This;
10067 
10068     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10069       return false;
10070 
10071     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10072     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10073       if (!Info.keepEvaluatingAfterFailure())
10074         return false;
10075       Success = false;
10076     }
10077     ++CaptureIt;
10078   }
10079   return Success;
10080 }
10081 
10082 static bool EvaluateRecord(const Expr *E, const LValue &This,
10083                            APValue &Result, EvalInfo &Info) {
10084   assert(!E->isValueDependent());
10085   assert(E->isPRValue() && E->getType()->isRecordType() &&
10086          "can't evaluate expression as a record rvalue");
10087   return RecordExprEvaluator(Info, This, Result).Visit(E);
10088 }
10089 
10090 //===----------------------------------------------------------------------===//
10091 // Temporary Evaluation
10092 //
10093 // Temporaries are represented in the AST as rvalues, but generally behave like
10094 // lvalues. The full-object of which the temporary is a subobject is implicitly
10095 // materialized so that a reference can bind to it.
10096 //===----------------------------------------------------------------------===//
10097 namespace {
10098 class TemporaryExprEvaluator
10099   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10100 public:
10101   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10102     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10103 
10104   /// Visit an expression which constructs the value of this temporary.
10105   bool VisitConstructExpr(const Expr *E) {
10106     APValue &Value = Info.CurrentCall->createTemporary(
10107         E, E->getType(), ScopeKind::FullExpression, Result);
10108     return EvaluateInPlace(Value, Info, Result, E);
10109   }
10110 
10111   bool VisitCastExpr(const CastExpr *E) {
10112     switch (E->getCastKind()) {
10113     default:
10114       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10115 
10116     case CK_ConstructorConversion:
10117       return VisitConstructExpr(E->getSubExpr());
10118     }
10119   }
10120   bool VisitInitListExpr(const InitListExpr *E) {
10121     return VisitConstructExpr(E);
10122   }
10123   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10124     return VisitConstructExpr(E);
10125   }
10126   bool VisitCallExpr(const CallExpr *E) {
10127     return VisitConstructExpr(E);
10128   }
10129   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10130     return VisitConstructExpr(E);
10131   }
10132   bool VisitLambdaExpr(const LambdaExpr *E) {
10133     return VisitConstructExpr(E);
10134   }
10135 };
10136 } // end anonymous namespace
10137 
10138 /// Evaluate an expression of record type as a temporary.
10139 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10140   assert(!E->isValueDependent());
10141   assert(E->isPRValue() && E->getType()->isRecordType());
10142   return TemporaryExprEvaluator(Info, Result).Visit(E);
10143 }
10144 
10145 //===----------------------------------------------------------------------===//
10146 // Vector Evaluation
10147 //===----------------------------------------------------------------------===//
10148 
10149 namespace {
10150   class VectorExprEvaluator
10151   : public ExprEvaluatorBase<VectorExprEvaluator> {
10152     APValue &Result;
10153   public:
10154 
10155     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10156       : ExprEvaluatorBaseTy(info), Result(Result) {}
10157 
10158     bool Success(ArrayRef<APValue> V, const Expr *E) {
10159       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10160       // FIXME: remove this APValue copy.
10161       Result = APValue(V.data(), V.size());
10162       return true;
10163     }
10164     bool Success(const APValue &V, const Expr *E) {
10165       assert(V.isVector());
10166       Result = V;
10167       return true;
10168     }
10169     bool ZeroInitialization(const Expr *E);
10170 
10171     bool VisitUnaryReal(const UnaryOperator *E)
10172       { return Visit(E->getSubExpr()); }
10173     bool VisitCastExpr(const CastExpr* E);
10174     bool VisitInitListExpr(const InitListExpr *E);
10175     bool VisitUnaryImag(const UnaryOperator *E);
10176     bool VisitBinaryOperator(const BinaryOperator *E);
10177     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10178     //                 conditional select), shufflevector, ExtVectorElementExpr
10179   };
10180 } // end anonymous namespace
10181 
10182 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10183   assert(E->isPRValue() && E->getType()->isVectorType() &&
10184          "not a vector prvalue");
10185   return VectorExprEvaluator(Info, Result).Visit(E);
10186 }
10187 
10188 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10189   const VectorType *VTy = E->getType()->castAs<VectorType>();
10190   unsigned NElts = VTy->getNumElements();
10191 
10192   const Expr *SE = E->getSubExpr();
10193   QualType SETy = SE->getType();
10194 
10195   switch (E->getCastKind()) {
10196   case CK_VectorSplat: {
10197     APValue Val = APValue();
10198     if (SETy->isIntegerType()) {
10199       APSInt IntResult;
10200       if (!EvaluateInteger(SE, IntResult, Info))
10201         return false;
10202       Val = APValue(std::move(IntResult));
10203     } else if (SETy->isRealFloatingType()) {
10204       APFloat FloatResult(0.0);
10205       if (!EvaluateFloat(SE, FloatResult, Info))
10206         return false;
10207       Val = APValue(std::move(FloatResult));
10208     } else {
10209       return Error(E);
10210     }
10211 
10212     // Splat and create vector APValue.
10213     SmallVector<APValue, 4> Elts(NElts, Val);
10214     return Success(Elts, E);
10215   }
10216   case CK_BitCast: {
10217     // Evaluate the operand into an APInt we can extract from.
10218     llvm::APInt SValInt;
10219     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10220       return false;
10221     // Extract the elements
10222     QualType EltTy = VTy->getElementType();
10223     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10224     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10225     SmallVector<APValue, 4> Elts;
10226     if (EltTy->isRealFloatingType()) {
10227       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10228       unsigned FloatEltSize = EltSize;
10229       if (&Sem == &APFloat::x87DoubleExtended())
10230         FloatEltSize = 80;
10231       for (unsigned i = 0; i < NElts; i++) {
10232         llvm::APInt Elt;
10233         if (BigEndian)
10234           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10235         else
10236           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10237         Elts.push_back(APValue(APFloat(Sem, Elt)));
10238       }
10239     } else if (EltTy->isIntegerType()) {
10240       for (unsigned i = 0; i < NElts; i++) {
10241         llvm::APInt Elt;
10242         if (BigEndian)
10243           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10244         else
10245           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10246         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10247       }
10248     } else {
10249       return Error(E);
10250     }
10251     return Success(Elts, E);
10252   }
10253   default:
10254     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10255   }
10256 }
10257 
10258 bool
10259 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10260   const VectorType *VT = E->getType()->castAs<VectorType>();
10261   unsigned NumInits = E->getNumInits();
10262   unsigned NumElements = VT->getNumElements();
10263 
10264   QualType EltTy = VT->getElementType();
10265   SmallVector<APValue, 4> Elements;
10266 
10267   // The number of initializers can be less than the number of
10268   // vector elements. For OpenCL, this can be due to nested vector
10269   // initialization. For GCC compatibility, missing trailing elements
10270   // should be initialized with zeroes.
10271   unsigned CountInits = 0, CountElts = 0;
10272   while (CountElts < NumElements) {
10273     // Handle nested vector initialization.
10274     if (CountInits < NumInits
10275         && E->getInit(CountInits)->getType()->isVectorType()) {
10276       APValue v;
10277       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10278         return Error(E);
10279       unsigned vlen = v.getVectorLength();
10280       for (unsigned j = 0; j < vlen; j++)
10281         Elements.push_back(v.getVectorElt(j));
10282       CountElts += vlen;
10283     } else if (EltTy->isIntegerType()) {
10284       llvm::APSInt sInt(32);
10285       if (CountInits < NumInits) {
10286         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10287           return false;
10288       } else // trailing integer zero.
10289         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10290       Elements.push_back(APValue(sInt));
10291       CountElts++;
10292     } else {
10293       llvm::APFloat f(0.0);
10294       if (CountInits < NumInits) {
10295         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10296           return false;
10297       } else // trailing float zero.
10298         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10299       Elements.push_back(APValue(f));
10300       CountElts++;
10301     }
10302     CountInits++;
10303   }
10304   return Success(Elements, E);
10305 }
10306 
10307 bool
10308 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10309   const auto *VT = E->getType()->castAs<VectorType>();
10310   QualType EltTy = VT->getElementType();
10311   APValue ZeroElement;
10312   if (EltTy->isIntegerType())
10313     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10314   else
10315     ZeroElement =
10316         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10317 
10318   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10319   return Success(Elements, E);
10320 }
10321 
10322 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10323   VisitIgnoredValue(E->getSubExpr());
10324   return ZeroInitialization(E);
10325 }
10326 
10327 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10328   BinaryOperatorKind Op = E->getOpcode();
10329   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10330          "Operation not supported on vector types");
10331 
10332   if (Op == BO_Comma)
10333     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10334 
10335   Expr *LHS = E->getLHS();
10336   Expr *RHS = E->getRHS();
10337 
10338   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10339          "Must both be vector types");
10340   // Checking JUST the types are the same would be fine, except shifts don't
10341   // need to have their types be the same (since you always shift by an int).
10342   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10343              E->getType()->castAs<VectorType>()->getNumElements() &&
10344          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10345              E->getType()->castAs<VectorType>()->getNumElements() &&
10346          "All operands must be the same size.");
10347 
10348   APValue LHSValue;
10349   APValue RHSValue;
10350   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10351   if (!LHSOK && !Info.noteFailure())
10352     return false;
10353   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10354     return false;
10355 
10356   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10357     return false;
10358 
10359   return Success(LHSValue, E);
10360 }
10361 
10362 //===----------------------------------------------------------------------===//
10363 // Array Evaluation
10364 //===----------------------------------------------------------------------===//
10365 
10366 namespace {
10367   class ArrayExprEvaluator
10368   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10369     const LValue &This;
10370     APValue &Result;
10371   public:
10372 
10373     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10374       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10375 
10376     bool Success(const APValue &V, const Expr *E) {
10377       assert(V.isArray() && "expected array");
10378       Result = V;
10379       return true;
10380     }
10381 
10382     bool ZeroInitialization(const Expr *E) {
10383       const ConstantArrayType *CAT =
10384           Info.Ctx.getAsConstantArrayType(E->getType());
10385       if (!CAT) {
10386         if (E->getType()->isIncompleteArrayType()) {
10387           // We can be asked to zero-initialize a flexible array member; this
10388           // is represented as an ImplicitValueInitExpr of incomplete array
10389           // type. In this case, the array has zero elements.
10390           Result = APValue(APValue::UninitArray(), 0, 0);
10391           return true;
10392         }
10393         // FIXME: We could handle VLAs here.
10394         return Error(E);
10395       }
10396 
10397       Result = APValue(APValue::UninitArray(), 0,
10398                        CAT->getSize().getZExtValue());
10399       if (!Result.hasArrayFiller())
10400         return true;
10401 
10402       // Zero-initialize all elements.
10403       LValue Subobject = This;
10404       Subobject.addArray(Info, E, CAT);
10405       ImplicitValueInitExpr VIE(CAT->getElementType());
10406       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10407     }
10408 
10409     bool VisitCallExpr(const CallExpr *E) {
10410       return handleCallExpr(E, Result, &This);
10411     }
10412     bool VisitInitListExpr(const InitListExpr *E,
10413                            QualType AllocType = QualType());
10414     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10415     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10416     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10417                                const LValue &Subobject,
10418                                APValue *Value, QualType Type);
10419     bool VisitStringLiteral(const StringLiteral *E,
10420                             QualType AllocType = QualType()) {
10421       expandStringLiteral(Info, E, Result, AllocType);
10422       return true;
10423     }
10424   };
10425 } // end anonymous namespace
10426 
10427 static bool EvaluateArray(const Expr *E, const LValue &This,
10428                           APValue &Result, EvalInfo &Info) {
10429   assert(!E->isValueDependent());
10430   assert(E->isPRValue() && E->getType()->isArrayType() &&
10431          "not an array prvalue");
10432   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10433 }
10434 
10435 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10436                                      APValue &Result, const InitListExpr *ILE,
10437                                      QualType AllocType) {
10438   assert(!ILE->isValueDependent());
10439   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10440          "not an array prvalue");
10441   return ArrayExprEvaluator(Info, This, Result)
10442       .VisitInitListExpr(ILE, AllocType);
10443 }
10444 
10445 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10446                                           APValue &Result,
10447                                           const CXXConstructExpr *CCE,
10448                                           QualType AllocType) {
10449   assert(!CCE->isValueDependent());
10450   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10451          "not an array prvalue");
10452   return ArrayExprEvaluator(Info, This, Result)
10453       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10454 }
10455 
10456 // Return true iff the given array filler may depend on the element index.
10457 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10458   // For now, just allow non-class value-initialization and initialization
10459   // lists comprised of them.
10460   if (isa<ImplicitValueInitExpr>(FillerExpr))
10461     return false;
10462   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10463     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10464       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10465         return true;
10466     }
10467     return false;
10468   }
10469   return true;
10470 }
10471 
10472 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10473                                            QualType AllocType) {
10474   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10475       AllocType.isNull() ? E->getType() : AllocType);
10476   if (!CAT)
10477     return Error(E);
10478 
10479   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10480   // an appropriately-typed string literal enclosed in braces.
10481   if (E->isStringLiteralInit()) {
10482     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10483     // FIXME: Support ObjCEncodeExpr here once we support it in
10484     // ArrayExprEvaluator generally.
10485     if (!SL)
10486       return Error(E);
10487     return VisitStringLiteral(SL, AllocType);
10488   }
10489   // Any other transparent list init will need proper handling of the
10490   // AllocType; we can't just recurse to the inner initializer.
10491   assert(!E->isTransparent() &&
10492          "transparent array list initialization is not string literal init?");
10493 
10494   bool Success = true;
10495 
10496   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10497          "zero-initialized array shouldn't have any initialized elts");
10498   APValue Filler;
10499   if (Result.isArray() && Result.hasArrayFiller())
10500     Filler = Result.getArrayFiller();
10501 
10502   unsigned NumEltsToInit = E->getNumInits();
10503   unsigned NumElts = CAT->getSize().getZExtValue();
10504   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10505 
10506   // If the initializer might depend on the array index, run it for each
10507   // array element.
10508   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10509     NumEltsToInit = NumElts;
10510 
10511   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10512                           << NumEltsToInit << ".\n");
10513 
10514   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10515 
10516   // If the array was previously zero-initialized, preserve the
10517   // zero-initialized values.
10518   if (Filler.hasValue()) {
10519     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10520       Result.getArrayInitializedElt(I) = Filler;
10521     if (Result.hasArrayFiller())
10522       Result.getArrayFiller() = Filler;
10523   }
10524 
10525   LValue Subobject = This;
10526   Subobject.addArray(Info, E, CAT);
10527   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10528     const Expr *Init =
10529         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10530     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10531                          Info, Subobject, Init) ||
10532         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10533                                      CAT->getElementType(), 1)) {
10534       if (!Info.noteFailure())
10535         return false;
10536       Success = false;
10537     }
10538   }
10539 
10540   if (!Result.hasArrayFiller())
10541     return Success;
10542 
10543   // If we get here, we have a trivial filler, which we can just evaluate
10544   // once and splat over the rest of the array elements.
10545   assert(FillerExpr && "no array filler for incomplete init list");
10546   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10547                          FillerExpr) && Success;
10548 }
10549 
10550 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10551   LValue CommonLV;
10552   if (E->getCommonExpr() &&
10553       !Evaluate(Info.CurrentCall->createTemporary(
10554                     E->getCommonExpr(),
10555                     getStorageType(Info.Ctx, E->getCommonExpr()),
10556                     ScopeKind::FullExpression, CommonLV),
10557                 Info, E->getCommonExpr()->getSourceExpr()))
10558     return false;
10559 
10560   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10561 
10562   uint64_t Elements = CAT->getSize().getZExtValue();
10563   Result = APValue(APValue::UninitArray(), Elements, Elements);
10564 
10565   LValue Subobject = This;
10566   Subobject.addArray(Info, E, CAT);
10567 
10568   bool Success = true;
10569   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10570     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10571                          Info, Subobject, E->getSubExpr()) ||
10572         !HandleLValueArrayAdjustment(Info, E, Subobject,
10573                                      CAT->getElementType(), 1)) {
10574       if (!Info.noteFailure())
10575         return false;
10576       Success = false;
10577     }
10578   }
10579 
10580   return Success;
10581 }
10582 
10583 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10584   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10585 }
10586 
10587 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10588                                                const LValue &Subobject,
10589                                                APValue *Value,
10590                                                QualType Type) {
10591   bool HadZeroInit = Value->hasValue();
10592 
10593   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10594     unsigned N = CAT->getSize().getZExtValue();
10595 
10596     // Preserve the array filler if we had prior zero-initialization.
10597     APValue Filler =
10598       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10599                                              : APValue();
10600 
10601     *Value = APValue(APValue::UninitArray(), N, N);
10602 
10603     if (HadZeroInit)
10604       for (unsigned I = 0; I != N; ++I)
10605         Value->getArrayInitializedElt(I) = Filler;
10606 
10607     // Initialize the elements.
10608     LValue ArrayElt = Subobject;
10609     ArrayElt.addArray(Info, E, CAT);
10610     for (unsigned I = 0; I != N; ++I)
10611       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10612                                  CAT->getElementType()) ||
10613           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10614                                        CAT->getElementType(), 1))
10615         return false;
10616 
10617     return true;
10618   }
10619 
10620   if (!Type->isRecordType())
10621     return Error(E);
10622 
10623   return RecordExprEvaluator(Info, Subobject, *Value)
10624              .VisitCXXConstructExpr(E, Type);
10625 }
10626 
10627 //===----------------------------------------------------------------------===//
10628 // Integer Evaluation
10629 //
10630 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10631 // types and back in constant folding. Integer values are thus represented
10632 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10633 //===----------------------------------------------------------------------===//
10634 
10635 namespace {
10636 class IntExprEvaluator
10637         : public ExprEvaluatorBase<IntExprEvaluator> {
10638   APValue &Result;
10639 public:
10640   IntExprEvaluator(EvalInfo &info, APValue &result)
10641       : ExprEvaluatorBaseTy(info), Result(result) {}
10642 
10643   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10644     assert(E->getType()->isIntegralOrEnumerationType() &&
10645            "Invalid evaluation result.");
10646     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10647            "Invalid evaluation result.");
10648     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10649            "Invalid evaluation result.");
10650     Result = APValue(SI);
10651     return true;
10652   }
10653   bool Success(const llvm::APSInt &SI, const Expr *E) {
10654     return Success(SI, E, Result);
10655   }
10656 
10657   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10658     assert(E->getType()->isIntegralOrEnumerationType() &&
10659            "Invalid evaluation result.");
10660     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10661            "Invalid evaluation result.");
10662     Result = APValue(APSInt(I));
10663     Result.getInt().setIsUnsigned(
10664                             E->getType()->isUnsignedIntegerOrEnumerationType());
10665     return true;
10666   }
10667   bool Success(const llvm::APInt &I, const Expr *E) {
10668     return Success(I, E, Result);
10669   }
10670 
10671   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10672     assert(E->getType()->isIntegralOrEnumerationType() &&
10673            "Invalid evaluation result.");
10674     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10675     return true;
10676   }
10677   bool Success(uint64_t Value, const Expr *E) {
10678     return Success(Value, E, Result);
10679   }
10680 
10681   bool Success(CharUnits Size, const Expr *E) {
10682     return Success(Size.getQuantity(), E);
10683   }
10684 
10685   bool Success(const APValue &V, const Expr *E) {
10686     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10687       Result = V;
10688       return true;
10689     }
10690     return Success(V.getInt(), E);
10691   }
10692 
10693   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10694 
10695   //===--------------------------------------------------------------------===//
10696   //                            Visitor Methods
10697   //===--------------------------------------------------------------------===//
10698 
10699   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10700     return Success(E->getValue(), E);
10701   }
10702   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10703     return Success(E->getValue(), E);
10704   }
10705 
10706   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10707   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10708     if (CheckReferencedDecl(E, E->getDecl()))
10709       return true;
10710 
10711     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10712   }
10713   bool VisitMemberExpr(const MemberExpr *E) {
10714     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10715       VisitIgnoredBaseExpression(E->getBase());
10716       return true;
10717     }
10718 
10719     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10720   }
10721 
10722   bool VisitCallExpr(const CallExpr *E);
10723   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10724   bool VisitBinaryOperator(const BinaryOperator *E);
10725   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10726   bool VisitUnaryOperator(const UnaryOperator *E);
10727 
10728   bool VisitCastExpr(const CastExpr* E);
10729   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10730 
10731   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10732     return Success(E->getValue(), E);
10733   }
10734 
10735   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10736     return Success(E->getValue(), E);
10737   }
10738 
10739   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10740     if (Info.ArrayInitIndex == uint64_t(-1)) {
10741       // We were asked to evaluate this subexpression independent of the
10742       // enclosing ArrayInitLoopExpr. We can't do that.
10743       Info.FFDiag(E);
10744       return false;
10745     }
10746     return Success(Info.ArrayInitIndex, E);
10747   }
10748 
10749   // Note, GNU defines __null as an integer, not a pointer.
10750   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10751     return ZeroInitialization(E);
10752   }
10753 
10754   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10755     return Success(E->getValue(), E);
10756   }
10757 
10758   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10759     return Success(E->getValue(), E);
10760   }
10761 
10762   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10763     return Success(E->getValue(), E);
10764   }
10765 
10766   bool VisitUnaryReal(const UnaryOperator *E);
10767   bool VisitUnaryImag(const UnaryOperator *E);
10768 
10769   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10770   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10771   bool VisitSourceLocExpr(const SourceLocExpr *E);
10772   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10773   bool VisitRequiresExpr(const RequiresExpr *E);
10774   // FIXME: Missing: array subscript of vector, member of vector
10775 };
10776 
10777 class FixedPointExprEvaluator
10778     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10779   APValue &Result;
10780 
10781  public:
10782   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10783       : ExprEvaluatorBaseTy(info), Result(result) {}
10784 
10785   bool Success(const llvm::APInt &I, const Expr *E) {
10786     return Success(
10787         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10788   }
10789 
10790   bool Success(uint64_t Value, const Expr *E) {
10791     return Success(
10792         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10793   }
10794 
10795   bool Success(const APValue &V, const Expr *E) {
10796     return Success(V.getFixedPoint(), E);
10797   }
10798 
10799   bool Success(const APFixedPoint &V, const Expr *E) {
10800     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10801     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10802            "Invalid evaluation result.");
10803     Result = APValue(V);
10804     return true;
10805   }
10806 
10807   //===--------------------------------------------------------------------===//
10808   //                            Visitor Methods
10809   //===--------------------------------------------------------------------===//
10810 
10811   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10812     return Success(E->getValue(), E);
10813   }
10814 
10815   bool VisitCastExpr(const CastExpr *E);
10816   bool VisitUnaryOperator(const UnaryOperator *E);
10817   bool VisitBinaryOperator(const BinaryOperator *E);
10818 };
10819 } // end anonymous namespace
10820 
10821 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10822 /// produce either the integer value or a pointer.
10823 ///
10824 /// GCC has a heinous extension which folds casts between pointer types and
10825 /// pointer-sized integral types. We support this by allowing the evaluation of
10826 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10827 /// Some simple arithmetic on such values is supported (they are treated much
10828 /// like char*).
10829 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10830                                     EvalInfo &Info) {
10831   assert(!E->isValueDependent());
10832   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10833   return IntExprEvaluator(Info, Result).Visit(E);
10834 }
10835 
10836 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10837   assert(!E->isValueDependent());
10838   APValue Val;
10839   if (!EvaluateIntegerOrLValue(E, Val, Info))
10840     return false;
10841   if (!Val.isInt()) {
10842     // FIXME: It would be better to produce the diagnostic for casting
10843     //        a pointer to an integer.
10844     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10845     return false;
10846   }
10847   Result = Val.getInt();
10848   return true;
10849 }
10850 
10851 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10852   APValue Evaluated = E->EvaluateInContext(
10853       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10854   return Success(Evaluated, E);
10855 }
10856 
10857 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10858                                EvalInfo &Info) {
10859   assert(!E->isValueDependent());
10860   if (E->getType()->isFixedPointType()) {
10861     APValue Val;
10862     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10863       return false;
10864     if (!Val.isFixedPoint())
10865       return false;
10866 
10867     Result = Val.getFixedPoint();
10868     return true;
10869   }
10870   return false;
10871 }
10872 
10873 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10874                                         EvalInfo &Info) {
10875   assert(!E->isValueDependent());
10876   if (E->getType()->isIntegerType()) {
10877     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10878     APSInt Val;
10879     if (!EvaluateInteger(E, Val, Info))
10880       return false;
10881     Result = APFixedPoint(Val, FXSema);
10882     return true;
10883   } else if (E->getType()->isFixedPointType()) {
10884     return EvaluateFixedPoint(E, Result, Info);
10885   }
10886   return false;
10887 }
10888 
10889 /// Check whether the given declaration can be directly converted to an integral
10890 /// rvalue. If not, no diagnostic is produced; there are other things we can
10891 /// try.
10892 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10893   // Enums are integer constant exprs.
10894   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10895     // Check for signedness/width mismatches between E type and ECD value.
10896     bool SameSign = (ECD->getInitVal().isSigned()
10897                      == E->getType()->isSignedIntegerOrEnumerationType());
10898     bool SameWidth = (ECD->getInitVal().getBitWidth()
10899                       == Info.Ctx.getIntWidth(E->getType()));
10900     if (SameSign && SameWidth)
10901       return Success(ECD->getInitVal(), E);
10902     else {
10903       // Get rid of mismatch (otherwise Success assertions will fail)
10904       // by computing a new value matching the type of E.
10905       llvm::APSInt Val = ECD->getInitVal();
10906       if (!SameSign)
10907         Val.setIsSigned(!ECD->getInitVal().isSigned());
10908       if (!SameWidth)
10909         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10910       return Success(Val, E);
10911     }
10912   }
10913   return false;
10914 }
10915 
10916 /// Values returned by __builtin_classify_type, chosen to match the values
10917 /// produced by GCC's builtin.
10918 enum class GCCTypeClass {
10919   None = -1,
10920   Void = 0,
10921   Integer = 1,
10922   // GCC reserves 2 for character types, but instead classifies them as
10923   // integers.
10924   Enum = 3,
10925   Bool = 4,
10926   Pointer = 5,
10927   // GCC reserves 6 for references, but appears to never use it (because
10928   // expressions never have reference type, presumably).
10929   PointerToDataMember = 7,
10930   RealFloat = 8,
10931   Complex = 9,
10932   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10933   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10934   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10935   // uses 12 for that purpose, same as for a class or struct. Maybe it
10936   // internally implements a pointer to member as a struct?  Who knows.
10937   PointerToMemberFunction = 12, // Not a bug, see above.
10938   ClassOrStruct = 12,
10939   Union = 13,
10940   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10941   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10942   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10943   // literals.
10944 };
10945 
10946 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10947 /// as GCC.
10948 static GCCTypeClass
10949 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10950   assert(!T->isDependentType() && "unexpected dependent type");
10951 
10952   QualType CanTy = T.getCanonicalType();
10953   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10954 
10955   switch (CanTy->getTypeClass()) {
10956 #define TYPE(ID, BASE)
10957 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10958 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10959 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10960 #include "clang/AST/TypeNodes.inc"
10961   case Type::Auto:
10962   case Type::DeducedTemplateSpecialization:
10963       llvm_unreachable("unexpected non-canonical or dependent type");
10964 
10965   case Type::Builtin:
10966     switch (BT->getKind()) {
10967 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10968 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10969     case BuiltinType::ID: return GCCTypeClass::Integer;
10970 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10971     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10972 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10973     case BuiltinType::ID: break;
10974 #include "clang/AST/BuiltinTypes.def"
10975     case BuiltinType::Void:
10976       return GCCTypeClass::Void;
10977 
10978     case BuiltinType::Bool:
10979       return GCCTypeClass::Bool;
10980 
10981     case BuiltinType::Char_U:
10982     case BuiltinType::UChar:
10983     case BuiltinType::WChar_U:
10984     case BuiltinType::Char8:
10985     case BuiltinType::Char16:
10986     case BuiltinType::Char32:
10987     case BuiltinType::UShort:
10988     case BuiltinType::UInt:
10989     case BuiltinType::ULong:
10990     case BuiltinType::ULongLong:
10991     case BuiltinType::UInt128:
10992       return GCCTypeClass::Integer;
10993 
10994     case BuiltinType::UShortAccum:
10995     case BuiltinType::UAccum:
10996     case BuiltinType::ULongAccum:
10997     case BuiltinType::UShortFract:
10998     case BuiltinType::UFract:
10999     case BuiltinType::ULongFract:
11000     case BuiltinType::SatUShortAccum:
11001     case BuiltinType::SatUAccum:
11002     case BuiltinType::SatULongAccum:
11003     case BuiltinType::SatUShortFract:
11004     case BuiltinType::SatUFract:
11005     case BuiltinType::SatULongFract:
11006       return GCCTypeClass::None;
11007 
11008     case BuiltinType::NullPtr:
11009 
11010     case BuiltinType::ObjCId:
11011     case BuiltinType::ObjCClass:
11012     case BuiltinType::ObjCSel:
11013 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11014     case BuiltinType::Id:
11015 #include "clang/Basic/OpenCLImageTypes.def"
11016 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11017     case BuiltinType::Id:
11018 #include "clang/Basic/OpenCLExtensionTypes.def"
11019     case BuiltinType::OCLSampler:
11020     case BuiltinType::OCLEvent:
11021     case BuiltinType::OCLClkEvent:
11022     case BuiltinType::OCLQueue:
11023     case BuiltinType::OCLReserveID:
11024 #define SVE_TYPE(Name, Id, SingletonId) \
11025     case BuiltinType::Id:
11026 #include "clang/Basic/AArch64SVEACLETypes.def"
11027 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11028     case BuiltinType::Id:
11029 #include "clang/Basic/PPCTypes.def"
11030 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11031 #include "clang/Basic/RISCVVTypes.def"
11032       return GCCTypeClass::None;
11033 
11034     case BuiltinType::Dependent:
11035       llvm_unreachable("unexpected dependent type");
11036     };
11037     llvm_unreachable("unexpected placeholder type");
11038 
11039   case Type::Enum:
11040     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11041 
11042   case Type::Pointer:
11043   case Type::ConstantArray:
11044   case Type::VariableArray:
11045   case Type::IncompleteArray:
11046   case Type::FunctionNoProto:
11047   case Type::FunctionProto:
11048     return GCCTypeClass::Pointer;
11049 
11050   case Type::MemberPointer:
11051     return CanTy->isMemberDataPointerType()
11052                ? GCCTypeClass::PointerToDataMember
11053                : GCCTypeClass::PointerToMemberFunction;
11054 
11055   case Type::Complex:
11056     return GCCTypeClass::Complex;
11057 
11058   case Type::Record:
11059     return CanTy->isUnionType() ? GCCTypeClass::Union
11060                                 : GCCTypeClass::ClassOrStruct;
11061 
11062   case Type::Atomic:
11063     // GCC classifies _Atomic T the same as T.
11064     return EvaluateBuiltinClassifyType(
11065         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11066 
11067   case Type::BlockPointer:
11068   case Type::Vector:
11069   case Type::ExtVector:
11070   case Type::ConstantMatrix:
11071   case Type::ObjCObject:
11072   case Type::ObjCInterface:
11073   case Type::ObjCObjectPointer:
11074   case Type::Pipe:
11075   case Type::ExtInt:
11076     // GCC classifies vectors as None. We follow its lead and classify all
11077     // other types that don't fit into the regular classification the same way.
11078     return GCCTypeClass::None;
11079 
11080   case Type::LValueReference:
11081   case Type::RValueReference:
11082     llvm_unreachable("invalid type for expression");
11083   }
11084 
11085   llvm_unreachable("unexpected type class");
11086 }
11087 
11088 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11089 /// as GCC.
11090 static GCCTypeClass
11091 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11092   // If no argument was supplied, default to None. This isn't
11093   // ideal, however it is what gcc does.
11094   if (E->getNumArgs() == 0)
11095     return GCCTypeClass::None;
11096 
11097   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11098   // being an ICE, but still folds it to a constant using the type of the first
11099   // argument.
11100   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11101 }
11102 
11103 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11104 /// __builtin_constant_p when applied to the given pointer.
11105 ///
11106 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11107 /// or it points to the first character of a string literal.
11108 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11109   APValue::LValueBase Base = LV.getLValueBase();
11110   if (Base.isNull()) {
11111     // A null base is acceptable.
11112     return true;
11113   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11114     if (!isa<StringLiteral>(E))
11115       return false;
11116     return LV.getLValueOffset().isZero();
11117   } else if (Base.is<TypeInfoLValue>()) {
11118     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11119     // evaluate to true.
11120     return true;
11121   } else {
11122     // Any other base is not constant enough for GCC.
11123     return false;
11124   }
11125 }
11126 
11127 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11128 /// GCC as we can manage.
11129 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11130   // This evaluation is not permitted to have side-effects, so evaluate it in
11131   // a speculative evaluation context.
11132   SpeculativeEvaluationRAII SpeculativeEval(Info);
11133 
11134   // Constant-folding is always enabled for the operand of __builtin_constant_p
11135   // (even when the enclosing evaluation context otherwise requires a strict
11136   // language-specific constant expression).
11137   FoldConstant Fold(Info, true);
11138 
11139   QualType ArgType = Arg->getType();
11140 
11141   // __builtin_constant_p always has one operand. The rules which gcc follows
11142   // are not precisely documented, but are as follows:
11143   //
11144   //  - If the operand is of integral, floating, complex or enumeration type,
11145   //    and can be folded to a known value of that type, it returns 1.
11146   //  - If the operand can be folded to a pointer to the first character
11147   //    of a string literal (or such a pointer cast to an integral type)
11148   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11149   //
11150   // Otherwise, it returns 0.
11151   //
11152   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11153   // its support for this did not work prior to GCC 9 and is not yet well
11154   // understood.
11155   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11156       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11157       ArgType->isNullPtrType()) {
11158     APValue V;
11159     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11160       Fold.keepDiagnostics();
11161       return false;
11162     }
11163 
11164     // For a pointer (possibly cast to integer), there are special rules.
11165     if (V.getKind() == APValue::LValue)
11166       return EvaluateBuiltinConstantPForLValue(V);
11167 
11168     // Otherwise, any constant value is good enough.
11169     return V.hasValue();
11170   }
11171 
11172   // Anything else isn't considered to be sufficiently constant.
11173   return false;
11174 }
11175 
11176 /// Retrieves the "underlying object type" of the given expression,
11177 /// as used by __builtin_object_size.
11178 static QualType getObjectType(APValue::LValueBase B) {
11179   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11180     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11181       return VD->getType();
11182   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11183     if (isa<CompoundLiteralExpr>(E))
11184       return E->getType();
11185   } else if (B.is<TypeInfoLValue>()) {
11186     return B.getTypeInfoType();
11187   } else if (B.is<DynamicAllocLValue>()) {
11188     return B.getDynamicAllocType();
11189   }
11190 
11191   return QualType();
11192 }
11193 
11194 /// A more selective version of E->IgnoreParenCasts for
11195 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11196 /// to change the type of E.
11197 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11198 ///
11199 /// Always returns an RValue with a pointer representation.
11200 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11201   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11202 
11203   auto *NoParens = E->IgnoreParens();
11204   auto *Cast = dyn_cast<CastExpr>(NoParens);
11205   if (Cast == nullptr)
11206     return NoParens;
11207 
11208   // We only conservatively allow a few kinds of casts, because this code is
11209   // inherently a simple solution that seeks to support the common case.
11210   auto CastKind = Cast->getCastKind();
11211   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11212       CastKind != CK_AddressSpaceConversion)
11213     return NoParens;
11214 
11215   auto *SubExpr = Cast->getSubExpr();
11216   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11217     return NoParens;
11218   return ignorePointerCastsAndParens(SubExpr);
11219 }
11220 
11221 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11222 /// record layout. e.g.
11223 ///   struct { struct { int a, b; } fst, snd; } obj;
11224 ///   obj.fst   // no
11225 ///   obj.snd   // yes
11226 ///   obj.fst.a // no
11227 ///   obj.fst.b // no
11228 ///   obj.snd.a // no
11229 ///   obj.snd.b // yes
11230 ///
11231 /// Please note: this function is specialized for how __builtin_object_size
11232 /// views "objects".
11233 ///
11234 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11235 /// correct result, it will always return true.
11236 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11237   assert(!LVal.Designator.Invalid);
11238 
11239   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11240     const RecordDecl *Parent = FD->getParent();
11241     Invalid = Parent->isInvalidDecl();
11242     if (Invalid || Parent->isUnion())
11243       return true;
11244     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11245     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11246   };
11247 
11248   auto &Base = LVal.getLValueBase();
11249   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11250     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11251       bool Invalid;
11252       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11253         return Invalid;
11254     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11255       for (auto *FD : IFD->chain()) {
11256         bool Invalid;
11257         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11258           return Invalid;
11259       }
11260     }
11261   }
11262 
11263   unsigned I = 0;
11264   QualType BaseType = getType(Base);
11265   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11266     // If we don't know the array bound, conservatively assume we're looking at
11267     // the final array element.
11268     ++I;
11269     if (BaseType->isIncompleteArrayType())
11270       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11271     else
11272       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11273   }
11274 
11275   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11276     const auto &Entry = LVal.Designator.Entries[I];
11277     if (BaseType->isArrayType()) {
11278       // Because __builtin_object_size treats arrays as objects, we can ignore
11279       // the index iff this is the last array in the Designator.
11280       if (I + 1 == E)
11281         return true;
11282       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11283       uint64_t Index = Entry.getAsArrayIndex();
11284       if (Index + 1 != CAT->getSize())
11285         return false;
11286       BaseType = CAT->getElementType();
11287     } else if (BaseType->isAnyComplexType()) {
11288       const auto *CT = BaseType->castAs<ComplexType>();
11289       uint64_t Index = Entry.getAsArrayIndex();
11290       if (Index != 1)
11291         return false;
11292       BaseType = CT->getElementType();
11293     } else if (auto *FD = getAsField(Entry)) {
11294       bool Invalid;
11295       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11296         return Invalid;
11297       BaseType = FD->getType();
11298     } else {
11299       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11300       return false;
11301     }
11302   }
11303   return true;
11304 }
11305 
11306 /// Tests to see if the LValue has a user-specified designator (that isn't
11307 /// necessarily valid). Note that this always returns 'true' if the LValue has
11308 /// an unsized array as its first designator entry, because there's currently no
11309 /// way to tell if the user typed *foo or foo[0].
11310 static bool refersToCompleteObject(const LValue &LVal) {
11311   if (LVal.Designator.Invalid)
11312     return false;
11313 
11314   if (!LVal.Designator.Entries.empty())
11315     return LVal.Designator.isMostDerivedAnUnsizedArray();
11316 
11317   if (!LVal.InvalidBase)
11318     return true;
11319 
11320   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11321   // the LValueBase.
11322   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11323   return !E || !isa<MemberExpr>(E);
11324 }
11325 
11326 /// Attempts to detect a user writing into a piece of memory that's impossible
11327 /// to figure out the size of by just using types.
11328 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11329   const SubobjectDesignator &Designator = LVal.Designator;
11330   // Notes:
11331   // - Users can only write off of the end when we have an invalid base. Invalid
11332   //   bases imply we don't know where the memory came from.
11333   // - We used to be a bit more aggressive here; we'd only be conservative if
11334   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11335   //   broke some common standard library extensions (PR30346), but was
11336   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11337   //   with some sort of list. OTOH, it seems that GCC is always
11338   //   conservative with the last element in structs (if it's an array), so our
11339   //   current behavior is more compatible than an explicit list approach would
11340   //   be.
11341   return LVal.InvalidBase &&
11342          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11343          Designator.MostDerivedIsArrayElement &&
11344          isDesignatorAtObjectEnd(Ctx, LVal);
11345 }
11346 
11347 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11348 /// Fails if the conversion would cause loss of precision.
11349 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11350                                             CharUnits &Result) {
11351   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11352   if (Int.ugt(CharUnitsMax))
11353     return false;
11354   Result = CharUnits::fromQuantity(Int.getZExtValue());
11355   return true;
11356 }
11357 
11358 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11359 /// determine how many bytes exist from the beginning of the object to either
11360 /// the end of the current subobject, or the end of the object itself, depending
11361 /// on what the LValue looks like + the value of Type.
11362 ///
11363 /// If this returns false, the value of Result is undefined.
11364 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11365                                unsigned Type, const LValue &LVal,
11366                                CharUnits &EndOffset) {
11367   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11368 
11369   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11370     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11371       return false;
11372     return HandleSizeof(Info, ExprLoc, Ty, Result);
11373   };
11374 
11375   // We want to evaluate the size of the entire object. This is a valid fallback
11376   // for when Type=1 and the designator is invalid, because we're asked for an
11377   // upper-bound.
11378   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11379     // Type=3 wants a lower bound, so we can't fall back to this.
11380     if (Type == 3 && !DetermineForCompleteObject)
11381       return false;
11382 
11383     llvm::APInt APEndOffset;
11384     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11385         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11386       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11387 
11388     if (LVal.InvalidBase)
11389       return false;
11390 
11391     QualType BaseTy = getObjectType(LVal.getLValueBase());
11392     return CheckedHandleSizeof(BaseTy, EndOffset);
11393   }
11394 
11395   // We want to evaluate the size of a subobject.
11396   const SubobjectDesignator &Designator = LVal.Designator;
11397 
11398   // The following is a moderately common idiom in C:
11399   //
11400   // struct Foo { int a; char c[1]; };
11401   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11402   // strcpy(&F->c[0], Bar);
11403   //
11404   // In order to not break too much legacy code, we need to support it.
11405   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11406     // If we can resolve this to an alloc_size call, we can hand that back,
11407     // because we know for certain how many bytes there are to write to.
11408     llvm::APInt APEndOffset;
11409     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11410         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11411       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11412 
11413     // If we cannot determine the size of the initial allocation, then we can't
11414     // given an accurate upper-bound. However, we are still able to give
11415     // conservative lower-bounds for Type=3.
11416     if (Type == 1)
11417       return false;
11418   }
11419 
11420   CharUnits BytesPerElem;
11421   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11422     return false;
11423 
11424   // According to the GCC documentation, we want the size of the subobject
11425   // denoted by the pointer. But that's not quite right -- what we actually
11426   // want is the size of the immediately-enclosing array, if there is one.
11427   int64_t ElemsRemaining;
11428   if (Designator.MostDerivedIsArrayElement &&
11429       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11430     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11431     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11432     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11433   } else {
11434     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11435   }
11436 
11437   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11438   return true;
11439 }
11440 
11441 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11442 /// returns true and stores the result in @p Size.
11443 ///
11444 /// If @p WasError is non-null, this will report whether the failure to evaluate
11445 /// is to be treated as an Error in IntExprEvaluator.
11446 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11447                                          EvalInfo &Info, uint64_t &Size) {
11448   // Determine the denoted object.
11449   LValue LVal;
11450   {
11451     // The operand of __builtin_object_size is never evaluated for side-effects.
11452     // If there are any, but we can determine the pointed-to object anyway, then
11453     // ignore the side-effects.
11454     SpeculativeEvaluationRAII SpeculativeEval(Info);
11455     IgnoreSideEffectsRAII Fold(Info);
11456 
11457     if (E->isGLValue()) {
11458       // It's possible for us to be given GLValues if we're called via
11459       // Expr::tryEvaluateObjectSize.
11460       APValue RVal;
11461       if (!EvaluateAsRValue(Info, E, RVal))
11462         return false;
11463       LVal.setFrom(Info.Ctx, RVal);
11464     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11465                                 /*InvalidBaseOK=*/true))
11466       return false;
11467   }
11468 
11469   // If we point to before the start of the object, there are no accessible
11470   // bytes.
11471   if (LVal.getLValueOffset().isNegative()) {
11472     Size = 0;
11473     return true;
11474   }
11475 
11476   CharUnits EndOffset;
11477   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11478     return false;
11479 
11480   // If we've fallen outside of the end offset, just pretend there's nothing to
11481   // write to/read from.
11482   if (EndOffset <= LVal.getLValueOffset())
11483     Size = 0;
11484   else
11485     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11486   return true;
11487 }
11488 
11489 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11490   if (unsigned BuiltinOp = E->getBuiltinCallee())
11491     return VisitBuiltinCallExpr(E, BuiltinOp);
11492 
11493   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11494 }
11495 
11496 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11497                                      APValue &Val, APSInt &Alignment) {
11498   QualType SrcTy = E->getArg(0)->getType();
11499   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11500     return false;
11501   // Even though we are evaluating integer expressions we could get a pointer
11502   // argument for the __builtin_is_aligned() case.
11503   if (SrcTy->isPointerType()) {
11504     LValue Ptr;
11505     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11506       return false;
11507     Ptr.moveInto(Val);
11508   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11509     Info.FFDiag(E->getArg(0));
11510     return false;
11511   } else {
11512     APSInt SrcInt;
11513     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11514       return false;
11515     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11516            "Bit widths must be the same");
11517     Val = APValue(SrcInt);
11518   }
11519   assert(Val.hasValue());
11520   return true;
11521 }
11522 
11523 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11524                                             unsigned BuiltinOp) {
11525   switch (BuiltinOp) {
11526   default:
11527     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11528 
11529   case Builtin::BI__builtin_dynamic_object_size:
11530   case Builtin::BI__builtin_object_size: {
11531     // The type was checked when we built the expression.
11532     unsigned Type =
11533         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11534     assert(Type <= 3 && "unexpected type");
11535 
11536     uint64_t Size;
11537     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11538       return Success(Size, E);
11539 
11540     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11541       return Success((Type & 2) ? 0 : -1, E);
11542 
11543     // Expression had no side effects, but we couldn't statically determine the
11544     // size of the referenced object.
11545     switch (Info.EvalMode) {
11546     case EvalInfo::EM_ConstantExpression:
11547     case EvalInfo::EM_ConstantFold:
11548     case EvalInfo::EM_IgnoreSideEffects:
11549       // Leave it to IR generation.
11550       return Error(E);
11551     case EvalInfo::EM_ConstantExpressionUnevaluated:
11552       // Reduce it to a constant now.
11553       return Success((Type & 2) ? 0 : -1, E);
11554     }
11555 
11556     llvm_unreachable("unexpected EvalMode");
11557   }
11558 
11559   case Builtin::BI__builtin_os_log_format_buffer_size: {
11560     analyze_os_log::OSLogBufferLayout Layout;
11561     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11562     return Success(Layout.size().getQuantity(), E);
11563   }
11564 
11565   case Builtin::BI__builtin_is_aligned: {
11566     APValue Src;
11567     APSInt Alignment;
11568     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11569       return false;
11570     if (Src.isLValue()) {
11571       // If we evaluated a pointer, check the minimum known alignment.
11572       LValue Ptr;
11573       Ptr.setFrom(Info.Ctx, Src);
11574       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11575       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11576       // We can return true if the known alignment at the computed offset is
11577       // greater than the requested alignment.
11578       assert(PtrAlign.isPowerOfTwo());
11579       assert(Alignment.isPowerOf2());
11580       if (PtrAlign.getQuantity() >= Alignment)
11581         return Success(1, E);
11582       // If the alignment is not known to be sufficient, some cases could still
11583       // be aligned at run time. However, if the requested alignment is less or
11584       // equal to the base alignment and the offset is not aligned, we know that
11585       // the run-time value can never be aligned.
11586       if (BaseAlignment.getQuantity() >= Alignment &&
11587           PtrAlign.getQuantity() < Alignment)
11588         return Success(0, E);
11589       // Otherwise we can't infer whether the value is sufficiently aligned.
11590       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11591       //  in cases where we can't fully evaluate the pointer.
11592       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11593           << Alignment;
11594       return false;
11595     }
11596     assert(Src.isInt());
11597     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11598   }
11599   case Builtin::BI__builtin_align_up: {
11600     APValue Src;
11601     APSInt Alignment;
11602     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11603       return false;
11604     if (!Src.isInt())
11605       return Error(E);
11606     APSInt AlignedVal =
11607         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11608                Src.getInt().isUnsigned());
11609     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11610     return Success(AlignedVal, E);
11611   }
11612   case Builtin::BI__builtin_align_down: {
11613     APValue Src;
11614     APSInt Alignment;
11615     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11616       return false;
11617     if (!Src.isInt())
11618       return Error(E);
11619     APSInt AlignedVal =
11620         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11621     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11622     return Success(AlignedVal, E);
11623   }
11624 
11625   case Builtin::BI__builtin_bitreverse8:
11626   case Builtin::BI__builtin_bitreverse16:
11627   case Builtin::BI__builtin_bitreverse32:
11628   case Builtin::BI__builtin_bitreverse64: {
11629     APSInt Val;
11630     if (!EvaluateInteger(E->getArg(0), Val, Info))
11631       return false;
11632 
11633     return Success(Val.reverseBits(), E);
11634   }
11635 
11636   case Builtin::BI__builtin_bswap16:
11637   case Builtin::BI__builtin_bswap32:
11638   case Builtin::BI__builtin_bswap64: {
11639     APSInt Val;
11640     if (!EvaluateInteger(E->getArg(0), Val, Info))
11641       return false;
11642 
11643     return Success(Val.byteSwap(), E);
11644   }
11645 
11646   case Builtin::BI__builtin_classify_type:
11647     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11648 
11649   case Builtin::BI__builtin_clrsb:
11650   case Builtin::BI__builtin_clrsbl:
11651   case Builtin::BI__builtin_clrsbll: {
11652     APSInt Val;
11653     if (!EvaluateInteger(E->getArg(0), Val, Info))
11654       return false;
11655 
11656     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11657   }
11658 
11659   case Builtin::BI__builtin_clz:
11660   case Builtin::BI__builtin_clzl:
11661   case Builtin::BI__builtin_clzll:
11662   case Builtin::BI__builtin_clzs: {
11663     APSInt Val;
11664     if (!EvaluateInteger(E->getArg(0), Val, Info))
11665       return false;
11666     if (!Val)
11667       return Error(E);
11668 
11669     return Success(Val.countLeadingZeros(), E);
11670   }
11671 
11672   case Builtin::BI__builtin_constant_p: {
11673     const Expr *Arg = E->getArg(0);
11674     if (EvaluateBuiltinConstantP(Info, Arg))
11675       return Success(true, E);
11676     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11677       // Outside a constant context, eagerly evaluate to false in the presence
11678       // of side-effects in order to avoid -Wunsequenced false-positives in
11679       // a branch on __builtin_constant_p(expr).
11680       return Success(false, E);
11681     }
11682     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11683     return false;
11684   }
11685 
11686   case Builtin::BI__builtin_is_constant_evaluated: {
11687     const auto *Callee = Info.CurrentCall->getCallee();
11688     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11689         (Info.CallStackDepth == 1 ||
11690          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11691           Callee->getIdentifier() &&
11692           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11693       // FIXME: Find a better way to avoid duplicated diagnostics.
11694       if (Info.EvalStatus.Diag)
11695         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11696                                                : Info.CurrentCall->CallLoc,
11697                     diag::warn_is_constant_evaluated_always_true_constexpr)
11698             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11699                                          : "std::is_constant_evaluated");
11700     }
11701 
11702     return Success(Info.InConstantContext, E);
11703   }
11704 
11705   case Builtin::BI__builtin_ctz:
11706   case Builtin::BI__builtin_ctzl:
11707   case Builtin::BI__builtin_ctzll:
11708   case Builtin::BI__builtin_ctzs: {
11709     APSInt Val;
11710     if (!EvaluateInteger(E->getArg(0), Val, Info))
11711       return false;
11712     if (!Val)
11713       return Error(E);
11714 
11715     return Success(Val.countTrailingZeros(), E);
11716   }
11717 
11718   case Builtin::BI__builtin_eh_return_data_regno: {
11719     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11720     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11721     return Success(Operand, E);
11722   }
11723 
11724   case Builtin::BI__builtin_expect:
11725   case Builtin::BI__builtin_expect_with_probability:
11726     return Visit(E->getArg(0));
11727 
11728   case Builtin::BI__builtin_ffs:
11729   case Builtin::BI__builtin_ffsl:
11730   case Builtin::BI__builtin_ffsll: {
11731     APSInt Val;
11732     if (!EvaluateInteger(E->getArg(0), Val, Info))
11733       return false;
11734 
11735     unsigned N = Val.countTrailingZeros();
11736     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11737   }
11738 
11739   case Builtin::BI__builtin_fpclassify: {
11740     APFloat Val(0.0);
11741     if (!EvaluateFloat(E->getArg(5), Val, Info))
11742       return false;
11743     unsigned Arg;
11744     switch (Val.getCategory()) {
11745     case APFloat::fcNaN: Arg = 0; break;
11746     case APFloat::fcInfinity: Arg = 1; break;
11747     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11748     case APFloat::fcZero: Arg = 4; break;
11749     }
11750     return Visit(E->getArg(Arg));
11751   }
11752 
11753   case Builtin::BI__builtin_isinf_sign: {
11754     APFloat Val(0.0);
11755     return EvaluateFloat(E->getArg(0), Val, Info) &&
11756            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11757   }
11758 
11759   case Builtin::BI__builtin_isinf: {
11760     APFloat Val(0.0);
11761     return EvaluateFloat(E->getArg(0), Val, Info) &&
11762            Success(Val.isInfinity() ? 1 : 0, E);
11763   }
11764 
11765   case Builtin::BI__builtin_isfinite: {
11766     APFloat Val(0.0);
11767     return EvaluateFloat(E->getArg(0), Val, Info) &&
11768            Success(Val.isFinite() ? 1 : 0, E);
11769   }
11770 
11771   case Builtin::BI__builtin_isnan: {
11772     APFloat Val(0.0);
11773     return EvaluateFloat(E->getArg(0), Val, Info) &&
11774            Success(Val.isNaN() ? 1 : 0, E);
11775   }
11776 
11777   case Builtin::BI__builtin_isnormal: {
11778     APFloat Val(0.0);
11779     return EvaluateFloat(E->getArg(0), Val, Info) &&
11780            Success(Val.isNormal() ? 1 : 0, E);
11781   }
11782 
11783   case Builtin::BI__builtin_parity:
11784   case Builtin::BI__builtin_parityl:
11785   case Builtin::BI__builtin_parityll: {
11786     APSInt Val;
11787     if (!EvaluateInteger(E->getArg(0), Val, Info))
11788       return false;
11789 
11790     return Success(Val.countPopulation() % 2, E);
11791   }
11792 
11793   case Builtin::BI__builtin_popcount:
11794   case Builtin::BI__builtin_popcountl:
11795   case Builtin::BI__builtin_popcountll: {
11796     APSInt Val;
11797     if (!EvaluateInteger(E->getArg(0), Val, Info))
11798       return false;
11799 
11800     return Success(Val.countPopulation(), E);
11801   }
11802 
11803   case Builtin::BI__builtin_rotateleft8:
11804   case Builtin::BI__builtin_rotateleft16:
11805   case Builtin::BI__builtin_rotateleft32:
11806   case Builtin::BI__builtin_rotateleft64:
11807   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11808   case Builtin::BI_rotl16:
11809   case Builtin::BI_rotl:
11810   case Builtin::BI_lrotl:
11811   case Builtin::BI_rotl64: {
11812     APSInt Val, Amt;
11813     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11814         !EvaluateInteger(E->getArg(1), Amt, Info))
11815       return false;
11816 
11817     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11818   }
11819 
11820   case Builtin::BI__builtin_rotateright8:
11821   case Builtin::BI__builtin_rotateright16:
11822   case Builtin::BI__builtin_rotateright32:
11823   case Builtin::BI__builtin_rotateright64:
11824   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11825   case Builtin::BI_rotr16:
11826   case Builtin::BI_rotr:
11827   case Builtin::BI_lrotr:
11828   case Builtin::BI_rotr64: {
11829     APSInt Val, Amt;
11830     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11831         !EvaluateInteger(E->getArg(1), Amt, Info))
11832       return false;
11833 
11834     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11835   }
11836 
11837   case Builtin::BIstrlen:
11838   case Builtin::BIwcslen:
11839     // A call to strlen is not a constant expression.
11840     if (Info.getLangOpts().CPlusPlus11)
11841       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11842         << /*isConstexpr*/0 << /*isConstructor*/0
11843         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11844     else
11845       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11846     LLVM_FALLTHROUGH;
11847   case Builtin::BI__builtin_strlen:
11848   case Builtin::BI__builtin_wcslen: {
11849     // As an extension, we support __builtin_strlen() as a constant expression,
11850     // and support folding strlen() to a constant.
11851     uint64_t StrLen;
11852     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
11853       return Success(StrLen, E);
11854     return false;
11855   }
11856 
11857   case Builtin::BIstrcmp:
11858   case Builtin::BIwcscmp:
11859   case Builtin::BIstrncmp:
11860   case Builtin::BIwcsncmp:
11861   case Builtin::BImemcmp:
11862   case Builtin::BIbcmp:
11863   case Builtin::BIwmemcmp:
11864     // A call to strlen is not a constant expression.
11865     if (Info.getLangOpts().CPlusPlus11)
11866       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11867         << /*isConstexpr*/0 << /*isConstructor*/0
11868         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11869     else
11870       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11871     LLVM_FALLTHROUGH;
11872   case Builtin::BI__builtin_strcmp:
11873   case Builtin::BI__builtin_wcscmp:
11874   case Builtin::BI__builtin_strncmp:
11875   case Builtin::BI__builtin_wcsncmp:
11876   case Builtin::BI__builtin_memcmp:
11877   case Builtin::BI__builtin_bcmp:
11878   case Builtin::BI__builtin_wmemcmp: {
11879     LValue String1, String2;
11880     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11881         !EvaluatePointer(E->getArg(1), String2, Info))
11882       return false;
11883 
11884     uint64_t MaxLength = uint64_t(-1);
11885     if (BuiltinOp != Builtin::BIstrcmp &&
11886         BuiltinOp != Builtin::BIwcscmp &&
11887         BuiltinOp != Builtin::BI__builtin_strcmp &&
11888         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11889       APSInt N;
11890       if (!EvaluateInteger(E->getArg(2), N, Info))
11891         return false;
11892       MaxLength = N.getExtValue();
11893     }
11894 
11895     // Empty substrings compare equal by definition.
11896     if (MaxLength == 0u)
11897       return Success(0, E);
11898 
11899     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11900         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11901         String1.Designator.Invalid || String2.Designator.Invalid)
11902       return false;
11903 
11904     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11905     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11906 
11907     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11908                      BuiltinOp == Builtin::BIbcmp ||
11909                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11910                      BuiltinOp == Builtin::BI__builtin_bcmp;
11911 
11912     assert(IsRawByte ||
11913            (Info.Ctx.hasSameUnqualifiedType(
11914                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11915             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11916 
11917     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11918     // 'char8_t', but no other types.
11919     if (IsRawByte &&
11920         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11921       // FIXME: Consider using our bit_cast implementation to support this.
11922       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11923           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11924           << CharTy1 << CharTy2;
11925       return false;
11926     }
11927 
11928     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11929       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11930              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11931              Char1.isInt() && Char2.isInt();
11932     };
11933     const auto &AdvanceElems = [&] {
11934       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11935              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11936     };
11937 
11938     bool StopAtNull =
11939         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11940          BuiltinOp != Builtin::BIwmemcmp &&
11941          BuiltinOp != Builtin::BI__builtin_memcmp &&
11942          BuiltinOp != Builtin::BI__builtin_bcmp &&
11943          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11944     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11945                   BuiltinOp == Builtin::BIwcsncmp ||
11946                   BuiltinOp == Builtin::BIwmemcmp ||
11947                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11948                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11949                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11950 
11951     for (; MaxLength; --MaxLength) {
11952       APValue Char1, Char2;
11953       if (!ReadCurElems(Char1, Char2))
11954         return false;
11955       if (Char1.getInt().ne(Char2.getInt())) {
11956         if (IsWide) // wmemcmp compares with wchar_t signedness.
11957           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11958         // memcmp always compares unsigned chars.
11959         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11960       }
11961       if (StopAtNull && !Char1.getInt())
11962         return Success(0, E);
11963       assert(!(StopAtNull && !Char2.getInt()));
11964       if (!AdvanceElems())
11965         return false;
11966     }
11967     // We hit the strncmp / memcmp limit.
11968     return Success(0, E);
11969   }
11970 
11971   case Builtin::BI__atomic_always_lock_free:
11972   case Builtin::BI__atomic_is_lock_free:
11973   case Builtin::BI__c11_atomic_is_lock_free: {
11974     APSInt SizeVal;
11975     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11976       return false;
11977 
11978     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11979     // of two less than or equal to the maximum inline atomic width, we know it
11980     // is lock-free.  If the size isn't a power of two, or greater than the
11981     // maximum alignment where we promote atomics, we know it is not lock-free
11982     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11983     // the answer can only be determined at runtime; for example, 16-byte
11984     // atomics have lock-free implementations on some, but not all,
11985     // x86-64 processors.
11986 
11987     // Check power-of-two.
11988     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11989     if (Size.isPowerOfTwo()) {
11990       // Check against inlining width.
11991       unsigned InlineWidthBits =
11992           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11993       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11994         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11995             Size == CharUnits::One() ||
11996             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11997                                                 Expr::NPC_NeverValueDependent))
11998           // OK, we will inline appropriately-aligned operations of this size,
11999           // and _Atomic(T) is appropriately-aligned.
12000           return Success(1, E);
12001 
12002         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12003           castAs<PointerType>()->getPointeeType();
12004         if (!PointeeType->isIncompleteType() &&
12005             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12006           // OK, we will inline operations on this object.
12007           return Success(1, E);
12008         }
12009       }
12010     }
12011 
12012     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12013         Success(0, E) : Error(E);
12014   }
12015   case Builtin::BI__builtin_add_overflow:
12016   case Builtin::BI__builtin_sub_overflow:
12017   case Builtin::BI__builtin_mul_overflow:
12018   case Builtin::BI__builtin_sadd_overflow:
12019   case Builtin::BI__builtin_uadd_overflow:
12020   case Builtin::BI__builtin_uaddl_overflow:
12021   case Builtin::BI__builtin_uaddll_overflow:
12022   case Builtin::BI__builtin_usub_overflow:
12023   case Builtin::BI__builtin_usubl_overflow:
12024   case Builtin::BI__builtin_usubll_overflow:
12025   case Builtin::BI__builtin_umul_overflow:
12026   case Builtin::BI__builtin_umull_overflow:
12027   case Builtin::BI__builtin_umulll_overflow:
12028   case Builtin::BI__builtin_saddl_overflow:
12029   case Builtin::BI__builtin_saddll_overflow:
12030   case Builtin::BI__builtin_ssub_overflow:
12031   case Builtin::BI__builtin_ssubl_overflow:
12032   case Builtin::BI__builtin_ssubll_overflow:
12033   case Builtin::BI__builtin_smul_overflow:
12034   case Builtin::BI__builtin_smull_overflow:
12035   case Builtin::BI__builtin_smulll_overflow: {
12036     LValue ResultLValue;
12037     APSInt LHS, RHS;
12038 
12039     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12040     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12041         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12042         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12043       return false;
12044 
12045     APSInt Result;
12046     bool DidOverflow = false;
12047 
12048     // If the types don't have to match, enlarge all 3 to the largest of them.
12049     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12050         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12051         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12052       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12053                       ResultType->isSignedIntegerOrEnumerationType();
12054       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12055                       ResultType->isSignedIntegerOrEnumerationType();
12056       uint64_t LHSSize = LHS.getBitWidth();
12057       uint64_t RHSSize = RHS.getBitWidth();
12058       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12059       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12060 
12061       // Add an additional bit if the signedness isn't uniformly agreed to. We
12062       // could do this ONLY if there is a signed and an unsigned that both have
12063       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12064       // caught in the shrink-to-result later anyway.
12065       if (IsSigned && !AllSigned)
12066         ++MaxBits;
12067 
12068       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12069       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12070       Result = APSInt(MaxBits, !IsSigned);
12071     }
12072 
12073     // Find largest int.
12074     switch (BuiltinOp) {
12075     default:
12076       llvm_unreachable("Invalid value for BuiltinOp");
12077     case Builtin::BI__builtin_add_overflow:
12078     case Builtin::BI__builtin_sadd_overflow:
12079     case Builtin::BI__builtin_saddl_overflow:
12080     case Builtin::BI__builtin_saddll_overflow:
12081     case Builtin::BI__builtin_uadd_overflow:
12082     case Builtin::BI__builtin_uaddl_overflow:
12083     case Builtin::BI__builtin_uaddll_overflow:
12084       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12085                               : LHS.uadd_ov(RHS, DidOverflow);
12086       break;
12087     case Builtin::BI__builtin_sub_overflow:
12088     case Builtin::BI__builtin_ssub_overflow:
12089     case Builtin::BI__builtin_ssubl_overflow:
12090     case Builtin::BI__builtin_ssubll_overflow:
12091     case Builtin::BI__builtin_usub_overflow:
12092     case Builtin::BI__builtin_usubl_overflow:
12093     case Builtin::BI__builtin_usubll_overflow:
12094       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12095                               : LHS.usub_ov(RHS, DidOverflow);
12096       break;
12097     case Builtin::BI__builtin_mul_overflow:
12098     case Builtin::BI__builtin_smul_overflow:
12099     case Builtin::BI__builtin_smull_overflow:
12100     case Builtin::BI__builtin_smulll_overflow:
12101     case Builtin::BI__builtin_umul_overflow:
12102     case Builtin::BI__builtin_umull_overflow:
12103     case Builtin::BI__builtin_umulll_overflow:
12104       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12105                               : LHS.umul_ov(RHS, DidOverflow);
12106       break;
12107     }
12108 
12109     // In the case where multiple sizes are allowed, truncate and see if
12110     // the values are the same.
12111     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12112         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12113         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12114       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12115       // since it will give us the behavior of a TruncOrSelf in the case where
12116       // its parameter <= its size.  We previously set Result to be at least the
12117       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12118       // will work exactly like TruncOrSelf.
12119       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12120       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12121 
12122       if (!APSInt::isSameValue(Temp, Result))
12123         DidOverflow = true;
12124       Result = Temp;
12125     }
12126 
12127     APValue APV{Result};
12128     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12129       return false;
12130     return Success(DidOverflow, E);
12131   }
12132   }
12133 }
12134 
12135 /// Determine whether this is a pointer past the end of the complete
12136 /// object referred to by the lvalue.
12137 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12138                                             const LValue &LV) {
12139   // A null pointer can be viewed as being "past the end" but we don't
12140   // choose to look at it that way here.
12141   if (!LV.getLValueBase())
12142     return false;
12143 
12144   // If the designator is valid and refers to a subobject, we're not pointing
12145   // past the end.
12146   if (!LV.getLValueDesignator().Invalid &&
12147       !LV.getLValueDesignator().isOnePastTheEnd())
12148     return false;
12149 
12150   // A pointer to an incomplete type might be past-the-end if the type's size is
12151   // zero.  We cannot tell because the type is incomplete.
12152   QualType Ty = getType(LV.getLValueBase());
12153   if (Ty->isIncompleteType())
12154     return true;
12155 
12156   // We're a past-the-end pointer if we point to the byte after the object,
12157   // no matter what our type or path is.
12158   auto Size = Ctx.getTypeSizeInChars(Ty);
12159   return LV.getLValueOffset() == Size;
12160 }
12161 
12162 namespace {
12163 
12164 /// Data recursive integer evaluator of certain binary operators.
12165 ///
12166 /// We use a data recursive algorithm for binary operators so that we are able
12167 /// to handle extreme cases of chained binary operators without causing stack
12168 /// overflow.
12169 class DataRecursiveIntBinOpEvaluator {
12170   struct EvalResult {
12171     APValue Val;
12172     bool Failed;
12173 
12174     EvalResult() : Failed(false) { }
12175 
12176     void swap(EvalResult &RHS) {
12177       Val.swap(RHS.Val);
12178       Failed = RHS.Failed;
12179       RHS.Failed = false;
12180     }
12181   };
12182 
12183   struct Job {
12184     const Expr *E;
12185     EvalResult LHSResult; // meaningful only for binary operator expression.
12186     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12187 
12188     Job() = default;
12189     Job(Job &&) = default;
12190 
12191     void startSpeculativeEval(EvalInfo &Info) {
12192       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12193     }
12194 
12195   private:
12196     SpeculativeEvaluationRAII SpecEvalRAII;
12197   };
12198 
12199   SmallVector<Job, 16> Queue;
12200 
12201   IntExprEvaluator &IntEval;
12202   EvalInfo &Info;
12203   APValue &FinalResult;
12204 
12205 public:
12206   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12207     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12208 
12209   /// True if \param E is a binary operator that we are going to handle
12210   /// data recursively.
12211   /// We handle binary operators that are comma, logical, or that have operands
12212   /// with integral or enumeration type.
12213   static bool shouldEnqueue(const BinaryOperator *E) {
12214     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12215            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12216             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12217             E->getRHS()->getType()->isIntegralOrEnumerationType());
12218   }
12219 
12220   bool Traverse(const BinaryOperator *E) {
12221     enqueue(E);
12222     EvalResult PrevResult;
12223     while (!Queue.empty())
12224       process(PrevResult);
12225 
12226     if (PrevResult.Failed) return false;
12227 
12228     FinalResult.swap(PrevResult.Val);
12229     return true;
12230   }
12231 
12232 private:
12233   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12234     return IntEval.Success(Value, E, Result);
12235   }
12236   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12237     return IntEval.Success(Value, E, Result);
12238   }
12239   bool Error(const Expr *E) {
12240     return IntEval.Error(E);
12241   }
12242   bool Error(const Expr *E, diag::kind D) {
12243     return IntEval.Error(E, D);
12244   }
12245 
12246   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12247     return Info.CCEDiag(E, D);
12248   }
12249 
12250   // Returns true if visiting the RHS is necessary, false otherwise.
12251   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12252                          bool &SuppressRHSDiags);
12253 
12254   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12255                   const BinaryOperator *E, APValue &Result);
12256 
12257   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12258     Result.Failed = !Evaluate(Result.Val, Info, E);
12259     if (Result.Failed)
12260       Result.Val = APValue();
12261   }
12262 
12263   void process(EvalResult &Result);
12264 
12265   void enqueue(const Expr *E) {
12266     E = E->IgnoreParens();
12267     Queue.resize(Queue.size()+1);
12268     Queue.back().E = E;
12269     Queue.back().Kind = Job::AnyExprKind;
12270   }
12271 };
12272 
12273 }
12274 
12275 bool DataRecursiveIntBinOpEvaluator::
12276        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12277                          bool &SuppressRHSDiags) {
12278   if (E->getOpcode() == BO_Comma) {
12279     // Ignore LHS but note if we could not evaluate it.
12280     if (LHSResult.Failed)
12281       return Info.noteSideEffect();
12282     return true;
12283   }
12284 
12285   if (E->isLogicalOp()) {
12286     bool LHSAsBool;
12287     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12288       // We were able to evaluate the LHS, see if we can get away with not
12289       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12290       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12291         Success(LHSAsBool, E, LHSResult.Val);
12292         return false; // Ignore RHS
12293       }
12294     } else {
12295       LHSResult.Failed = true;
12296 
12297       // Since we weren't able to evaluate the left hand side, it
12298       // might have had side effects.
12299       if (!Info.noteSideEffect())
12300         return false;
12301 
12302       // We can't evaluate the LHS; however, sometimes the result
12303       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12304       // Don't ignore RHS and suppress diagnostics from this arm.
12305       SuppressRHSDiags = true;
12306     }
12307 
12308     return true;
12309   }
12310 
12311   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12312          E->getRHS()->getType()->isIntegralOrEnumerationType());
12313 
12314   if (LHSResult.Failed && !Info.noteFailure())
12315     return false; // Ignore RHS;
12316 
12317   return true;
12318 }
12319 
12320 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12321                                     bool IsSub) {
12322   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12323   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12324   // offsets.
12325   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12326   CharUnits &Offset = LVal.getLValueOffset();
12327   uint64_t Offset64 = Offset.getQuantity();
12328   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12329   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12330                                          : Offset64 + Index64);
12331 }
12332 
12333 bool DataRecursiveIntBinOpEvaluator::
12334        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12335                   const BinaryOperator *E, APValue &Result) {
12336   if (E->getOpcode() == BO_Comma) {
12337     if (RHSResult.Failed)
12338       return false;
12339     Result = RHSResult.Val;
12340     return true;
12341   }
12342 
12343   if (E->isLogicalOp()) {
12344     bool lhsResult, rhsResult;
12345     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12346     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12347 
12348     if (LHSIsOK) {
12349       if (RHSIsOK) {
12350         if (E->getOpcode() == BO_LOr)
12351           return Success(lhsResult || rhsResult, E, Result);
12352         else
12353           return Success(lhsResult && rhsResult, E, Result);
12354       }
12355     } else {
12356       if (RHSIsOK) {
12357         // We can't evaluate the LHS; however, sometimes the result
12358         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12359         if (rhsResult == (E->getOpcode() == BO_LOr))
12360           return Success(rhsResult, E, Result);
12361       }
12362     }
12363 
12364     return false;
12365   }
12366 
12367   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12368          E->getRHS()->getType()->isIntegralOrEnumerationType());
12369 
12370   if (LHSResult.Failed || RHSResult.Failed)
12371     return false;
12372 
12373   const APValue &LHSVal = LHSResult.Val;
12374   const APValue &RHSVal = RHSResult.Val;
12375 
12376   // Handle cases like (unsigned long)&a + 4.
12377   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12378     Result = LHSVal;
12379     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12380     return true;
12381   }
12382 
12383   // Handle cases like 4 + (unsigned long)&a
12384   if (E->getOpcode() == BO_Add &&
12385       RHSVal.isLValue() && LHSVal.isInt()) {
12386     Result = RHSVal;
12387     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12388     return true;
12389   }
12390 
12391   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12392     // Handle (intptr_t)&&A - (intptr_t)&&B.
12393     if (!LHSVal.getLValueOffset().isZero() ||
12394         !RHSVal.getLValueOffset().isZero())
12395       return false;
12396     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12397     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12398     if (!LHSExpr || !RHSExpr)
12399       return false;
12400     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12401     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12402     if (!LHSAddrExpr || !RHSAddrExpr)
12403       return false;
12404     // Make sure both labels come from the same function.
12405     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12406         RHSAddrExpr->getLabel()->getDeclContext())
12407       return false;
12408     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12409     return true;
12410   }
12411 
12412   // All the remaining cases expect both operands to be an integer
12413   if (!LHSVal.isInt() || !RHSVal.isInt())
12414     return Error(E);
12415 
12416   // Set up the width and signedness manually, in case it can't be deduced
12417   // from the operation we're performing.
12418   // FIXME: Don't do this in the cases where we can deduce it.
12419   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12420                E->getType()->isUnsignedIntegerOrEnumerationType());
12421   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12422                          RHSVal.getInt(), Value))
12423     return false;
12424   return Success(Value, E, Result);
12425 }
12426 
12427 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12428   Job &job = Queue.back();
12429 
12430   switch (job.Kind) {
12431     case Job::AnyExprKind: {
12432       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12433         if (shouldEnqueue(Bop)) {
12434           job.Kind = Job::BinOpKind;
12435           enqueue(Bop->getLHS());
12436           return;
12437         }
12438       }
12439 
12440       EvaluateExpr(job.E, Result);
12441       Queue.pop_back();
12442       return;
12443     }
12444 
12445     case Job::BinOpKind: {
12446       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12447       bool SuppressRHSDiags = false;
12448       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12449         Queue.pop_back();
12450         return;
12451       }
12452       if (SuppressRHSDiags)
12453         job.startSpeculativeEval(Info);
12454       job.LHSResult.swap(Result);
12455       job.Kind = Job::BinOpVisitedLHSKind;
12456       enqueue(Bop->getRHS());
12457       return;
12458     }
12459 
12460     case Job::BinOpVisitedLHSKind: {
12461       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12462       EvalResult RHS;
12463       RHS.swap(Result);
12464       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12465       Queue.pop_back();
12466       return;
12467     }
12468   }
12469 
12470   llvm_unreachable("Invalid Job::Kind!");
12471 }
12472 
12473 namespace {
12474 enum class CmpResult {
12475   Unequal,
12476   Less,
12477   Equal,
12478   Greater,
12479   Unordered,
12480 };
12481 }
12482 
12483 template <class SuccessCB, class AfterCB>
12484 static bool
12485 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12486                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12487   assert(!E->isValueDependent());
12488   assert(E->isComparisonOp() && "expected comparison operator");
12489   assert((E->getOpcode() == BO_Cmp ||
12490           E->getType()->isIntegralOrEnumerationType()) &&
12491          "unsupported binary expression evaluation");
12492   auto Error = [&](const Expr *E) {
12493     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12494     return false;
12495   };
12496 
12497   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12498   bool IsEquality = E->isEqualityOp();
12499 
12500   QualType LHSTy = E->getLHS()->getType();
12501   QualType RHSTy = E->getRHS()->getType();
12502 
12503   if (LHSTy->isIntegralOrEnumerationType() &&
12504       RHSTy->isIntegralOrEnumerationType()) {
12505     APSInt LHS, RHS;
12506     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12507     if (!LHSOK && !Info.noteFailure())
12508       return false;
12509     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12510       return false;
12511     if (LHS < RHS)
12512       return Success(CmpResult::Less, E);
12513     if (LHS > RHS)
12514       return Success(CmpResult::Greater, E);
12515     return Success(CmpResult::Equal, E);
12516   }
12517 
12518   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12519     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12520     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12521 
12522     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12523     if (!LHSOK && !Info.noteFailure())
12524       return false;
12525     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12526       return false;
12527     if (LHSFX < RHSFX)
12528       return Success(CmpResult::Less, E);
12529     if (LHSFX > RHSFX)
12530       return Success(CmpResult::Greater, E);
12531     return Success(CmpResult::Equal, E);
12532   }
12533 
12534   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12535     ComplexValue LHS, RHS;
12536     bool LHSOK;
12537     if (E->isAssignmentOp()) {
12538       LValue LV;
12539       EvaluateLValue(E->getLHS(), LV, Info);
12540       LHSOK = false;
12541     } else if (LHSTy->isRealFloatingType()) {
12542       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12543       if (LHSOK) {
12544         LHS.makeComplexFloat();
12545         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12546       }
12547     } else {
12548       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12549     }
12550     if (!LHSOK && !Info.noteFailure())
12551       return false;
12552 
12553     if (E->getRHS()->getType()->isRealFloatingType()) {
12554       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12555         return false;
12556       RHS.makeComplexFloat();
12557       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12558     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12559       return false;
12560 
12561     if (LHS.isComplexFloat()) {
12562       APFloat::cmpResult CR_r =
12563         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12564       APFloat::cmpResult CR_i =
12565         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12566       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12567       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12568     } else {
12569       assert(IsEquality && "invalid complex comparison");
12570       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12571                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12572       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12573     }
12574   }
12575 
12576   if (LHSTy->isRealFloatingType() &&
12577       RHSTy->isRealFloatingType()) {
12578     APFloat RHS(0.0), LHS(0.0);
12579 
12580     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12581     if (!LHSOK && !Info.noteFailure())
12582       return false;
12583 
12584     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12585       return false;
12586 
12587     assert(E->isComparisonOp() && "Invalid binary operator!");
12588     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12589     if (!Info.InConstantContext &&
12590         APFloatCmpResult == APFloat::cmpUnordered &&
12591         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12592       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12593       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12594       return false;
12595     }
12596     auto GetCmpRes = [&]() {
12597       switch (APFloatCmpResult) {
12598       case APFloat::cmpEqual:
12599         return CmpResult::Equal;
12600       case APFloat::cmpLessThan:
12601         return CmpResult::Less;
12602       case APFloat::cmpGreaterThan:
12603         return CmpResult::Greater;
12604       case APFloat::cmpUnordered:
12605         return CmpResult::Unordered;
12606       }
12607       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12608     };
12609     return Success(GetCmpRes(), E);
12610   }
12611 
12612   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12613     LValue LHSValue, RHSValue;
12614 
12615     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12616     if (!LHSOK && !Info.noteFailure())
12617       return false;
12618 
12619     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12620       return false;
12621 
12622     // Reject differing bases from the normal codepath; we special-case
12623     // comparisons to null.
12624     if (!HasSameBase(LHSValue, RHSValue)) {
12625       // Inequalities and subtractions between unrelated pointers have
12626       // unspecified or undefined behavior.
12627       if (!IsEquality) {
12628         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12629         return false;
12630       }
12631       // A constant address may compare equal to the address of a symbol.
12632       // The one exception is that address of an object cannot compare equal
12633       // to a null pointer constant.
12634       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12635           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12636         return Error(E);
12637       // It's implementation-defined whether distinct literals will have
12638       // distinct addresses. In clang, the result of such a comparison is
12639       // unspecified, so it is not a constant expression. However, we do know
12640       // that the address of a literal will be non-null.
12641       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12642           LHSValue.Base && RHSValue.Base)
12643         return Error(E);
12644       // We can't tell whether weak symbols will end up pointing to the same
12645       // object.
12646       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12647         return Error(E);
12648       // We can't compare the address of the start of one object with the
12649       // past-the-end address of another object, per C++ DR1652.
12650       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12651            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12652           (RHSValue.Base && RHSValue.Offset.isZero() &&
12653            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12654         return Error(E);
12655       // We can't tell whether an object is at the same address as another
12656       // zero sized object.
12657       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12658           (LHSValue.Base && isZeroSized(RHSValue)))
12659         return Error(E);
12660       return Success(CmpResult::Unequal, E);
12661     }
12662 
12663     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12664     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12665 
12666     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12667     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12668 
12669     // C++11 [expr.rel]p3:
12670     //   Pointers to void (after pointer conversions) can be compared, with a
12671     //   result defined as follows: If both pointers represent the same
12672     //   address or are both the null pointer value, the result is true if the
12673     //   operator is <= or >= and false otherwise; otherwise the result is
12674     //   unspecified.
12675     // We interpret this as applying to pointers to *cv* void.
12676     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12677       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12678 
12679     // C++11 [expr.rel]p2:
12680     // - If two pointers point to non-static data members of the same object,
12681     //   or to subobjects or array elements fo such members, recursively, the
12682     //   pointer to the later declared member compares greater provided the
12683     //   two members have the same access control and provided their class is
12684     //   not a union.
12685     //   [...]
12686     // - Otherwise pointer comparisons are unspecified.
12687     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12688       bool WasArrayIndex;
12689       unsigned Mismatch = FindDesignatorMismatch(
12690           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12691       // At the point where the designators diverge, the comparison has a
12692       // specified value if:
12693       //  - we are comparing array indices
12694       //  - we are comparing fields of a union, or fields with the same access
12695       // Otherwise, the result is unspecified and thus the comparison is not a
12696       // constant expression.
12697       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12698           Mismatch < RHSDesignator.Entries.size()) {
12699         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12700         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12701         if (!LF && !RF)
12702           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12703         else if (!LF)
12704           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12705               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12706               << RF->getParent() << RF;
12707         else if (!RF)
12708           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12709               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12710               << LF->getParent() << LF;
12711         else if (!LF->getParent()->isUnion() &&
12712                  LF->getAccess() != RF->getAccess())
12713           Info.CCEDiag(E,
12714                        diag::note_constexpr_pointer_comparison_differing_access)
12715               << LF << LF->getAccess() << RF << RF->getAccess()
12716               << LF->getParent();
12717       }
12718     }
12719 
12720     // The comparison here must be unsigned, and performed with the same
12721     // width as the pointer.
12722     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12723     uint64_t CompareLHS = LHSOffset.getQuantity();
12724     uint64_t CompareRHS = RHSOffset.getQuantity();
12725     assert(PtrSize <= 64 && "Unexpected pointer width");
12726     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12727     CompareLHS &= Mask;
12728     CompareRHS &= Mask;
12729 
12730     // If there is a base and this is a relational operator, we can only
12731     // compare pointers within the object in question; otherwise, the result
12732     // depends on where the object is located in memory.
12733     if (!LHSValue.Base.isNull() && IsRelational) {
12734       QualType BaseTy = getType(LHSValue.Base);
12735       if (BaseTy->isIncompleteType())
12736         return Error(E);
12737       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12738       uint64_t OffsetLimit = Size.getQuantity();
12739       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12740         return Error(E);
12741     }
12742 
12743     if (CompareLHS < CompareRHS)
12744       return Success(CmpResult::Less, E);
12745     if (CompareLHS > CompareRHS)
12746       return Success(CmpResult::Greater, E);
12747     return Success(CmpResult::Equal, E);
12748   }
12749 
12750   if (LHSTy->isMemberPointerType()) {
12751     assert(IsEquality && "unexpected member pointer operation");
12752     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12753 
12754     MemberPtr LHSValue, RHSValue;
12755 
12756     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12757     if (!LHSOK && !Info.noteFailure())
12758       return false;
12759 
12760     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12761       return false;
12762 
12763     // C++11 [expr.eq]p2:
12764     //   If both operands are null, they compare equal. Otherwise if only one is
12765     //   null, they compare unequal.
12766     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12767       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12768       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12769     }
12770 
12771     //   Otherwise if either is a pointer to a virtual member function, the
12772     //   result is unspecified.
12773     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12774       if (MD->isVirtual())
12775         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12776     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12777       if (MD->isVirtual())
12778         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12779 
12780     //   Otherwise they compare equal if and only if they would refer to the
12781     //   same member of the same most derived object or the same subobject if
12782     //   they were dereferenced with a hypothetical object of the associated
12783     //   class type.
12784     bool Equal = LHSValue == RHSValue;
12785     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12786   }
12787 
12788   if (LHSTy->isNullPtrType()) {
12789     assert(E->isComparisonOp() && "unexpected nullptr operation");
12790     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12791     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12792     // are compared, the result is true of the operator is <=, >= or ==, and
12793     // false otherwise.
12794     return Success(CmpResult::Equal, E);
12795   }
12796 
12797   return DoAfter();
12798 }
12799 
12800 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12801   if (!CheckLiteralType(Info, E))
12802     return false;
12803 
12804   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12805     ComparisonCategoryResult CCR;
12806     switch (CR) {
12807     case CmpResult::Unequal:
12808       llvm_unreachable("should never produce Unequal for three-way comparison");
12809     case CmpResult::Less:
12810       CCR = ComparisonCategoryResult::Less;
12811       break;
12812     case CmpResult::Equal:
12813       CCR = ComparisonCategoryResult::Equal;
12814       break;
12815     case CmpResult::Greater:
12816       CCR = ComparisonCategoryResult::Greater;
12817       break;
12818     case CmpResult::Unordered:
12819       CCR = ComparisonCategoryResult::Unordered;
12820       break;
12821     }
12822     // Evaluation succeeded. Lookup the information for the comparison category
12823     // type and fetch the VarDecl for the result.
12824     const ComparisonCategoryInfo &CmpInfo =
12825         Info.Ctx.CompCategories.getInfoForType(E->getType());
12826     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12827     // Check and evaluate the result as a constant expression.
12828     LValue LV;
12829     LV.set(VD);
12830     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12831       return false;
12832     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12833                                    ConstantExprKind::Normal);
12834   };
12835   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12836     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12837   });
12838 }
12839 
12840 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12841   // We don't support assignment in C. C++ assignments don't get here because
12842   // assignment is an lvalue in C++.
12843   if (E->isAssignmentOp()) {
12844     Error(E);
12845     if (!Info.noteFailure())
12846       return false;
12847   }
12848 
12849   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12850     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12851 
12852   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12853           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12854          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12855 
12856   if (E->isComparisonOp()) {
12857     // Evaluate builtin binary comparisons by evaluating them as three-way
12858     // comparisons and then translating the result.
12859     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12860       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12861              "should only produce Unequal for equality comparisons");
12862       bool IsEqual   = CR == CmpResult::Equal,
12863            IsLess    = CR == CmpResult::Less,
12864            IsGreater = CR == CmpResult::Greater;
12865       auto Op = E->getOpcode();
12866       switch (Op) {
12867       default:
12868         llvm_unreachable("unsupported binary operator");
12869       case BO_EQ:
12870       case BO_NE:
12871         return Success(IsEqual == (Op == BO_EQ), E);
12872       case BO_LT:
12873         return Success(IsLess, E);
12874       case BO_GT:
12875         return Success(IsGreater, E);
12876       case BO_LE:
12877         return Success(IsEqual || IsLess, E);
12878       case BO_GE:
12879         return Success(IsEqual || IsGreater, E);
12880       }
12881     };
12882     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12883       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12884     });
12885   }
12886 
12887   QualType LHSTy = E->getLHS()->getType();
12888   QualType RHSTy = E->getRHS()->getType();
12889 
12890   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12891       E->getOpcode() == BO_Sub) {
12892     LValue LHSValue, RHSValue;
12893 
12894     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12895     if (!LHSOK && !Info.noteFailure())
12896       return false;
12897 
12898     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12899       return false;
12900 
12901     // Reject differing bases from the normal codepath; we special-case
12902     // comparisons to null.
12903     if (!HasSameBase(LHSValue, RHSValue)) {
12904       // Handle &&A - &&B.
12905       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12906         return Error(E);
12907       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12908       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12909       if (!LHSExpr || !RHSExpr)
12910         return Error(E);
12911       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12912       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12913       if (!LHSAddrExpr || !RHSAddrExpr)
12914         return Error(E);
12915       // Make sure both labels come from the same function.
12916       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12917           RHSAddrExpr->getLabel()->getDeclContext())
12918         return Error(E);
12919       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12920     }
12921     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12922     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12923 
12924     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12925     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12926 
12927     // C++11 [expr.add]p6:
12928     //   Unless both pointers point to elements of the same array object, or
12929     //   one past the last element of the array object, the behavior is
12930     //   undefined.
12931     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12932         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12933                                 RHSDesignator))
12934       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12935 
12936     QualType Type = E->getLHS()->getType();
12937     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12938 
12939     CharUnits ElementSize;
12940     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12941       return false;
12942 
12943     // As an extension, a type may have zero size (empty struct or union in
12944     // C, array of zero length). Pointer subtraction in such cases has
12945     // undefined behavior, so is not constant.
12946     if (ElementSize.isZero()) {
12947       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12948           << ElementType;
12949       return false;
12950     }
12951 
12952     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12953     // and produce incorrect results when it overflows. Such behavior
12954     // appears to be non-conforming, but is common, so perhaps we should
12955     // assume the standard intended for such cases to be undefined behavior
12956     // and check for them.
12957 
12958     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12959     // overflow in the final conversion to ptrdiff_t.
12960     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12961     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12962     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12963                     false);
12964     APSInt TrueResult = (LHS - RHS) / ElemSize;
12965     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12966 
12967     if (Result.extend(65) != TrueResult &&
12968         !HandleOverflow(Info, E, TrueResult, E->getType()))
12969       return false;
12970     return Success(Result, E);
12971   }
12972 
12973   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12974 }
12975 
12976 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12977 /// a result as the expression's type.
12978 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12979                                     const UnaryExprOrTypeTraitExpr *E) {
12980   switch(E->getKind()) {
12981   case UETT_PreferredAlignOf:
12982   case UETT_AlignOf: {
12983     if (E->isArgumentType())
12984       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12985                      E);
12986     else
12987       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12988                      E);
12989   }
12990 
12991   case UETT_VecStep: {
12992     QualType Ty = E->getTypeOfArgument();
12993 
12994     if (Ty->isVectorType()) {
12995       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12996 
12997       // The vec_step built-in functions that take a 3-component
12998       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12999       if (n == 3)
13000         n = 4;
13001 
13002       return Success(n, E);
13003     } else
13004       return Success(1, E);
13005   }
13006 
13007   case UETT_SizeOf: {
13008     QualType SrcTy = E->getTypeOfArgument();
13009     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13010     //   the result is the size of the referenced type."
13011     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13012       SrcTy = Ref->getPointeeType();
13013 
13014     CharUnits Sizeof;
13015     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13016       return false;
13017     return Success(Sizeof, E);
13018   }
13019   case UETT_OpenMPRequiredSimdAlign:
13020     assert(E->isArgumentType());
13021     return Success(
13022         Info.Ctx.toCharUnitsFromBits(
13023                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13024             .getQuantity(),
13025         E);
13026   }
13027 
13028   llvm_unreachable("unknown expr/type trait");
13029 }
13030 
13031 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13032   CharUnits Result;
13033   unsigned n = OOE->getNumComponents();
13034   if (n == 0)
13035     return Error(OOE);
13036   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13037   for (unsigned i = 0; i != n; ++i) {
13038     OffsetOfNode ON = OOE->getComponent(i);
13039     switch (ON.getKind()) {
13040     case OffsetOfNode::Array: {
13041       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13042       APSInt IdxResult;
13043       if (!EvaluateInteger(Idx, IdxResult, Info))
13044         return false;
13045       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13046       if (!AT)
13047         return Error(OOE);
13048       CurrentType = AT->getElementType();
13049       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13050       Result += IdxResult.getSExtValue() * ElementSize;
13051       break;
13052     }
13053 
13054     case OffsetOfNode::Field: {
13055       FieldDecl *MemberDecl = ON.getField();
13056       const RecordType *RT = CurrentType->getAs<RecordType>();
13057       if (!RT)
13058         return Error(OOE);
13059       RecordDecl *RD = RT->getDecl();
13060       if (RD->isInvalidDecl()) return false;
13061       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13062       unsigned i = MemberDecl->getFieldIndex();
13063       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13064       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13065       CurrentType = MemberDecl->getType().getNonReferenceType();
13066       break;
13067     }
13068 
13069     case OffsetOfNode::Identifier:
13070       llvm_unreachable("dependent __builtin_offsetof");
13071 
13072     case OffsetOfNode::Base: {
13073       CXXBaseSpecifier *BaseSpec = ON.getBase();
13074       if (BaseSpec->isVirtual())
13075         return Error(OOE);
13076 
13077       // Find the layout of the class whose base we are looking into.
13078       const RecordType *RT = CurrentType->getAs<RecordType>();
13079       if (!RT)
13080         return Error(OOE);
13081       RecordDecl *RD = RT->getDecl();
13082       if (RD->isInvalidDecl()) return false;
13083       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13084 
13085       // Find the base class itself.
13086       CurrentType = BaseSpec->getType();
13087       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13088       if (!BaseRT)
13089         return Error(OOE);
13090 
13091       // Add the offset to the base.
13092       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13093       break;
13094     }
13095     }
13096   }
13097   return Success(Result, OOE);
13098 }
13099 
13100 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13101   switch (E->getOpcode()) {
13102   default:
13103     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13104     // See C99 6.6p3.
13105     return Error(E);
13106   case UO_Extension:
13107     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13108     // If so, we could clear the diagnostic ID.
13109     return Visit(E->getSubExpr());
13110   case UO_Plus:
13111     // The result is just the value.
13112     return Visit(E->getSubExpr());
13113   case UO_Minus: {
13114     if (!Visit(E->getSubExpr()))
13115       return false;
13116     if (!Result.isInt()) return Error(E);
13117     const APSInt &Value = Result.getInt();
13118     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13119         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13120                         E->getType()))
13121       return false;
13122     return Success(-Value, E);
13123   }
13124   case UO_Not: {
13125     if (!Visit(E->getSubExpr()))
13126       return false;
13127     if (!Result.isInt()) return Error(E);
13128     return Success(~Result.getInt(), E);
13129   }
13130   case UO_LNot: {
13131     bool bres;
13132     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13133       return false;
13134     return Success(!bres, E);
13135   }
13136   }
13137 }
13138 
13139 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13140 /// result type is integer.
13141 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13142   const Expr *SubExpr = E->getSubExpr();
13143   QualType DestType = E->getType();
13144   QualType SrcType = SubExpr->getType();
13145 
13146   switch (E->getCastKind()) {
13147   case CK_BaseToDerived:
13148   case CK_DerivedToBase:
13149   case CK_UncheckedDerivedToBase:
13150   case CK_Dynamic:
13151   case CK_ToUnion:
13152   case CK_ArrayToPointerDecay:
13153   case CK_FunctionToPointerDecay:
13154   case CK_NullToPointer:
13155   case CK_NullToMemberPointer:
13156   case CK_BaseToDerivedMemberPointer:
13157   case CK_DerivedToBaseMemberPointer:
13158   case CK_ReinterpretMemberPointer:
13159   case CK_ConstructorConversion:
13160   case CK_IntegralToPointer:
13161   case CK_ToVoid:
13162   case CK_VectorSplat:
13163   case CK_IntegralToFloating:
13164   case CK_FloatingCast:
13165   case CK_CPointerToObjCPointerCast:
13166   case CK_BlockPointerToObjCPointerCast:
13167   case CK_AnyPointerToBlockPointerCast:
13168   case CK_ObjCObjectLValueCast:
13169   case CK_FloatingRealToComplex:
13170   case CK_FloatingComplexToReal:
13171   case CK_FloatingComplexCast:
13172   case CK_FloatingComplexToIntegralComplex:
13173   case CK_IntegralRealToComplex:
13174   case CK_IntegralComplexCast:
13175   case CK_IntegralComplexToFloatingComplex:
13176   case CK_BuiltinFnToFnPtr:
13177   case CK_ZeroToOCLOpaqueType:
13178   case CK_NonAtomicToAtomic:
13179   case CK_AddressSpaceConversion:
13180   case CK_IntToOCLSampler:
13181   case CK_FloatingToFixedPoint:
13182   case CK_FixedPointToFloating:
13183   case CK_FixedPointCast:
13184   case CK_IntegralToFixedPoint:
13185   case CK_MatrixCast:
13186     llvm_unreachable("invalid cast kind for integral value");
13187 
13188   case CK_BitCast:
13189   case CK_Dependent:
13190   case CK_LValueBitCast:
13191   case CK_ARCProduceObject:
13192   case CK_ARCConsumeObject:
13193   case CK_ARCReclaimReturnedObject:
13194   case CK_ARCExtendBlockObject:
13195   case CK_CopyAndAutoreleaseBlockObject:
13196     return Error(E);
13197 
13198   case CK_UserDefinedConversion:
13199   case CK_LValueToRValue:
13200   case CK_AtomicToNonAtomic:
13201   case CK_NoOp:
13202   case CK_LValueToRValueBitCast:
13203     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13204 
13205   case CK_MemberPointerToBoolean:
13206   case CK_PointerToBoolean:
13207   case CK_IntegralToBoolean:
13208   case CK_FloatingToBoolean:
13209   case CK_BooleanToSignedIntegral:
13210   case CK_FloatingComplexToBoolean:
13211   case CK_IntegralComplexToBoolean: {
13212     bool BoolResult;
13213     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13214       return false;
13215     uint64_t IntResult = BoolResult;
13216     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13217       IntResult = (uint64_t)-1;
13218     return Success(IntResult, E);
13219   }
13220 
13221   case CK_FixedPointToIntegral: {
13222     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13223     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13224       return false;
13225     bool Overflowed;
13226     llvm::APSInt Result = Src.convertToInt(
13227         Info.Ctx.getIntWidth(DestType),
13228         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13229     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13230       return false;
13231     return Success(Result, E);
13232   }
13233 
13234   case CK_FixedPointToBoolean: {
13235     // Unsigned padding does not affect this.
13236     APValue Val;
13237     if (!Evaluate(Val, Info, SubExpr))
13238       return false;
13239     return Success(Val.getFixedPoint().getBoolValue(), E);
13240   }
13241 
13242   case CK_IntegralCast: {
13243     if (!Visit(SubExpr))
13244       return false;
13245 
13246     if (!Result.isInt()) {
13247       // Allow casts of address-of-label differences if they are no-ops
13248       // or narrowing.  (The narrowing case isn't actually guaranteed to
13249       // be constant-evaluatable except in some narrow cases which are hard
13250       // to detect here.  We let it through on the assumption the user knows
13251       // what they are doing.)
13252       if (Result.isAddrLabelDiff())
13253         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13254       // Only allow casts of lvalues if they are lossless.
13255       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13256     }
13257 
13258     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13259                                       Result.getInt()), E);
13260   }
13261 
13262   case CK_PointerToIntegral: {
13263     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13264 
13265     LValue LV;
13266     if (!EvaluatePointer(SubExpr, LV, Info))
13267       return false;
13268 
13269     if (LV.getLValueBase()) {
13270       // Only allow based lvalue casts if they are lossless.
13271       // FIXME: Allow a larger integer size than the pointer size, and allow
13272       // narrowing back down to pointer width in subsequent integral casts.
13273       // FIXME: Check integer type's active bits, not its type size.
13274       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13275         return Error(E);
13276 
13277       LV.Designator.setInvalid();
13278       LV.moveInto(Result);
13279       return true;
13280     }
13281 
13282     APSInt AsInt;
13283     APValue V;
13284     LV.moveInto(V);
13285     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13286       llvm_unreachable("Can't cast this!");
13287 
13288     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13289   }
13290 
13291   case CK_IntegralComplexToReal: {
13292     ComplexValue C;
13293     if (!EvaluateComplex(SubExpr, C, Info))
13294       return false;
13295     return Success(C.getComplexIntReal(), E);
13296   }
13297 
13298   case CK_FloatingToIntegral: {
13299     APFloat F(0.0);
13300     if (!EvaluateFloat(SubExpr, F, Info))
13301       return false;
13302 
13303     APSInt Value;
13304     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13305       return false;
13306     return Success(Value, E);
13307   }
13308   }
13309 
13310   llvm_unreachable("unknown cast resulting in integral value");
13311 }
13312 
13313 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13314   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13315     ComplexValue LV;
13316     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13317       return false;
13318     if (!LV.isComplexInt())
13319       return Error(E);
13320     return Success(LV.getComplexIntReal(), E);
13321   }
13322 
13323   return Visit(E->getSubExpr());
13324 }
13325 
13326 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13327   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13328     ComplexValue LV;
13329     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13330       return false;
13331     if (!LV.isComplexInt())
13332       return Error(E);
13333     return Success(LV.getComplexIntImag(), E);
13334   }
13335 
13336   VisitIgnoredValue(E->getSubExpr());
13337   return Success(0, E);
13338 }
13339 
13340 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13341   return Success(E->getPackLength(), E);
13342 }
13343 
13344 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13345   return Success(E->getValue(), E);
13346 }
13347 
13348 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13349        const ConceptSpecializationExpr *E) {
13350   return Success(E->isSatisfied(), E);
13351 }
13352 
13353 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13354   return Success(E->isSatisfied(), E);
13355 }
13356 
13357 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13358   switch (E->getOpcode()) {
13359     default:
13360       // Invalid unary operators
13361       return Error(E);
13362     case UO_Plus:
13363       // The result is just the value.
13364       return Visit(E->getSubExpr());
13365     case UO_Minus: {
13366       if (!Visit(E->getSubExpr())) return false;
13367       if (!Result.isFixedPoint())
13368         return Error(E);
13369       bool Overflowed;
13370       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13371       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13372         return false;
13373       return Success(Negated, E);
13374     }
13375     case UO_LNot: {
13376       bool bres;
13377       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13378         return false;
13379       return Success(!bres, E);
13380     }
13381   }
13382 }
13383 
13384 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13385   const Expr *SubExpr = E->getSubExpr();
13386   QualType DestType = E->getType();
13387   assert(DestType->isFixedPointType() &&
13388          "Expected destination type to be a fixed point type");
13389   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13390 
13391   switch (E->getCastKind()) {
13392   case CK_FixedPointCast: {
13393     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13394     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13395       return false;
13396     bool Overflowed;
13397     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13398     if (Overflowed) {
13399       if (Info.checkingForUndefinedBehavior())
13400         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13401                                          diag::warn_fixedpoint_constant_overflow)
13402           << Result.toString() << E->getType();
13403       if (!HandleOverflow(Info, E, Result, E->getType()))
13404         return false;
13405     }
13406     return Success(Result, E);
13407   }
13408   case CK_IntegralToFixedPoint: {
13409     APSInt Src;
13410     if (!EvaluateInteger(SubExpr, Src, Info))
13411       return false;
13412 
13413     bool Overflowed;
13414     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13415         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13416 
13417     if (Overflowed) {
13418       if (Info.checkingForUndefinedBehavior())
13419         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13420                                          diag::warn_fixedpoint_constant_overflow)
13421           << IntResult.toString() << E->getType();
13422       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13423         return false;
13424     }
13425 
13426     return Success(IntResult, E);
13427   }
13428   case CK_FloatingToFixedPoint: {
13429     APFloat Src(0.0);
13430     if (!EvaluateFloat(SubExpr, Src, Info))
13431       return false;
13432 
13433     bool Overflowed;
13434     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13435         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13436 
13437     if (Overflowed) {
13438       if (Info.checkingForUndefinedBehavior())
13439         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13440                                          diag::warn_fixedpoint_constant_overflow)
13441           << Result.toString() << E->getType();
13442       if (!HandleOverflow(Info, E, Result, E->getType()))
13443         return false;
13444     }
13445 
13446     return Success(Result, E);
13447   }
13448   case CK_NoOp:
13449   case CK_LValueToRValue:
13450     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13451   default:
13452     return Error(E);
13453   }
13454 }
13455 
13456 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13457   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13458     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13459 
13460   const Expr *LHS = E->getLHS();
13461   const Expr *RHS = E->getRHS();
13462   FixedPointSemantics ResultFXSema =
13463       Info.Ctx.getFixedPointSemantics(E->getType());
13464 
13465   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13466   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13467     return false;
13468   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13469   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13470     return false;
13471 
13472   bool OpOverflow = false, ConversionOverflow = false;
13473   APFixedPoint Result(LHSFX.getSemantics());
13474   switch (E->getOpcode()) {
13475   case BO_Add: {
13476     Result = LHSFX.add(RHSFX, &OpOverflow)
13477                   .convert(ResultFXSema, &ConversionOverflow);
13478     break;
13479   }
13480   case BO_Sub: {
13481     Result = LHSFX.sub(RHSFX, &OpOverflow)
13482                   .convert(ResultFXSema, &ConversionOverflow);
13483     break;
13484   }
13485   case BO_Mul: {
13486     Result = LHSFX.mul(RHSFX, &OpOverflow)
13487                   .convert(ResultFXSema, &ConversionOverflow);
13488     break;
13489   }
13490   case BO_Div: {
13491     if (RHSFX.getValue() == 0) {
13492       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13493       return false;
13494     }
13495     Result = LHSFX.div(RHSFX, &OpOverflow)
13496                   .convert(ResultFXSema, &ConversionOverflow);
13497     break;
13498   }
13499   case BO_Shl:
13500   case BO_Shr: {
13501     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13502     llvm::APSInt RHSVal = RHSFX.getValue();
13503 
13504     unsigned ShiftBW =
13505         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13506     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13507     // Embedded-C 4.1.6.2.2:
13508     //   The right operand must be nonnegative and less than the total number
13509     //   of (nonpadding) bits of the fixed-point operand ...
13510     if (RHSVal.isNegative())
13511       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13512     else if (Amt != RHSVal)
13513       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13514           << RHSVal << E->getType() << ShiftBW;
13515 
13516     if (E->getOpcode() == BO_Shl)
13517       Result = LHSFX.shl(Amt, &OpOverflow);
13518     else
13519       Result = LHSFX.shr(Amt, &OpOverflow);
13520     break;
13521   }
13522   default:
13523     return false;
13524   }
13525   if (OpOverflow || ConversionOverflow) {
13526     if (Info.checkingForUndefinedBehavior())
13527       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13528                                        diag::warn_fixedpoint_constant_overflow)
13529         << Result.toString() << E->getType();
13530     if (!HandleOverflow(Info, E, Result, E->getType()))
13531       return false;
13532   }
13533   return Success(Result, E);
13534 }
13535 
13536 //===----------------------------------------------------------------------===//
13537 // Float Evaluation
13538 //===----------------------------------------------------------------------===//
13539 
13540 namespace {
13541 class FloatExprEvaluator
13542   : public ExprEvaluatorBase<FloatExprEvaluator> {
13543   APFloat &Result;
13544 public:
13545   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13546     : ExprEvaluatorBaseTy(info), Result(result) {}
13547 
13548   bool Success(const APValue &V, const Expr *e) {
13549     Result = V.getFloat();
13550     return true;
13551   }
13552 
13553   bool ZeroInitialization(const Expr *E) {
13554     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13555     return true;
13556   }
13557 
13558   bool VisitCallExpr(const CallExpr *E);
13559 
13560   bool VisitUnaryOperator(const UnaryOperator *E);
13561   bool VisitBinaryOperator(const BinaryOperator *E);
13562   bool VisitFloatingLiteral(const FloatingLiteral *E);
13563   bool VisitCastExpr(const CastExpr *E);
13564 
13565   bool VisitUnaryReal(const UnaryOperator *E);
13566   bool VisitUnaryImag(const UnaryOperator *E);
13567 
13568   // FIXME: Missing: array subscript of vector, member of vector
13569 };
13570 } // end anonymous namespace
13571 
13572 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13573   assert(!E->isValueDependent());
13574   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13575   return FloatExprEvaluator(Info, Result).Visit(E);
13576 }
13577 
13578 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13579                                   QualType ResultTy,
13580                                   const Expr *Arg,
13581                                   bool SNaN,
13582                                   llvm::APFloat &Result) {
13583   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13584   if (!S) return false;
13585 
13586   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13587 
13588   llvm::APInt fill;
13589 
13590   // Treat empty strings as if they were zero.
13591   if (S->getString().empty())
13592     fill = llvm::APInt(32, 0);
13593   else if (S->getString().getAsInteger(0, fill))
13594     return false;
13595 
13596   if (Context.getTargetInfo().isNan2008()) {
13597     if (SNaN)
13598       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13599     else
13600       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13601   } else {
13602     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13603     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13604     // a different encoding to what became a standard in 2008, and for pre-
13605     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13606     // sNaN. This is now known as "legacy NaN" encoding.
13607     if (SNaN)
13608       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13609     else
13610       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13611   }
13612 
13613   return true;
13614 }
13615 
13616 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13617   switch (E->getBuiltinCallee()) {
13618   default:
13619     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13620 
13621   case Builtin::BI__builtin_huge_val:
13622   case Builtin::BI__builtin_huge_valf:
13623   case Builtin::BI__builtin_huge_vall:
13624   case Builtin::BI__builtin_huge_valf128:
13625   case Builtin::BI__builtin_inf:
13626   case Builtin::BI__builtin_inff:
13627   case Builtin::BI__builtin_infl:
13628   case Builtin::BI__builtin_inff128: {
13629     const llvm::fltSemantics &Sem =
13630       Info.Ctx.getFloatTypeSemantics(E->getType());
13631     Result = llvm::APFloat::getInf(Sem);
13632     return true;
13633   }
13634 
13635   case Builtin::BI__builtin_nans:
13636   case Builtin::BI__builtin_nansf:
13637   case Builtin::BI__builtin_nansl:
13638   case Builtin::BI__builtin_nansf128:
13639     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13640                                true, Result))
13641       return Error(E);
13642     return true;
13643 
13644   case Builtin::BI__builtin_nan:
13645   case Builtin::BI__builtin_nanf:
13646   case Builtin::BI__builtin_nanl:
13647   case Builtin::BI__builtin_nanf128:
13648     // If this is __builtin_nan() turn this into a nan, otherwise we
13649     // can't constant fold it.
13650     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13651                                false, Result))
13652       return Error(E);
13653     return true;
13654 
13655   case Builtin::BI__builtin_fabs:
13656   case Builtin::BI__builtin_fabsf:
13657   case Builtin::BI__builtin_fabsl:
13658   case Builtin::BI__builtin_fabsf128:
13659     // The C standard says "fabs raises no floating-point exceptions,
13660     // even if x is a signaling NaN. The returned value is independent of
13661     // the current rounding direction mode."  Therefore constant folding can
13662     // proceed without regard to the floating point settings.
13663     // Reference, WG14 N2478 F.10.4.3
13664     if (!EvaluateFloat(E->getArg(0), Result, Info))
13665       return false;
13666 
13667     if (Result.isNegative())
13668       Result.changeSign();
13669     return true;
13670 
13671   case Builtin::BI__arithmetic_fence:
13672     return EvaluateFloat(E->getArg(0), Result, Info);
13673 
13674   // FIXME: Builtin::BI__builtin_powi
13675   // FIXME: Builtin::BI__builtin_powif
13676   // FIXME: Builtin::BI__builtin_powil
13677 
13678   case Builtin::BI__builtin_copysign:
13679   case Builtin::BI__builtin_copysignf:
13680   case Builtin::BI__builtin_copysignl:
13681   case Builtin::BI__builtin_copysignf128: {
13682     APFloat RHS(0.);
13683     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13684         !EvaluateFloat(E->getArg(1), RHS, Info))
13685       return false;
13686     Result.copySign(RHS);
13687     return true;
13688   }
13689   }
13690 }
13691 
13692 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13693   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13694     ComplexValue CV;
13695     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13696       return false;
13697     Result = CV.FloatReal;
13698     return true;
13699   }
13700 
13701   return Visit(E->getSubExpr());
13702 }
13703 
13704 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13705   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13706     ComplexValue CV;
13707     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13708       return false;
13709     Result = CV.FloatImag;
13710     return true;
13711   }
13712 
13713   VisitIgnoredValue(E->getSubExpr());
13714   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13715   Result = llvm::APFloat::getZero(Sem);
13716   return true;
13717 }
13718 
13719 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13720   switch (E->getOpcode()) {
13721   default: return Error(E);
13722   case UO_Plus:
13723     return EvaluateFloat(E->getSubExpr(), Result, Info);
13724   case UO_Minus:
13725     // In C standard, WG14 N2478 F.3 p4
13726     // "the unary - raises no floating point exceptions,
13727     // even if the operand is signalling."
13728     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13729       return false;
13730     Result.changeSign();
13731     return true;
13732   }
13733 }
13734 
13735 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13736   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13737     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13738 
13739   APFloat RHS(0.0);
13740   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13741   if (!LHSOK && !Info.noteFailure())
13742     return false;
13743   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13744          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13745 }
13746 
13747 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13748   Result = E->getValue();
13749   return true;
13750 }
13751 
13752 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13753   const Expr* SubExpr = E->getSubExpr();
13754 
13755   switch (E->getCastKind()) {
13756   default:
13757     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13758 
13759   case CK_IntegralToFloating: {
13760     APSInt IntResult;
13761     const FPOptions FPO = E->getFPFeaturesInEffect(
13762                                   Info.Ctx.getLangOpts());
13763     return EvaluateInteger(SubExpr, IntResult, Info) &&
13764            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13765                                 IntResult, E->getType(), Result);
13766   }
13767 
13768   case CK_FixedPointToFloating: {
13769     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13770     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13771       return false;
13772     Result =
13773         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13774     return true;
13775   }
13776 
13777   case CK_FloatingCast: {
13778     if (!Visit(SubExpr))
13779       return false;
13780     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13781                                   Result);
13782   }
13783 
13784   case CK_FloatingComplexToReal: {
13785     ComplexValue V;
13786     if (!EvaluateComplex(SubExpr, V, Info))
13787       return false;
13788     Result = V.getComplexFloatReal();
13789     return true;
13790   }
13791   }
13792 }
13793 
13794 //===----------------------------------------------------------------------===//
13795 // Complex Evaluation (for float and integer)
13796 //===----------------------------------------------------------------------===//
13797 
13798 namespace {
13799 class ComplexExprEvaluator
13800   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13801   ComplexValue &Result;
13802 
13803 public:
13804   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13805     : ExprEvaluatorBaseTy(info), Result(Result) {}
13806 
13807   bool Success(const APValue &V, const Expr *e) {
13808     Result.setFrom(V);
13809     return true;
13810   }
13811 
13812   bool ZeroInitialization(const Expr *E);
13813 
13814   //===--------------------------------------------------------------------===//
13815   //                            Visitor Methods
13816   //===--------------------------------------------------------------------===//
13817 
13818   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13819   bool VisitCastExpr(const CastExpr *E);
13820   bool VisitBinaryOperator(const BinaryOperator *E);
13821   bool VisitUnaryOperator(const UnaryOperator *E);
13822   bool VisitInitListExpr(const InitListExpr *E);
13823   bool VisitCallExpr(const CallExpr *E);
13824 };
13825 } // end anonymous namespace
13826 
13827 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13828                             EvalInfo &Info) {
13829   assert(!E->isValueDependent());
13830   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13831   return ComplexExprEvaluator(Info, Result).Visit(E);
13832 }
13833 
13834 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13835   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13836   if (ElemTy->isRealFloatingType()) {
13837     Result.makeComplexFloat();
13838     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13839     Result.FloatReal = Zero;
13840     Result.FloatImag = Zero;
13841   } else {
13842     Result.makeComplexInt();
13843     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13844     Result.IntReal = Zero;
13845     Result.IntImag = Zero;
13846   }
13847   return true;
13848 }
13849 
13850 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13851   const Expr* SubExpr = E->getSubExpr();
13852 
13853   if (SubExpr->getType()->isRealFloatingType()) {
13854     Result.makeComplexFloat();
13855     APFloat &Imag = Result.FloatImag;
13856     if (!EvaluateFloat(SubExpr, Imag, Info))
13857       return false;
13858 
13859     Result.FloatReal = APFloat(Imag.getSemantics());
13860     return true;
13861   } else {
13862     assert(SubExpr->getType()->isIntegerType() &&
13863            "Unexpected imaginary literal.");
13864 
13865     Result.makeComplexInt();
13866     APSInt &Imag = Result.IntImag;
13867     if (!EvaluateInteger(SubExpr, Imag, Info))
13868       return false;
13869 
13870     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13871     return true;
13872   }
13873 }
13874 
13875 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13876 
13877   switch (E->getCastKind()) {
13878   case CK_BitCast:
13879   case CK_BaseToDerived:
13880   case CK_DerivedToBase:
13881   case CK_UncheckedDerivedToBase:
13882   case CK_Dynamic:
13883   case CK_ToUnion:
13884   case CK_ArrayToPointerDecay:
13885   case CK_FunctionToPointerDecay:
13886   case CK_NullToPointer:
13887   case CK_NullToMemberPointer:
13888   case CK_BaseToDerivedMemberPointer:
13889   case CK_DerivedToBaseMemberPointer:
13890   case CK_MemberPointerToBoolean:
13891   case CK_ReinterpretMemberPointer:
13892   case CK_ConstructorConversion:
13893   case CK_IntegralToPointer:
13894   case CK_PointerToIntegral:
13895   case CK_PointerToBoolean:
13896   case CK_ToVoid:
13897   case CK_VectorSplat:
13898   case CK_IntegralCast:
13899   case CK_BooleanToSignedIntegral:
13900   case CK_IntegralToBoolean:
13901   case CK_IntegralToFloating:
13902   case CK_FloatingToIntegral:
13903   case CK_FloatingToBoolean:
13904   case CK_FloatingCast:
13905   case CK_CPointerToObjCPointerCast:
13906   case CK_BlockPointerToObjCPointerCast:
13907   case CK_AnyPointerToBlockPointerCast:
13908   case CK_ObjCObjectLValueCast:
13909   case CK_FloatingComplexToReal:
13910   case CK_FloatingComplexToBoolean:
13911   case CK_IntegralComplexToReal:
13912   case CK_IntegralComplexToBoolean:
13913   case CK_ARCProduceObject:
13914   case CK_ARCConsumeObject:
13915   case CK_ARCReclaimReturnedObject:
13916   case CK_ARCExtendBlockObject:
13917   case CK_CopyAndAutoreleaseBlockObject:
13918   case CK_BuiltinFnToFnPtr:
13919   case CK_ZeroToOCLOpaqueType:
13920   case CK_NonAtomicToAtomic:
13921   case CK_AddressSpaceConversion:
13922   case CK_IntToOCLSampler:
13923   case CK_FloatingToFixedPoint:
13924   case CK_FixedPointToFloating:
13925   case CK_FixedPointCast:
13926   case CK_FixedPointToBoolean:
13927   case CK_FixedPointToIntegral:
13928   case CK_IntegralToFixedPoint:
13929   case CK_MatrixCast:
13930     llvm_unreachable("invalid cast kind for complex value");
13931 
13932   case CK_LValueToRValue:
13933   case CK_AtomicToNonAtomic:
13934   case CK_NoOp:
13935   case CK_LValueToRValueBitCast:
13936     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13937 
13938   case CK_Dependent:
13939   case CK_LValueBitCast:
13940   case CK_UserDefinedConversion:
13941     return Error(E);
13942 
13943   case CK_FloatingRealToComplex: {
13944     APFloat &Real = Result.FloatReal;
13945     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13946       return false;
13947 
13948     Result.makeComplexFloat();
13949     Result.FloatImag = APFloat(Real.getSemantics());
13950     return true;
13951   }
13952 
13953   case CK_FloatingComplexCast: {
13954     if (!Visit(E->getSubExpr()))
13955       return false;
13956 
13957     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13958     QualType From
13959       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13960 
13961     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13962            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13963   }
13964 
13965   case CK_FloatingComplexToIntegralComplex: {
13966     if (!Visit(E->getSubExpr()))
13967       return false;
13968 
13969     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13970     QualType From
13971       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13972     Result.makeComplexInt();
13973     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13974                                 To, Result.IntReal) &&
13975            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13976                                 To, Result.IntImag);
13977   }
13978 
13979   case CK_IntegralRealToComplex: {
13980     APSInt &Real = Result.IntReal;
13981     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13982       return false;
13983 
13984     Result.makeComplexInt();
13985     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13986     return true;
13987   }
13988 
13989   case CK_IntegralComplexCast: {
13990     if (!Visit(E->getSubExpr()))
13991       return false;
13992 
13993     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13994     QualType From
13995       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13996 
13997     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13998     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13999     return true;
14000   }
14001 
14002   case CK_IntegralComplexToFloatingComplex: {
14003     if (!Visit(E->getSubExpr()))
14004       return false;
14005 
14006     const FPOptions FPO = E->getFPFeaturesInEffect(
14007                                   Info.Ctx.getLangOpts());
14008     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14009     QualType From
14010       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14011     Result.makeComplexFloat();
14012     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14013                                 To, Result.FloatReal) &&
14014            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14015                                 To, Result.FloatImag);
14016   }
14017   }
14018 
14019   llvm_unreachable("unknown cast resulting in complex value");
14020 }
14021 
14022 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14023   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14024     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14025 
14026   // Track whether the LHS or RHS is real at the type system level. When this is
14027   // the case we can simplify our evaluation strategy.
14028   bool LHSReal = false, RHSReal = false;
14029 
14030   bool LHSOK;
14031   if (E->getLHS()->getType()->isRealFloatingType()) {
14032     LHSReal = true;
14033     APFloat &Real = Result.FloatReal;
14034     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14035     if (LHSOK) {
14036       Result.makeComplexFloat();
14037       Result.FloatImag = APFloat(Real.getSemantics());
14038     }
14039   } else {
14040     LHSOK = Visit(E->getLHS());
14041   }
14042   if (!LHSOK && !Info.noteFailure())
14043     return false;
14044 
14045   ComplexValue RHS;
14046   if (E->getRHS()->getType()->isRealFloatingType()) {
14047     RHSReal = true;
14048     APFloat &Real = RHS.FloatReal;
14049     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14050       return false;
14051     RHS.makeComplexFloat();
14052     RHS.FloatImag = APFloat(Real.getSemantics());
14053   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14054     return false;
14055 
14056   assert(!(LHSReal && RHSReal) &&
14057          "Cannot have both operands of a complex operation be real.");
14058   switch (E->getOpcode()) {
14059   default: return Error(E);
14060   case BO_Add:
14061     if (Result.isComplexFloat()) {
14062       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14063                                        APFloat::rmNearestTiesToEven);
14064       if (LHSReal)
14065         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14066       else if (!RHSReal)
14067         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14068                                          APFloat::rmNearestTiesToEven);
14069     } else {
14070       Result.getComplexIntReal() += RHS.getComplexIntReal();
14071       Result.getComplexIntImag() += RHS.getComplexIntImag();
14072     }
14073     break;
14074   case BO_Sub:
14075     if (Result.isComplexFloat()) {
14076       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14077                                             APFloat::rmNearestTiesToEven);
14078       if (LHSReal) {
14079         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14080         Result.getComplexFloatImag().changeSign();
14081       } else if (!RHSReal) {
14082         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14083                                               APFloat::rmNearestTiesToEven);
14084       }
14085     } else {
14086       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14087       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14088     }
14089     break;
14090   case BO_Mul:
14091     if (Result.isComplexFloat()) {
14092       // This is an implementation of complex multiplication according to the
14093       // constraints laid out in C11 Annex G. The implementation uses the
14094       // following naming scheme:
14095       //   (a + ib) * (c + id)
14096       ComplexValue LHS = Result;
14097       APFloat &A = LHS.getComplexFloatReal();
14098       APFloat &B = LHS.getComplexFloatImag();
14099       APFloat &C = RHS.getComplexFloatReal();
14100       APFloat &D = RHS.getComplexFloatImag();
14101       APFloat &ResR = Result.getComplexFloatReal();
14102       APFloat &ResI = Result.getComplexFloatImag();
14103       if (LHSReal) {
14104         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14105         ResR = A * C;
14106         ResI = A * D;
14107       } else if (RHSReal) {
14108         ResR = C * A;
14109         ResI = C * B;
14110       } else {
14111         // In the fully general case, we need to handle NaNs and infinities
14112         // robustly.
14113         APFloat AC = A * C;
14114         APFloat BD = B * D;
14115         APFloat AD = A * D;
14116         APFloat BC = B * C;
14117         ResR = AC - BD;
14118         ResI = AD + BC;
14119         if (ResR.isNaN() && ResI.isNaN()) {
14120           bool Recalc = false;
14121           if (A.isInfinity() || B.isInfinity()) {
14122             A = APFloat::copySign(
14123                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14124             B = APFloat::copySign(
14125                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14126             if (C.isNaN())
14127               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14128             if (D.isNaN())
14129               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14130             Recalc = true;
14131           }
14132           if (C.isInfinity() || D.isInfinity()) {
14133             C = APFloat::copySign(
14134                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14135             D = APFloat::copySign(
14136                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14137             if (A.isNaN())
14138               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14139             if (B.isNaN())
14140               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14141             Recalc = true;
14142           }
14143           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14144                           AD.isInfinity() || BC.isInfinity())) {
14145             if (A.isNaN())
14146               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14147             if (B.isNaN())
14148               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14149             if (C.isNaN())
14150               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14151             if (D.isNaN())
14152               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14153             Recalc = true;
14154           }
14155           if (Recalc) {
14156             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14157             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14158           }
14159         }
14160       }
14161     } else {
14162       ComplexValue LHS = Result;
14163       Result.getComplexIntReal() =
14164         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14165          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14166       Result.getComplexIntImag() =
14167         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14168          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14169     }
14170     break;
14171   case BO_Div:
14172     if (Result.isComplexFloat()) {
14173       // This is an implementation of complex division according to the
14174       // constraints laid out in C11 Annex G. The implementation uses the
14175       // following naming scheme:
14176       //   (a + ib) / (c + id)
14177       ComplexValue LHS = Result;
14178       APFloat &A = LHS.getComplexFloatReal();
14179       APFloat &B = LHS.getComplexFloatImag();
14180       APFloat &C = RHS.getComplexFloatReal();
14181       APFloat &D = RHS.getComplexFloatImag();
14182       APFloat &ResR = Result.getComplexFloatReal();
14183       APFloat &ResI = Result.getComplexFloatImag();
14184       if (RHSReal) {
14185         ResR = A / C;
14186         ResI = B / C;
14187       } else {
14188         if (LHSReal) {
14189           // No real optimizations we can do here, stub out with zero.
14190           B = APFloat::getZero(A.getSemantics());
14191         }
14192         int DenomLogB = 0;
14193         APFloat MaxCD = maxnum(abs(C), abs(D));
14194         if (MaxCD.isFinite()) {
14195           DenomLogB = ilogb(MaxCD);
14196           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14197           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14198         }
14199         APFloat Denom = C * C + D * D;
14200         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14201                       APFloat::rmNearestTiesToEven);
14202         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14203                       APFloat::rmNearestTiesToEven);
14204         if (ResR.isNaN() && ResI.isNaN()) {
14205           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14206             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14207             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14208           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14209                      D.isFinite()) {
14210             A = APFloat::copySign(
14211                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14212             B = APFloat::copySign(
14213                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14214             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14215             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14216           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14217             C = APFloat::copySign(
14218                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14219             D = APFloat::copySign(
14220                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14221             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14222             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14223           }
14224         }
14225       }
14226     } else {
14227       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14228         return Error(E, diag::note_expr_divide_by_zero);
14229 
14230       ComplexValue LHS = Result;
14231       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14232         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14233       Result.getComplexIntReal() =
14234         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14235          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14236       Result.getComplexIntImag() =
14237         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14238          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14239     }
14240     break;
14241   }
14242 
14243   return true;
14244 }
14245 
14246 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14247   // Get the operand value into 'Result'.
14248   if (!Visit(E->getSubExpr()))
14249     return false;
14250 
14251   switch (E->getOpcode()) {
14252   default:
14253     return Error(E);
14254   case UO_Extension:
14255     return true;
14256   case UO_Plus:
14257     // The result is always just the subexpr.
14258     return true;
14259   case UO_Minus:
14260     if (Result.isComplexFloat()) {
14261       Result.getComplexFloatReal().changeSign();
14262       Result.getComplexFloatImag().changeSign();
14263     }
14264     else {
14265       Result.getComplexIntReal() = -Result.getComplexIntReal();
14266       Result.getComplexIntImag() = -Result.getComplexIntImag();
14267     }
14268     return true;
14269   case UO_Not:
14270     if (Result.isComplexFloat())
14271       Result.getComplexFloatImag().changeSign();
14272     else
14273       Result.getComplexIntImag() = -Result.getComplexIntImag();
14274     return true;
14275   }
14276 }
14277 
14278 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14279   if (E->getNumInits() == 2) {
14280     if (E->getType()->isComplexType()) {
14281       Result.makeComplexFloat();
14282       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14283         return false;
14284       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14285         return false;
14286     } else {
14287       Result.makeComplexInt();
14288       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14289         return false;
14290       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14291         return false;
14292     }
14293     return true;
14294   }
14295   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14296 }
14297 
14298 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14299   switch (E->getBuiltinCallee()) {
14300   case Builtin::BI__builtin_complex:
14301     Result.makeComplexFloat();
14302     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14303       return false;
14304     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14305       return false;
14306     return true;
14307 
14308   default:
14309     break;
14310   }
14311 
14312   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14313 }
14314 
14315 //===----------------------------------------------------------------------===//
14316 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14317 // implicit conversion.
14318 //===----------------------------------------------------------------------===//
14319 
14320 namespace {
14321 class AtomicExprEvaluator :
14322     public ExprEvaluatorBase<AtomicExprEvaluator> {
14323   const LValue *This;
14324   APValue &Result;
14325 public:
14326   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14327       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14328 
14329   bool Success(const APValue &V, const Expr *E) {
14330     Result = V;
14331     return true;
14332   }
14333 
14334   bool ZeroInitialization(const Expr *E) {
14335     ImplicitValueInitExpr VIE(
14336         E->getType()->castAs<AtomicType>()->getValueType());
14337     // For atomic-qualified class (and array) types in C++, initialize the
14338     // _Atomic-wrapped subobject directly, in-place.
14339     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14340                 : Evaluate(Result, Info, &VIE);
14341   }
14342 
14343   bool VisitCastExpr(const CastExpr *E) {
14344     switch (E->getCastKind()) {
14345     default:
14346       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14347     case CK_NonAtomicToAtomic:
14348       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14349                   : Evaluate(Result, Info, E->getSubExpr());
14350     }
14351   }
14352 };
14353 } // end anonymous namespace
14354 
14355 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14356                            EvalInfo &Info) {
14357   assert(!E->isValueDependent());
14358   assert(E->isPRValue() && E->getType()->isAtomicType());
14359   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14360 }
14361 
14362 //===----------------------------------------------------------------------===//
14363 // Void expression evaluation, primarily for a cast to void on the LHS of a
14364 // comma operator
14365 //===----------------------------------------------------------------------===//
14366 
14367 namespace {
14368 class VoidExprEvaluator
14369   : public ExprEvaluatorBase<VoidExprEvaluator> {
14370 public:
14371   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14372 
14373   bool Success(const APValue &V, const Expr *e) { return true; }
14374 
14375   bool ZeroInitialization(const Expr *E) { return true; }
14376 
14377   bool VisitCastExpr(const CastExpr *E) {
14378     switch (E->getCastKind()) {
14379     default:
14380       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14381     case CK_ToVoid:
14382       VisitIgnoredValue(E->getSubExpr());
14383       return true;
14384     }
14385   }
14386 
14387   bool VisitCallExpr(const CallExpr *E) {
14388     switch (E->getBuiltinCallee()) {
14389     case Builtin::BI__assume:
14390     case Builtin::BI__builtin_assume:
14391       // The argument is not evaluated!
14392       return true;
14393 
14394     case Builtin::BI__builtin_operator_delete:
14395       return HandleOperatorDeleteCall(Info, E);
14396 
14397     default:
14398       break;
14399     }
14400 
14401     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14402   }
14403 
14404   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14405 };
14406 } // end anonymous namespace
14407 
14408 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14409   // We cannot speculatively evaluate a delete expression.
14410   if (Info.SpeculativeEvaluationDepth)
14411     return false;
14412 
14413   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14414   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14415     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14416         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14417     return false;
14418   }
14419 
14420   const Expr *Arg = E->getArgument();
14421 
14422   LValue Pointer;
14423   if (!EvaluatePointer(Arg, Pointer, Info))
14424     return false;
14425   if (Pointer.Designator.Invalid)
14426     return false;
14427 
14428   // Deleting a null pointer has no effect.
14429   if (Pointer.isNullPointer()) {
14430     // This is the only case where we need to produce an extension warning:
14431     // the only other way we can succeed is if we find a dynamic allocation,
14432     // and we will have warned when we allocated it in that case.
14433     if (!Info.getLangOpts().CPlusPlus20)
14434       Info.CCEDiag(E, diag::note_constexpr_new);
14435     return true;
14436   }
14437 
14438   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14439       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14440   if (!Alloc)
14441     return false;
14442   QualType AllocType = Pointer.Base.getDynamicAllocType();
14443 
14444   // For the non-array case, the designator must be empty if the static type
14445   // does not have a virtual destructor.
14446   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14447       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14448     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14449         << Arg->getType()->getPointeeType() << AllocType;
14450     return false;
14451   }
14452 
14453   // For a class type with a virtual destructor, the selected operator delete
14454   // is the one looked up when building the destructor.
14455   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14456     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14457     if (VirtualDelete &&
14458         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14459       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14460           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14461       return false;
14462     }
14463   }
14464 
14465   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14466                          (*Alloc)->Value, AllocType))
14467     return false;
14468 
14469   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14470     // The element was already erased. This means the destructor call also
14471     // deleted the object.
14472     // FIXME: This probably results in undefined behavior before we get this
14473     // far, and should be diagnosed elsewhere first.
14474     Info.FFDiag(E, diag::note_constexpr_double_delete);
14475     return false;
14476   }
14477 
14478   return true;
14479 }
14480 
14481 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14482   assert(!E->isValueDependent());
14483   assert(E->isPRValue() && E->getType()->isVoidType());
14484   return VoidExprEvaluator(Info).Visit(E);
14485 }
14486 
14487 //===----------------------------------------------------------------------===//
14488 // Top level Expr::EvaluateAsRValue method.
14489 //===----------------------------------------------------------------------===//
14490 
14491 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14492   assert(!E->isValueDependent());
14493   // In C, function designators are not lvalues, but we evaluate them as if they
14494   // are.
14495   QualType T = E->getType();
14496   if (E->isGLValue() || T->isFunctionType()) {
14497     LValue LV;
14498     if (!EvaluateLValue(E, LV, Info))
14499       return false;
14500     LV.moveInto(Result);
14501   } else if (T->isVectorType()) {
14502     if (!EvaluateVector(E, Result, Info))
14503       return false;
14504   } else if (T->isIntegralOrEnumerationType()) {
14505     if (!IntExprEvaluator(Info, Result).Visit(E))
14506       return false;
14507   } else if (T->hasPointerRepresentation()) {
14508     LValue LV;
14509     if (!EvaluatePointer(E, LV, Info))
14510       return false;
14511     LV.moveInto(Result);
14512   } else if (T->isRealFloatingType()) {
14513     llvm::APFloat F(0.0);
14514     if (!EvaluateFloat(E, F, Info))
14515       return false;
14516     Result = APValue(F);
14517   } else if (T->isAnyComplexType()) {
14518     ComplexValue C;
14519     if (!EvaluateComplex(E, C, Info))
14520       return false;
14521     C.moveInto(Result);
14522   } else if (T->isFixedPointType()) {
14523     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14524   } else if (T->isMemberPointerType()) {
14525     MemberPtr P;
14526     if (!EvaluateMemberPointer(E, P, Info))
14527       return false;
14528     P.moveInto(Result);
14529     return true;
14530   } else if (T->isArrayType()) {
14531     LValue LV;
14532     APValue &Value =
14533         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14534     if (!EvaluateArray(E, LV, Value, Info))
14535       return false;
14536     Result = Value;
14537   } else if (T->isRecordType()) {
14538     LValue LV;
14539     APValue &Value =
14540         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14541     if (!EvaluateRecord(E, LV, Value, Info))
14542       return false;
14543     Result = Value;
14544   } else if (T->isVoidType()) {
14545     if (!Info.getLangOpts().CPlusPlus11)
14546       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14547         << E->getType();
14548     if (!EvaluateVoid(E, Info))
14549       return false;
14550   } else if (T->isAtomicType()) {
14551     QualType Unqual = T.getAtomicUnqualifiedType();
14552     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14553       LValue LV;
14554       APValue &Value = Info.CurrentCall->createTemporary(
14555           E, Unqual, ScopeKind::FullExpression, LV);
14556       if (!EvaluateAtomic(E, &LV, Value, Info))
14557         return false;
14558     } else {
14559       if (!EvaluateAtomic(E, nullptr, Result, Info))
14560         return false;
14561     }
14562   } else if (Info.getLangOpts().CPlusPlus11) {
14563     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14564     return false;
14565   } else {
14566     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14567     return false;
14568   }
14569 
14570   return true;
14571 }
14572 
14573 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14574 /// cases, the in-place evaluation is essential, since later initializers for
14575 /// an object can indirectly refer to subobjects which were initialized earlier.
14576 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14577                             const Expr *E, bool AllowNonLiteralTypes) {
14578   assert(!E->isValueDependent());
14579 
14580   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14581     return false;
14582 
14583   if (E->isPRValue()) {
14584     // Evaluate arrays and record types in-place, so that later initializers can
14585     // refer to earlier-initialized members of the object.
14586     QualType T = E->getType();
14587     if (T->isArrayType())
14588       return EvaluateArray(E, This, Result, Info);
14589     else if (T->isRecordType())
14590       return EvaluateRecord(E, This, Result, Info);
14591     else if (T->isAtomicType()) {
14592       QualType Unqual = T.getAtomicUnqualifiedType();
14593       if (Unqual->isArrayType() || Unqual->isRecordType())
14594         return EvaluateAtomic(E, &This, Result, Info);
14595     }
14596   }
14597 
14598   // For any other type, in-place evaluation is unimportant.
14599   return Evaluate(Result, Info, E);
14600 }
14601 
14602 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14603 /// lvalue-to-rvalue cast if it is an lvalue.
14604 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14605   assert(!E->isValueDependent());
14606   if (Info.EnableNewConstInterp) {
14607     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14608       return false;
14609   } else {
14610     if (E->getType().isNull())
14611       return false;
14612 
14613     if (!CheckLiteralType(Info, E))
14614       return false;
14615 
14616     if (!::Evaluate(Result, Info, E))
14617       return false;
14618 
14619     if (E->isGLValue()) {
14620       LValue LV;
14621       LV.setFrom(Info.Ctx, Result);
14622       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14623         return false;
14624     }
14625   }
14626 
14627   // Check this core constant expression is a constant expression.
14628   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14629                                  ConstantExprKind::Normal) &&
14630          CheckMemoryLeaks(Info);
14631 }
14632 
14633 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14634                                  const ASTContext &Ctx, bool &IsConst) {
14635   // Fast-path evaluations of integer literals, since we sometimes see files
14636   // containing vast quantities of these.
14637   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14638     Result.Val = APValue(APSInt(L->getValue(),
14639                                 L->getType()->isUnsignedIntegerType()));
14640     IsConst = true;
14641     return true;
14642   }
14643 
14644   // This case should be rare, but we need to check it before we check on
14645   // the type below.
14646   if (Exp->getType().isNull()) {
14647     IsConst = false;
14648     return true;
14649   }
14650 
14651   // FIXME: Evaluating values of large array and record types can cause
14652   // performance problems. Only do so in C++11 for now.
14653   if (Exp->isPRValue() &&
14654       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14655       !Ctx.getLangOpts().CPlusPlus11) {
14656     IsConst = false;
14657     return true;
14658   }
14659   return false;
14660 }
14661 
14662 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14663                                       Expr::SideEffectsKind SEK) {
14664   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14665          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14666 }
14667 
14668 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14669                              const ASTContext &Ctx, EvalInfo &Info) {
14670   assert(!E->isValueDependent());
14671   bool IsConst;
14672   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14673     return IsConst;
14674 
14675   return EvaluateAsRValue(Info, E, Result.Val);
14676 }
14677 
14678 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14679                           const ASTContext &Ctx,
14680                           Expr::SideEffectsKind AllowSideEffects,
14681                           EvalInfo &Info) {
14682   assert(!E->isValueDependent());
14683   if (!E->getType()->isIntegralOrEnumerationType())
14684     return false;
14685 
14686   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14687       !ExprResult.Val.isInt() ||
14688       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14689     return false;
14690 
14691   return true;
14692 }
14693 
14694 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14695                                  const ASTContext &Ctx,
14696                                  Expr::SideEffectsKind AllowSideEffects,
14697                                  EvalInfo &Info) {
14698   assert(!E->isValueDependent());
14699   if (!E->getType()->isFixedPointType())
14700     return false;
14701 
14702   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14703     return false;
14704 
14705   if (!ExprResult.Val.isFixedPoint() ||
14706       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14707     return false;
14708 
14709   return true;
14710 }
14711 
14712 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14713 /// any crazy technique (that has nothing to do with language standards) that
14714 /// we want to.  If this function returns true, it returns the folded constant
14715 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14716 /// will be applied to the result.
14717 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14718                             bool InConstantContext) const {
14719   assert(!isValueDependent() &&
14720          "Expression evaluator can't be called on a dependent expression.");
14721   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14722   Info.InConstantContext = InConstantContext;
14723   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14724 }
14725 
14726 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14727                                       bool InConstantContext) const {
14728   assert(!isValueDependent() &&
14729          "Expression evaluator can't be called on a dependent expression.");
14730   EvalResult Scratch;
14731   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14732          HandleConversionToBool(Scratch.Val, Result);
14733 }
14734 
14735 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14736                          SideEffectsKind AllowSideEffects,
14737                          bool InConstantContext) const {
14738   assert(!isValueDependent() &&
14739          "Expression evaluator can't be called on a dependent expression.");
14740   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14741   Info.InConstantContext = InConstantContext;
14742   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14743 }
14744 
14745 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14746                                 SideEffectsKind AllowSideEffects,
14747                                 bool InConstantContext) const {
14748   assert(!isValueDependent() &&
14749          "Expression evaluator can't be called on a dependent expression.");
14750   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14751   Info.InConstantContext = InConstantContext;
14752   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14753 }
14754 
14755 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14756                            SideEffectsKind AllowSideEffects,
14757                            bool InConstantContext) const {
14758   assert(!isValueDependent() &&
14759          "Expression evaluator can't be called on a dependent expression.");
14760 
14761   if (!getType()->isRealFloatingType())
14762     return false;
14763 
14764   EvalResult ExprResult;
14765   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14766       !ExprResult.Val.isFloat() ||
14767       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14768     return false;
14769 
14770   Result = ExprResult.Val.getFloat();
14771   return true;
14772 }
14773 
14774 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14775                             bool InConstantContext) const {
14776   assert(!isValueDependent() &&
14777          "Expression evaluator can't be called on a dependent expression.");
14778 
14779   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14780   Info.InConstantContext = InConstantContext;
14781   LValue LV;
14782   CheckedTemporaries CheckedTemps;
14783   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14784       Result.HasSideEffects ||
14785       !CheckLValueConstantExpression(Info, getExprLoc(),
14786                                      Ctx.getLValueReferenceType(getType()), LV,
14787                                      ConstantExprKind::Normal, CheckedTemps))
14788     return false;
14789 
14790   LV.moveInto(Result.Val);
14791   return true;
14792 }
14793 
14794 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14795                                 APValue DestroyedValue, QualType Type,
14796                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14797                                 bool IsConstantDestruction) {
14798   EvalInfo Info(Ctx, EStatus,
14799                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14800                                       : EvalInfo::EM_ConstantFold);
14801   Info.setEvaluatingDecl(Base, DestroyedValue,
14802                          EvalInfo::EvaluatingDeclKind::Dtor);
14803   Info.InConstantContext = IsConstantDestruction;
14804 
14805   LValue LVal;
14806   LVal.set(Base);
14807 
14808   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14809       EStatus.HasSideEffects)
14810     return false;
14811 
14812   if (!Info.discardCleanups())
14813     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14814 
14815   return true;
14816 }
14817 
14818 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14819                                   ConstantExprKind Kind) const {
14820   assert(!isValueDependent() &&
14821          "Expression evaluator can't be called on a dependent expression.");
14822 
14823   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14824   EvalInfo Info(Ctx, Result, EM);
14825   Info.InConstantContext = true;
14826 
14827   // The type of the object we're initializing is 'const T' for a class NTTP.
14828   QualType T = getType();
14829   if (Kind == ConstantExprKind::ClassTemplateArgument)
14830     T.addConst();
14831 
14832   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14833   // represent the result of the evaluation. CheckConstantExpression ensures
14834   // this doesn't escape.
14835   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14836   APValue::LValueBase Base(&BaseMTE);
14837 
14838   Info.setEvaluatingDecl(Base, Result.Val);
14839   LValue LVal;
14840   LVal.set(Base);
14841 
14842   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14843     return false;
14844 
14845   if (!Info.discardCleanups())
14846     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14847 
14848   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14849                                Result.Val, Kind))
14850     return false;
14851   if (!CheckMemoryLeaks(Info))
14852     return false;
14853 
14854   // If this is a class template argument, it's required to have constant
14855   // destruction too.
14856   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14857       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14858                             true) ||
14859        Result.HasSideEffects)) {
14860     // FIXME: Prefix a note to indicate that the problem is lack of constant
14861     // destruction.
14862     return false;
14863   }
14864 
14865   return true;
14866 }
14867 
14868 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14869                                  const VarDecl *VD,
14870                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14871                                  bool IsConstantInitialization) const {
14872   assert(!isValueDependent() &&
14873          "Expression evaluator can't be called on a dependent expression.");
14874 
14875   // FIXME: Evaluating initializers for large array and record types can cause
14876   // performance problems. Only do so in C++11 for now.
14877   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14878       !Ctx.getLangOpts().CPlusPlus11)
14879     return false;
14880 
14881   Expr::EvalStatus EStatus;
14882   EStatus.Diag = &Notes;
14883 
14884   EvalInfo Info(Ctx, EStatus,
14885                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14886                     ? EvalInfo::EM_ConstantExpression
14887                     : EvalInfo::EM_ConstantFold);
14888   Info.setEvaluatingDecl(VD, Value);
14889   Info.InConstantContext = IsConstantInitialization;
14890 
14891   SourceLocation DeclLoc = VD->getLocation();
14892   QualType DeclTy = VD->getType();
14893 
14894   if (Info.EnableNewConstInterp) {
14895     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14896     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14897       return false;
14898   } else {
14899     LValue LVal;
14900     LVal.set(VD);
14901 
14902     if (!EvaluateInPlace(Value, Info, LVal, this,
14903                          /*AllowNonLiteralTypes=*/true) ||
14904         EStatus.HasSideEffects)
14905       return false;
14906 
14907     // At this point, any lifetime-extended temporaries are completely
14908     // initialized.
14909     Info.performLifetimeExtension();
14910 
14911     if (!Info.discardCleanups())
14912       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14913   }
14914   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14915                                  ConstantExprKind::Normal) &&
14916          CheckMemoryLeaks(Info);
14917 }
14918 
14919 bool VarDecl::evaluateDestruction(
14920     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14921   Expr::EvalStatus EStatus;
14922   EStatus.Diag = &Notes;
14923 
14924   // Only treat the destruction as constant destruction if we formally have
14925   // constant initialization (or are usable in a constant expression).
14926   bool IsConstantDestruction = hasConstantInitialization();
14927 
14928   // Make a copy of the value for the destructor to mutate, if we know it.
14929   // Otherwise, treat the value as default-initialized; if the destructor works
14930   // anyway, then the destruction is constant (and must be essentially empty).
14931   APValue DestroyedValue;
14932   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14933     DestroyedValue = *getEvaluatedValue();
14934   else if (!getDefaultInitValue(getType(), DestroyedValue))
14935     return false;
14936 
14937   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14938                            getType(), getLocation(), EStatus,
14939                            IsConstantDestruction) ||
14940       EStatus.HasSideEffects)
14941     return false;
14942 
14943   ensureEvaluatedStmt()->HasConstantDestruction = true;
14944   return true;
14945 }
14946 
14947 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14948 /// constant folded, but discard the result.
14949 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14950   assert(!isValueDependent() &&
14951          "Expression evaluator can't be called on a dependent expression.");
14952 
14953   EvalResult Result;
14954   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14955          !hasUnacceptableSideEffect(Result, SEK);
14956 }
14957 
14958 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14959                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14960   assert(!isValueDependent() &&
14961          "Expression evaluator can't be called on a dependent expression.");
14962 
14963   EvalResult EVResult;
14964   EVResult.Diag = Diag;
14965   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14966   Info.InConstantContext = true;
14967 
14968   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14969   (void)Result;
14970   assert(Result && "Could not evaluate expression");
14971   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14972 
14973   return EVResult.Val.getInt();
14974 }
14975 
14976 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14977     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14978   assert(!isValueDependent() &&
14979          "Expression evaluator can't be called on a dependent expression.");
14980 
14981   EvalResult EVResult;
14982   EVResult.Diag = Diag;
14983   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14984   Info.InConstantContext = true;
14985   Info.CheckingForUndefinedBehavior = true;
14986 
14987   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14988   (void)Result;
14989   assert(Result && "Could not evaluate expression");
14990   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14991 
14992   return EVResult.Val.getInt();
14993 }
14994 
14995 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14996   assert(!isValueDependent() &&
14997          "Expression evaluator can't be called on a dependent expression.");
14998 
14999   bool IsConst;
15000   EvalResult EVResult;
15001   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15002     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15003     Info.CheckingForUndefinedBehavior = true;
15004     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15005   }
15006 }
15007 
15008 bool Expr::EvalResult::isGlobalLValue() const {
15009   assert(Val.isLValue());
15010   return IsGlobalLValue(Val.getLValueBase());
15011 }
15012 
15013 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15014 /// an integer constant expression.
15015 
15016 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15017 /// comma, etc
15018 
15019 // CheckICE - This function does the fundamental ICE checking: the returned
15020 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15021 // and a (possibly null) SourceLocation indicating the location of the problem.
15022 //
15023 // Note that to reduce code duplication, this helper does no evaluation
15024 // itself; the caller checks whether the expression is evaluatable, and
15025 // in the rare cases where CheckICE actually cares about the evaluated
15026 // value, it calls into Evaluate.
15027 
15028 namespace {
15029 
15030 enum ICEKind {
15031   /// This expression is an ICE.
15032   IK_ICE,
15033   /// This expression is not an ICE, but if it isn't evaluated, it's
15034   /// a legal subexpression for an ICE. This return value is used to handle
15035   /// the comma operator in C99 mode, and non-constant subexpressions.
15036   IK_ICEIfUnevaluated,
15037   /// This expression is not an ICE, and is not a legal subexpression for one.
15038   IK_NotICE
15039 };
15040 
15041 struct ICEDiag {
15042   ICEKind Kind;
15043   SourceLocation Loc;
15044 
15045   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15046 };
15047 
15048 }
15049 
15050 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15051 
15052 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15053 
15054 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15055   Expr::EvalResult EVResult;
15056   Expr::EvalStatus Status;
15057   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15058 
15059   Info.InConstantContext = true;
15060   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15061       !EVResult.Val.isInt())
15062     return ICEDiag(IK_NotICE, E->getBeginLoc());
15063 
15064   return NoDiag();
15065 }
15066 
15067 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15068   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15069   if (!E->getType()->isIntegralOrEnumerationType())
15070     return ICEDiag(IK_NotICE, E->getBeginLoc());
15071 
15072   switch (E->getStmtClass()) {
15073 #define ABSTRACT_STMT(Node)
15074 #define STMT(Node, Base) case Expr::Node##Class:
15075 #define EXPR(Node, Base)
15076 #include "clang/AST/StmtNodes.inc"
15077   case Expr::PredefinedExprClass:
15078   case Expr::FloatingLiteralClass:
15079   case Expr::ImaginaryLiteralClass:
15080   case Expr::StringLiteralClass:
15081   case Expr::ArraySubscriptExprClass:
15082   case Expr::MatrixSubscriptExprClass:
15083   case Expr::OMPArraySectionExprClass:
15084   case Expr::OMPArrayShapingExprClass:
15085   case Expr::OMPIteratorExprClass:
15086   case Expr::MemberExprClass:
15087   case Expr::CompoundAssignOperatorClass:
15088   case Expr::CompoundLiteralExprClass:
15089   case Expr::ExtVectorElementExprClass:
15090   case Expr::DesignatedInitExprClass:
15091   case Expr::ArrayInitLoopExprClass:
15092   case Expr::ArrayInitIndexExprClass:
15093   case Expr::NoInitExprClass:
15094   case Expr::DesignatedInitUpdateExprClass:
15095   case Expr::ImplicitValueInitExprClass:
15096   case Expr::ParenListExprClass:
15097   case Expr::VAArgExprClass:
15098   case Expr::AddrLabelExprClass:
15099   case Expr::StmtExprClass:
15100   case Expr::CXXMemberCallExprClass:
15101   case Expr::CUDAKernelCallExprClass:
15102   case Expr::CXXAddrspaceCastExprClass:
15103   case Expr::CXXDynamicCastExprClass:
15104   case Expr::CXXTypeidExprClass:
15105   case Expr::CXXUuidofExprClass:
15106   case Expr::MSPropertyRefExprClass:
15107   case Expr::MSPropertySubscriptExprClass:
15108   case Expr::CXXNullPtrLiteralExprClass:
15109   case Expr::UserDefinedLiteralClass:
15110   case Expr::CXXThisExprClass:
15111   case Expr::CXXThrowExprClass:
15112   case Expr::CXXNewExprClass:
15113   case Expr::CXXDeleteExprClass:
15114   case Expr::CXXPseudoDestructorExprClass:
15115   case Expr::UnresolvedLookupExprClass:
15116   case Expr::TypoExprClass:
15117   case Expr::RecoveryExprClass:
15118   case Expr::DependentScopeDeclRefExprClass:
15119   case Expr::CXXConstructExprClass:
15120   case Expr::CXXInheritedCtorInitExprClass:
15121   case Expr::CXXStdInitializerListExprClass:
15122   case Expr::CXXBindTemporaryExprClass:
15123   case Expr::ExprWithCleanupsClass:
15124   case Expr::CXXTemporaryObjectExprClass:
15125   case Expr::CXXUnresolvedConstructExprClass:
15126   case Expr::CXXDependentScopeMemberExprClass:
15127   case Expr::UnresolvedMemberExprClass:
15128   case Expr::ObjCStringLiteralClass:
15129   case Expr::ObjCBoxedExprClass:
15130   case Expr::ObjCArrayLiteralClass:
15131   case Expr::ObjCDictionaryLiteralClass:
15132   case Expr::ObjCEncodeExprClass:
15133   case Expr::ObjCMessageExprClass:
15134   case Expr::ObjCSelectorExprClass:
15135   case Expr::ObjCProtocolExprClass:
15136   case Expr::ObjCIvarRefExprClass:
15137   case Expr::ObjCPropertyRefExprClass:
15138   case Expr::ObjCSubscriptRefExprClass:
15139   case Expr::ObjCIsaExprClass:
15140   case Expr::ObjCAvailabilityCheckExprClass:
15141   case Expr::ShuffleVectorExprClass:
15142   case Expr::ConvertVectorExprClass:
15143   case Expr::BlockExprClass:
15144   case Expr::NoStmtClass:
15145   case Expr::OpaqueValueExprClass:
15146   case Expr::PackExpansionExprClass:
15147   case Expr::SubstNonTypeTemplateParmPackExprClass:
15148   case Expr::FunctionParmPackExprClass:
15149   case Expr::AsTypeExprClass:
15150   case Expr::ObjCIndirectCopyRestoreExprClass:
15151   case Expr::MaterializeTemporaryExprClass:
15152   case Expr::PseudoObjectExprClass:
15153   case Expr::AtomicExprClass:
15154   case Expr::LambdaExprClass:
15155   case Expr::CXXFoldExprClass:
15156   case Expr::CoawaitExprClass:
15157   case Expr::DependentCoawaitExprClass:
15158   case Expr::CoyieldExprClass:
15159   case Expr::SYCLUniqueStableNameExprClass:
15160     return ICEDiag(IK_NotICE, E->getBeginLoc());
15161 
15162   case Expr::InitListExprClass: {
15163     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15164     // form "T x = { a };" is equivalent to "T x = a;".
15165     // Unless we're initializing a reference, T is a scalar as it is known to be
15166     // of integral or enumeration type.
15167     if (E->isPRValue())
15168       if (cast<InitListExpr>(E)->getNumInits() == 1)
15169         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15170     return ICEDiag(IK_NotICE, E->getBeginLoc());
15171   }
15172 
15173   case Expr::SizeOfPackExprClass:
15174   case Expr::GNUNullExprClass:
15175   case Expr::SourceLocExprClass:
15176     return NoDiag();
15177 
15178   case Expr::SubstNonTypeTemplateParmExprClass:
15179     return
15180       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15181 
15182   case Expr::ConstantExprClass:
15183     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15184 
15185   case Expr::ParenExprClass:
15186     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15187   case Expr::GenericSelectionExprClass:
15188     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15189   case Expr::IntegerLiteralClass:
15190   case Expr::FixedPointLiteralClass:
15191   case Expr::CharacterLiteralClass:
15192   case Expr::ObjCBoolLiteralExprClass:
15193   case Expr::CXXBoolLiteralExprClass:
15194   case Expr::CXXScalarValueInitExprClass:
15195   case Expr::TypeTraitExprClass:
15196   case Expr::ConceptSpecializationExprClass:
15197   case Expr::RequiresExprClass:
15198   case Expr::ArrayTypeTraitExprClass:
15199   case Expr::ExpressionTraitExprClass:
15200   case Expr::CXXNoexceptExprClass:
15201     return NoDiag();
15202   case Expr::CallExprClass:
15203   case Expr::CXXOperatorCallExprClass: {
15204     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15205     // constant expressions, but they can never be ICEs because an ICE cannot
15206     // contain an operand of (pointer to) function type.
15207     const CallExpr *CE = cast<CallExpr>(E);
15208     if (CE->getBuiltinCallee())
15209       return CheckEvalInICE(E, Ctx);
15210     return ICEDiag(IK_NotICE, E->getBeginLoc());
15211   }
15212   case Expr::CXXRewrittenBinaryOperatorClass:
15213     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15214                     Ctx);
15215   case Expr::DeclRefExprClass: {
15216     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15217     if (isa<EnumConstantDecl>(D))
15218       return NoDiag();
15219 
15220     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15221     // integer variables in constant expressions:
15222     //
15223     // C++ 7.1.5.1p2
15224     //   A variable of non-volatile const-qualified integral or enumeration
15225     //   type initialized by an ICE can be used in ICEs.
15226     //
15227     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15228     // that mode, use of reference variables should not be allowed.
15229     const VarDecl *VD = dyn_cast<VarDecl>(D);
15230     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15231         !VD->getType()->isReferenceType())
15232       return NoDiag();
15233 
15234     return ICEDiag(IK_NotICE, E->getBeginLoc());
15235   }
15236   case Expr::UnaryOperatorClass: {
15237     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15238     switch (Exp->getOpcode()) {
15239     case UO_PostInc:
15240     case UO_PostDec:
15241     case UO_PreInc:
15242     case UO_PreDec:
15243     case UO_AddrOf:
15244     case UO_Deref:
15245     case UO_Coawait:
15246       // C99 6.6/3 allows increment and decrement within unevaluated
15247       // subexpressions of constant expressions, but they can never be ICEs
15248       // because an ICE cannot contain an lvalue operand.
15249       return ICEDiag(IK_NotICE, E->getBeginLoc());
15250     case UO_Extension:
15251     case UO_LNot:
15252     case UO_Plus:
15253     case UO_Minus:
15254     case UO_Not:
15255     case UO_Real:
15256     case UO_Imag:
15257       return CheckICE(Exp->getSubExpr(), Ctx);
15258     }
15259     llvm_unreachable("invalid unary operator class");
15260   }
15261   case Expr::OffsetOfExprClass: {
15262     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15263     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15264     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15265     // compliance: we should warn earlier for offsetof expressions with
15266     // array subscripts that aren't ICEs, and if the array subscripts
15267     // are ICEs, the value of the offsetof must be an integer constant.
15268     return CheckEvalInICE(E, Ctx);
15269   }
15270   case Expr::UnaryExprOrTypeTraitExprClass: {
15271     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15272     if ((Exp->getKind() ==  UETT_SizeOf) &&
15273         Exp->getTypeOfArgument()->isVariableArrayType())
15274       return ICEDiag(IK_NotICE, E->getBeginLoc());
15275     return NoDiag();
15276   }
15277   case Expr::BinaryOperatorClass: {
15278     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15279     switch (Exp->getOpcode()) {
15280     case BO_PtrMemD:
15281     case BO_PtrMemI:
15282     case BO_Assign:
15283     case BO_MulAssign:
15284     case BO_DivAssign:
15285     case BO_RemAssign:
15286     case BO_AddAssign:
15287     case BO_SubAssign:
15288     case BO_ShlAssign:
15289     case BO_ShrAssign:
15290     case BO_AndAssign:
15291     case BO_XorAssign:
15292     case BO_OrAssign:
15293       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15294       // constant expressions, but they can never be ICEs because an ICE cannot
15295       // contain an lvalue operand.
15296       return ICEDiag(IK_NotICE, E->getBeginLoc());
15297 
15298     case BO_Mul:
15299     case BO_Div:
15300     case BO_Rem:
15301     case BO_Add:
15302     case BO_Sub:
15303     case BO_Shl:
15304     case BO_Shr:
15305     case BO_LT:
15306     case BO_GT:
15307     case BO_LE:
15308     case BO_GE:
15309     case BO_EQ:
15310     case BO_NE:
15311     case BO_And:
15312     case BO_Xor:
15313     case BO_Or:
15314     case BO_Comma:
15315     case BO_Cmp: {
15316       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15317       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15318       if (Exp->getOpcode() == BO_Div ||
15319           Exp->getOpcode() == BO_Rem) {
15320         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15321         // we don't evaluate one.
15322         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15323           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15324           if (REval == 0)
15325             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15326           if (REval.isSigned() && REval.isAllOnes()) {
15327             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15328             if (LEval.isMinSignedValue())
15329               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15330           }
15331         }
15332       }
15333       if (Exp->getOpcode() == BO_Comma) {
15334         if (Ctx.getLangOpts().C99) {
15335           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15336           // if it isn't evaluated.
15337           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15338             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15339         } else {
15340           // In both C89 and C++, commas in ICEs are illegal.
15341           return ICEDiag(IK_NotICE, E->getBeginLoc());
15342         }
15343       }
15344       return Worst(LHSResult, RHSResult);
15345     }
15346     case BO_LAnd:
15347     case BO_LOr: {
15348       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15349       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15350       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15351         // Rare case where the RHS has a comma "side-effect"; we need
15352         // to actually check the condition to see whether the side
15353         // with the comma is evaluated.
15354         if ((Exp->getOpcode() == BO_LAnd) !=
15355             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15356           return RHSResult;
15357         return NoDiag();
15358       }
15359 
15360       return Worst(LHSResult, RHSResult);
15361     }
15362     }
15363     llvm_unreachable("invalid binary operator kind");
15364   }
15365   case Expr::ImplicitCastExprClass:
15366   case Expr::CStyleCastExprClass:
15367   case Expr::CXXFunctionalCastExprClass:
15368   case Expr::CXXStaticCastExprClass:
15369   case Expr::CXXReinterpretCastExprClass:
15370   case Expr::CXXConstCastExprClass:
15371   case Expr::ObjCBridgedCastExprClass: {
15372     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15373     if (isa<ExplicitCastExpr>(E)) {
15374       if (const FloatingLiteral *FL
15375             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15376         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15377         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15378         APSInt IgnoredVal(DestWidth, !DestSigned);
15379         bool Ignored;
15380         // If the value does not fit in the destination type, the behavior is
15381         // undefined, so we are not required to treat it as a constant
15382         // expression.
15383         if (FL->getValue().convertToInteger(IgnoredVal,
15384                                             llvm::APFloat::rmTowardZero,
15385                                             &Ignored) & APFloat::opInvalidOp)
15386           return ICEDiag(IK_NotICE, E->getBeginLoc());
15387         return NoDiag();
15388       }
15389     }
15390     switch (cast<CastExpr>(E)->getCastKind()) {
15391     case CK_LValueToRValue:
15392     case CK_AtomicToNonAtomic:
15393     case CK_NonAtomicToAtomic:
15394     case CK_NoOp:
15395     case CK_IntegralToBoolean:
15396     case CK_IntegralCast:
15397       return CheckICE(SubExpr, Ctx);
15398     default:
15399       return ICEDiag(IK_NotICE, E->getBeginLoc());
15400     }
15401   }
15402   case Expr::BinaryConditionalOperatorClass: {
15403     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15404     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15405     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15406     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15407     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15408     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15409     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15410         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15411     return FalseResult;
15412   }
15413   case Expr::ConditionalOperatorClass: {
15414     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15415     // If the condition (ignoring parens) is a __builtin_constant_p call,
15416     // then only the true side is actually considered in an integer constant
15417     // expression, and it is fully evaluated.  This is an important GNU
15418     // extension.  See GCC PR38377 for discussion.
15419     if (const CallExpr *CallCE
15420         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15421       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15422         return CheckEvalInICE(E, Ctx);
15423     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15424     if (CondResult.Kind == IK_NotICE)
15425       return CondResult;
15426 
15427     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15428     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15429 
15430     if (TrueResult.Kind == IK_NotICE)
15431       return TrueResult;
15432     if (FalseResult.Kind == IK_NotICE)
15433       return FalseResult;
15434     if (CondResult.Kind == IK_ICEIfUnevaluated)
15435       return CondResult;
15436     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15437       return NoDiag();
15438     // Rare case where the diagnostics depend on which side is evaluated
15439     // Note that if we get here, CondResult is 0, and at least one of
15440     // TrueResult and FalseResult is non-zero.
15441     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15442       return FalseResult;
15443     return TrueResult;
15444   }
15445   case Expr::CXXDefaultArgExprClass:
15446     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15447   case Expr::CXXDefaultInitExprClass:
15448     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15449   case Expr::ChooseExprClass: {
15450     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15451   }
15452   case Expr::BuiltinBitCastExprClass: {
15453     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15454       return ICEDiag(IK_NotICE, E->getBeginLoc());
15455     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15456   }
15457   }
15458 
15459   llvm_unreachable("Invalid StmtClass!");
15460 }
15461 
15462 /// Evaluate an expression as a C++11 integral constant expression.
15463 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15464                                                     const Expr *E,
15465                                                     llvm::APSInt *Value,
15466                                                     SourceLocation *Loc) {
15467   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15468     if (Loc) *Loc = E->getExprLoc();
15469     return false;
15470   }
15471 
15472   APValue Result;
15473   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15474     return false;
15475 
15476   if (!Result.isInt()) {
15477     if (Loc) *Loc = E->getExprLoc();
15478     return false;
15479   }
15480 
15481   if (Value) *Value = Result.getInt();
15482   return true;
15483 }
15484 
15485 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15486                                  SourceLocation *Loc) const {
15487   assert(!isValueDependent() &&
15488          "Expression evaluator can't be called on a dependent expression.");
15489 
15490   if (Ctx.getLangOpts().CPlusPlus11)
15491     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15492 
15493   ICEDiag D = CheckICE(this, Ctx);
15494   if (D.Kind != IK_ICE) {
15495     if (Loc) *Loc = D.Loc;
15496     return false;
15497   }
15498   return true;
15499 }
15500 
15501 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15502                                                     SourceLocation *Loc,
15503                                                     bool isEvaluated) const {
15504   if (isValueDependent()) {
15505     // Expression evaluator can't succeed on a dependent expression.
15506     return None;
15507   }
15508 
15509   APSInt Value;
15510 
15511   if (Ctx.getLangOpts().CPlusPlus11) {
15512     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15513       return Value;
15514     return None;
15515   }
15516 
15517   if (!isIntegerConstantExpr(Ctx, Loc))
15518     return None;
15519 
15520   // The only possible side-effects here are due to UB discovered in the
15521   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15522   // required to treat the expression as an ICE, so we produce the folded
15523   // value.
15524   EvalResult ExprResult;
15525   Expr::EvalStatus Status;
15526   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15527   Info.InConstantContext = true;
15528 
15529   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15530     llvm_unreachable("ICE cannot be evaluated!");
15531 
15532   return ExprResult.Val.getInt();
15533 }
15534 
15535 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15536   assert(!isValueDependent() &&
15537          "Expression evaluator can't be called on a dependent expression.");
15538 
15539   return CheckICE(this, Ctx).Kind == IK_ICE;
15540 }
15541 
15542 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15543                                SourceLocation *Loc) const {
15544   assert(!isValueDependent() &&
15545          "Expression evaluator can't be called on a dependent expression.");
15546 
15547   // We support this checking in C++98 mode in order to diagnose compatibility
15548   // issues.
15549   assert(Ctx.getLangOpts().CPlusPlus);
15550 
15551   // Build evaluation settings.
15552   Expr::EvalStatus Status;
15553   SmallVector<PartialDiagnosticAt, 8> Diags;
15554   Status.Diag = &Diags;
15555   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15556 
15557   APValue Scratch;
15558   bool IsConstExpr =
15559       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15560       // FIXME: We don't produce a diagnostic for this, but the callers that
15561       // call us on arbitrary full-expressions should generally not care.
15562       Info.discardCleanups() && !Status.HasSideEffects;
15563 
15564   if (!Diags.empty()) {
15565     IsConstExpr = false;
15566     if (Loc) *Loc = Diags[0].first;
15567   } else if (!IsConstExpr) {
15568     // FIXME: This shouldn't happen.
15569     if (Loc) *Loc = getExprLoc();
15570   }
15571 
15572   return IsConstExpr;
15573 }
15574 
15575 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15576                                     const FunctionDecl *Callee,
15577                                     ArrayRef<const Expr*> Args,
15578                                     const Expr *This) const {
15579   assert(!isValueDependent() &&
15580          "Expression evaluator can't be called on a dependent expression.");
15581 
15582   Expr::EvalStatus Status;
15583   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15584   Info.InConstantContext = true;
15585 
15586   LValue ThisVal;
15587   const LValue *ThisPtr = nullptr;
15588   if (This) {
15589 #ifndef NDEBUG
15590     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15591     assert(MD && "Don't provide `this` for non-methods.");
15592     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15593 #endif
15594     if (!This->isValueDependent() &&
15595         EvaluateObjectArgument(Info, This, ThisVal) &&
15596         !Info.EvalStatus.HasSideEffects)
15597       ThisPtr = &ThisVal;
15598 
15599     // Ignore any side-effects from a failed evaluation. This is safe because
15600     // they can't interfere with any other argument evaluation.
15601     Info.EvalStatus.HasSideEffects = false;
15602   }
15603 
15604   CallRef Call = Info.CurrentCall->createCall(Callee);
15605   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15606        I != E; ++I) {
15607     unsigned Idx = I - Args.begin();
15608     if (Idx >= Callee->getNumParams())
15609       break;
15610     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15611     if ((*I)->isValueDependent() ||
15612         !EvaluateCallArg(PVD, *I, Call, Info) ||
15613         Info.EvalStatus.HasSideEffects) {
15614       // If evaluation fails, throw away the argument entirely.
15615       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15616         *Slot = APValue();
15617     }
15618 
15619     // Ignore any side-effects from a failed evaluation. This is safe because
15620     // they can't interfere with any other argument evaluation.
15621     Info.EvalStatus.HasSideEffects = false;
15622   }
15623 
15624   // Parameter cleanups happen in the caller and are not part of this
15625   // evaluation.
15626   Info.discardCleanups();
15627   Info.EvalStatus.HasSideEffects = false;
15628 
15629   // Build fake call to Callee.
15630   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15631   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15632   FullExpressionRAII Scope(Info);
15633   return Evaluate(Value, Info, this) && Scope.destroy() &&
15634          !Info.EvalStatus.HasSideEffects;
15635 }
15636 
15637 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15638                                    SmallVectorImpl<
15639                                      PartialDiagnosticAt> &Diags) {
15640   // FIXME: It would be useful to check constexpr function templates, but at the
15641   // moment the constant expression evaluator cannot cope with the non-rigorous
15642   // ASTs which we build for dependent expressions.
15643   if (FD->isDependentContext())
15644     return true;
15645 
15646   Expr::EvalStatus Status;
15647   Status.Diag = &Diags;
15648 
15649   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15650   Info.InConstantContext = true;
15651   Info.CheckingPotentialConstantExpression = true;
15652 
15653   // The constexpr VM attempts to compile all methods to bytecode here.
15654   if (Info.EnableNewConstInterp) {
15655     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15656     return Diags.empty();
15657   }
15658 
15659   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15660   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15661 
15662   // Fabricate an arbitrary expression on the stack and pretend that it
15663   // is a temporary being used as the 'this' pointer.
15664   LValue This;
15665   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15666   This.set({&VIE, Info.CurrentCall->Index});
15667 
15668   ArrayRef<const Expr*> Args;
15669 
15670   APValue Scratch;
15671   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15672     // Evaluate the call as a constant initializer, to allow the construction
15673     // of objects of non-literal types.
15674     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15675     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15676   } else {
15677     SourceLocation Loc = FD->getLocation();
15678     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15679                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15680   }
15681 
15682   return Diags.empty();
15683 }
15684 
15685 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15686                                               const FunctionDecl *FD,
15687                                               SmallVectorImpl<
15688                                                 PartialDiagnosticAt> &Diags) {
15689   assert(!E->isValueDependent() &&
15690          "Expression evaluator can't be called on a dependent expression.");
15691 
15692   Expr::EvalStatus Status;
15693   Status.Diag = &Diags;
15694 
15695   EvalInfo Info(FD->getASTContext(), Status,
15696                 EvalInfo::EM_ConstantExpressionUnevaluated);
15697   Info.InConstantContext = true;
15698   Info.CheckingPotentialConstantExpression = true;
15699 
15700   // Fabricate a call stack frame to give the arguments a plausible cover story.
15701   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15702 
15703   APValue ResultScratch;
15704   Evaluate(ResultScratch, Info, E);
15705   return Diags.empty();
15706 }
15707 
15708 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15709                                  unsigned Type) const {
15710   if (!getType()->isPointerType())
15711     return false;
15712 
15713   Expr::EvalStatus Status;
15714   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15715   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15716 }
15717 
15718 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15719                                   EvalInfo &Info) {
15720   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15721     return false;
15722 
15723   LValue String;
15724 
15725   if (!EvaluatePointer(E, String, Info))
15726     return false;
15727 
15728   QualType CharTy = E->getType()->getPointeeType();
15729 
15730   // Fast path: if it's a string literal, search the string value.
15731   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15732           String.getLValueBase().dyn_cast<const Expr *>())) {
15733     StringRef Str = S->getBytes();
15734     int64_t Off = String.Offset.getQuantity();
15735     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15736         S->getCharByteWidth() == 1 &&
15737         // FIXME: Add fast-path for wchar_t too.
15738         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15739       Str = Str.substr(Off);
15740 
15741       StringRef::size_type Pos = Str.find(0);
15742       if (Pos != StringRef::npos)
15743         Str = Str.substr(0, Pos);
15744 
15745       Result = Str.size();
15746       return true;
15747     }
15748 
15749     // Fall through to slow path.
15750   }
15751 
15752   // Slow path: scan the bytes of the string looking for the terminating 0.
15753   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15754     APValue Char;
15755     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15756         !Char.isInt())
15757       return false;
15758     if (!Char.getInt()) {
15759       Result = Strlen;
15760       return true;
15761     }
15762     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15763       return false;
15764   }
15765 }
15766 
15767 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15768   Expr::EvalStatus Status;
15769   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15770   return EvaluateBuiltinStrLen(this, Result, Info);
15771 }
15772