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   // The boolean operations on these vector types use an instruction that
2935   // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2936   // to -1 to make sure that we produce the correct value.
2937   Result.negate();
2938 
2939   return true;
2940 }
2941 
2942 static bool handleCompareOpForVector(const APValue &LHSValue,
2943                                      BinaryOperatorKind Opcode,
2944                                      const APValue &RHSValue, APInt &Result) {
2945   // The result is always an int type, however operands match the first.
2946   if (LHSValue.getKind() == APValue::Int)
2947     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2948                                           RHSValue.getInt(), Result);
2949   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2950   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2951                                         RHSValue.getFloat(), Result);
2952 }
2953 
2954 // Perform binary operations for vector types, in place on the LHS.
2955 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2956                                     BinaryOperatorKind Opcode,
2957                                     APValue &LHSValue,
2958                                     const APValue &RHSValue) {
2959   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2960          "Operation not supported on vector types");
2961 
2962   const auto *VT = E->getType()->castAs<VectorType>();
2963   unsigned NumElements = VT->getNumElements();
2964   QualType EltTy = VT->getElementType();
2965 
2966   // In the cases (typically C as I've observed) where we aren't evaluating
2967   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2968   // just give up.
2969   if (!LHSValue.isVector()) {
2970     assert(LHSValue.isLValue() &&
2971            "A vector result that isn't a vector OR uncalculated LValue");
2972     Info.FFDiag(E);
2973     return false;
2974   }
2975 
2976   assert(LHSValue.getVectorLength() == NumElements &&
2977          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2978 
2979   SmallVector<APValue, 4> ResultElements;
2980 
2981   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2982     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2983     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2984 
2985     if (EltTy->isIntegerType()) {
2986       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2987                        EltTy->isUnsignedIntegerType()};
2988       bool Success = true;
2989 
2990       if (BinaryOperator::isLogicalOp(Opcode))
2991         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2992       else if (BinaryOperator::isComparisonOp(Opcode))
2993         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2994       else
2995         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2996                                     RHSElt.getInt(), EltResult);
2997 
2998       if (!Success) {
2999         Info.FFDiag(E);
3000         return false;
3001       }
3002       ResultElements.emplace_back(EltResult);
3003 
3004     } else if (EltTy->isFloatingType()) {
3005       assert(LHSElt.getKind() == APValue::Float &&
3006              RHSElt.getKind() == APValue::Float &&
3007              "Mismatched LHS/RHS/Result Type");
3008       APFloat LHSFloat = LHSElt.getFloat();
3009 
3010       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3011                                  RHSElt.getFloat())) {
3012         Info.FFDiag(E);
3013         return false;
3014       }
3015 
3016       ResultElements.emplace_back(LHSFloat);
3017     }
3018   }
3019 
3020   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3021   return true;
3022 }
3023 
3024 /// Cast an lvalue referring to a base subobject to a derived class, by
3025 /// truncating the lvalue's path to the given length.
3026 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3027                                const RecordDecl *TruncatedType,
3028                                unsigned TruncatedElements) {
3029   SubobjectDesignator &D = Result.Designator;
3030 
3031   // Check we actually point to a derived class object.
3032   if (TruncatedElements == D.Entries.size())
3033     return true;
3034   assert(TruncatedElements >= D.MostDerivedPathLength &&
3035          "not casting to a derived class");
3036   if (!Result.checkSubobject(Info, E, CSK_Derived))
3037     return false;
3038 
3039   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3040   const RecordDecl *RD = TruncatedType;
3041   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3042     if (RD->isInvalidDecl()) return false;
3043     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3044     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3045     if (isVirtualBaseClass(D.Entries[I]))
3046       Result.Offset -= Layout.getVBaseClassOffset(Base);
3047     else
3048       Result.Offset -= Layout.getBaseClassOffset(Base);
3049     RD = Base;
3050   }
3051   D.Entries.resize(TruncatedElements);
3052   return true;
3053 }
3054 
3055 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3056                                    const CXXRecordDecl *Derived,
3057                                    const CXXRecordDecl *Base,
3058                                    const ASTRecordLayout *RL = nullptr) {
3059   if (!RL) {
3060     if (Derived->isInvalidDecl()) return false;
3061     RL = &Info.Ctx.getASTRecordLayout(Derived);
3062   }
3063 
3064   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3065   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3066   return true;
3067 }
3068 
3069 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3070                              const CXXRecordDecl *DerivedDecl,
3071                              const CXXBaseSpecifier *Base) {
3072   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3073 
3074   if (!Base->isVirtual())
3075     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3076 
3077   SubobjectDesignator &D = Obj.Designator;
3078   if (D.Invalid)
3079     return false;
3080 
3081   // Extract most-derived object and corresponding type.
3082   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3083   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3084     return false;
3085 
3086   // Find the virtual base class.
3087   if (DerivedDecl->isInvalidDecl()) return false;
3088   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3089   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3090   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3091   return true;
3092 }
3093 
3094 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3095                                  QualType Type, LValue &Result) {
3096   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3097                                      PathE = E->path_end();
3098        PathI != PathE; ++PathI) {
3099     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3100                           *PathI))
3101       return false;
3102     Type = (*PathI)->getType();
3103   }
3104   return true;
3105 }
3106 
3107 /// Cast an lvalue referring to a derived class to a known base subobject.
3108 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3109                             const CXXRecordDecl *DerivedRD,
3110                             const CXXRecordDecl *BaseRD) {
3111   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3112                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3113   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3114     llvm_unreachable("Class must be derived from the passed in base class!");
3115 
3116   for (CXXBasePathElement &Elem : Paths.front())
3117     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3118       return false;
3119   return true;
3120 }
3121 
3122 /// Update LVal to refer to the given field, which must be a member of the type
3123 /// currently described by LVal.
3124 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3125                                const FieldDecl *FD,
3126                                const ASTRecordLayout *RL = nullptr) {
3127   if (!RL) {
3128     if (FD->getParent()->isInvalidDecl()) return false;
3129     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3130   }
3131 
3132   unsigned I = FD->getFieldIndex();
3133   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3134   LVal.addDecl(Info, E, FD);
3135   return true;
3136 }
3137 
3138 /// Update LVal to refer to the given indirect field.
3139 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3140                                        LValue &LVal,
3141                                        const IndirectFieldDecl *IFD) {
3142   for (const auto *C : IFD->chain())
3143     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3144       return false;
3145   return true;
3146 }
3147 
3148 /// Get the size of the given type in char units.
3149 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3150                          QualType Type, CharUnits &Size) {
3151   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3152   // extension.
3153   if (Type->isVoidType() || Type->isFunctionType()) {
3154     Size = CharUnits::One();
3155     return true;
3156   }
3157 
3158   if (Type->isDependentType()) {
3159     Info.FFDiag(Loc);
3160     return false;
3161   }
3162 
3163   if (!Type->isConstantSizeType()) {
3164     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3165     // FIXME: Better diagnostic.
3166     Info.FFDiag(Loc);
3167     return false;
3168   }
3169 
3170   Size = Info.Ctx.getTypeSizeInChars(Type);
3171   return true;
3172 }
3173 
3174 /// Update a pointer value to model pointer arithmetic.
3175 /// \param Info - Information about the ongoing evaluation.
3176 /// \param E - The expression being evaluated, for diagnostic purposes.
3177 /// \param LVal - The pointer value to be updated.
3178 /// \param EltTy - The pointee type represented by LVal.
3179 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3180 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3181                                         LValue &LVal, QualType EltTy,
3182                                         APSInt Adjustment) {
3183   CharUnits SizeOfPointee;
3184   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3185     return false;
3186 
3187   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3188   return true;
3189 }
3190 
3191 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3192                                         LValue &LVal, QualType EltTy,
3193                                         int64_t Adjustment) {
3194   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3195                                      APSInt::get(Adjustment));
3196 }
3197 
3198 /// Update an lvalue to refer to a component of a complex number.
3199 /// \param Info - Information about the ongoing evaluation.
3200 /// \param LVal - The lvalue to be updated.
3201 /// \param EltTy - The complex number's component type.
3202 /// \param Imag - False for the real component, true for the imaginary.
3203 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3204                                        LValue &LVal, QualType EltTy,
3205                                        bool Imag) {
3206   if (Imag) {
3207     CharUnits SizeOfComponent;
3208     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3209       return false;
3210     LVal.Offset += SizeOfComponent;
3211   }
3212   LVal.addComplex(Info, E, EltTy, Imag);
3213   return true;
3214 }
3215 
3216 /// Try to evaluate the initializer for a variable declaration.
3217 ///
3218 /// \param Info   Information about the ongoing evaluation.
3219 /// \param E      An expression to be used when printing diagnostics.
3220 /// \param VD     The variable whose initializer should be obtained.
3221 /// \param Version The version of the variable within the frame.
3222 /// \param Frame  The frame in which the variable was created. Must be null
3223 ///               if this variable is not local to the evaluation.
3224 /// \param Result Filled in with a pointer to the value of the variable.
3225 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3226                                 const VarDecl *VD, CallStackFrame *Frame,
3227                                 unsigned Version, APValue *&Result) {
3228   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3229 
3230   // If this is a local variable, dig out its value.
3231   if (Frame) {
3232     Result = Frame->getTemporary(VD, Version);
3233     if (Result)
3234       return true;
3235 
3236     if (!isa<ParmVarDecl>(VD)) {
3237       // Assume variables referenced within a lambda's call operator that were
3238       // not declared within the call operator are captures and during checking
3239       // of a potential constant expression, assume they are unknown constant
3240       // expressions.
3241       assert(isLambdaCallOperator(Frame->Callee) &&
3242              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3243              "missing value for local variable");
3244       if (Info.checkingPotentialConstantExpression())
3245         return false;
3246       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3247       // still reachable at all?
3248       Info.FFDiag(E->getBeginLoc(),
3249                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3250           << "captures not currently allowed";
3251       return false;
3252     }
3253   }
3254 
3255   // If we're currently evaluating the initializer of this declaration, use that
3256   // in-flight value.
3257   if (Info.EvaluatingDecl == Base) {
3258     Result = Info.EvaluatingDeclValue;
3259     return true;
3260   }
3261 
3262   if (isa<ParmVarDecl>(VD)) {
3263     // Assume parameters of a potential constant expression are usable in
3264     // constant expressions.
3265     if (!Info.checkingPotentialConstantExpression() ||
3266         !Info.CurrentCall->Callee ||
3267         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3268       if (Info.getLangOpts().CPlusPlus11) {
3269         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3270             << VD;
3271         NoteLValueLocation(Info, Base);
3272       } else {
3273         Info.FFDiag(E);
3274       }
3275     }
3276     return false;
3277   }
3278 
3279   // Dig out the initializer, and use the declaration which it's attached to.
3280   // FIXME: We should eventually check whether the variable has a reachable
3281   // initializing declaration.
3282   const Expr *Init = VD->getAnyInitializer(VD);
3283   if (!Init) {
3284     // Don't diagnose during potential constant expression checking; an
3285     // initializer might be added later.
3286     if (!Info.checkingPotentialConstantExpression()) {
3287       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3288         << VD;
3289       NoteLValueLocation(Info, Base);
3290     }
3291     return false;
3292   }
3293 
3294   if (Init->isValueDependent()) {
3295     // The DeclRefExpr is not value-dependent, but the variable it refers to
3296     // has a value-dependent initializer. This should only happen in
3297     // constant-folding cases, where the variable is not actually of a suitable
3298     // type for use in a constant expression (otherwise the DeclRefExpr would
3299     // have been value-dependent too), so diagnose that.
3300     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3301     if (!Info.checkingPotentialConstantExpression()) {
3302       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3303                          ? diag::note_constexpr_ltor_non_constexpr
3304                          : diag::note_constexpr_ltor_non_integral, 1)
3305           << VD << VD->getType();
3306       NoteLValueLocation(Info, Base);
3307     }
3308     return false;
3309   }
3310 
3311   // Check that we can fold the initializer. In C++, we will have already done
3312   // this in the cases where it matters for conformance.
3313   if (!VD->evaluateValue()) {
3314     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3315     NoteLValueLocation(Info, Base);
3316     return false;
3317   }
3318 
3319   // Check that the variable is actually usable in constant expressions. For a
3320   // const integral variable or a reference, we might have a non-constant
3321   // initializer that we can nonetheless evaluate the initializer for. Such
3322   // variables are not usable in constant expressions. In C++98, the
3323   // initializer also syntactically needs to be an ICE.
3324   //
3325   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3326   // expressions here; doing so would regress diagnostics for things like
3327   // reading from a volatile constexpr variable.
3328   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3329        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3330       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3331        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3332     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3333     NoteLValueLocation(Info, Base);
3334   }
3335 
3336   // Never use the initializer of a weak variable, not even for constant
3337   // folding. We can't be sure that this is the definition that will be used.
3338   if (VD->isWeak()) {
3339     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3340     NoteLValueLocation(Info, Base);
3341     return false;
3342   }
3343 
3344   Result = VD->getEvaluatedValue();
3345   return true;
3346 }
3347 
3348 /// Get the base index of the given base class within an APValue representing
3349 /// the given derived class.
3350 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3351                              const CXXRecordDecl *Base) {
3352   Base = Base->getCanonicalDecl();
3353   unsigned Index = 0;
3354   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3355          E = Derived->bases_end(); I != E; ++I, ++Index) {
3356     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3357       return Index;
3358   }
3359 
3360   llvm_unreachable("base class missing from derived class's bases list");
3361 }
3362 
3363 /// Extract the value of a character from a string literal.
3364 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3365                                             uint64_t Index) {
3366   assert(!isa<SourceLocExpr>(Lit) &&
3367          "SourceLocExpr should have already been converted to a StringLiteral");
3368 
3369   // FIXME: Support MakeStringConstant
3370   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3371     std::string Str;
3372     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3373     assert(Index <= Str.size() && "Index too large");
3374     return APSInt::getUnsigned(Str.c_str()[Index]);
3375   }
3376 
3377   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3378     Lit = PE->getFunctionName();
3379   const StringLiteral *S = cast<StringLiteral>(Lit);
3380   const ConstantArrayType *CAT =
3381       Info.Ctx.getAsConstantArrayType(S->getType());
3382   assert(CAT && "string literal isn't an array");
3383   QualType CharType = CAT->getElementType();
3384   assert(CharType->isIntegerType() && "unexpected character type");
3385 
3386   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3387                CharType->isUnsignedIntegerType());
3388   if (Index < S->getLength())
3389     Value = S->getCodeUnit(Index);
3390   return Value;
3391 }
3392 
3393 // Expand a string literal into an array of characters.
3394 //
3395 // FIXME: This is inefficient; we should probably introduce something similar
3396 // to the LLVM ConstantDataArray to make this cheaper.
3397 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3398                                 APValue &Result,
3399                                 QualType AllocType = QualType()) {
3400   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3401       AllocType.isNull() ? S->getType() : AllocType);
3402   assert(CAT && "string literal isn't an array");
3403   QualType CharType = CAT->getElementType();
3404   assert(CharType->isIntegerType() && "unexpected character type");
3405 
3406   unsigned Elts = CAT->getSize().getZExtValue();
3407   Result = APValue(APValue::UninitArray(),
3408                    std::min(S->getLength(), Elts), Elts);
3409   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3410                CharType->isUnsignedIntegerType());
3411   if (Result.hasArrayFiller())
3412     Result.getArrayFiller() = APValue(Value);
3413   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3414     Value = S->getCodeUnit(I);
3415     Result.getArrayInitializedElt(I) = APValue(Value);
3416   }
3417 }
3418 
3419 // Expand an array so that it has more than Index filled elements.
3420 static void expandArray(APValue &Array, unsigned Index) {
3421   unsigned Size = Array.getArraySize();
3422   assert(Index < Size);
3423 
3424   // Always at least double the number of elements for which we store a value.
3425   unsigned OldElts = Array.getArrayInitializedElts();
3426   unsigned NewElts = std::max(Index+1, OldElts * 2);
3427   NewElts = std::min(Size, std::max(NewElts, 8u));
3428 
3429   // Copy the data across.
3430   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3431   for (unsigned I = 0; I != OldElts; ++I)
3432     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3433   for (unsigned I = OldElts; I != NewElts; ++I)
3434     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3435   if (NewValue.hasArrayFiller())
3436     NewValue.getArrayFiller() = Array.getArrayFiller();
3437   Array.swap(NewValue);
3438 }
3439 
3440 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3441 /// conversion. If it's of class type, we may assume that the copy operation
3442 /// is trivial. Note that this is never true for a union type with fields
3443 /// (because the copy always "reads" the active member) and always true for
3444 /// a non-class type.
3445 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3446 static bool isReadByLvalueToRvalueConversion(QualType T) {
3447   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3448   return !RD || isReadByLvalueToRvalueConversion(RD);
3449 }
3450 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3451   // FIXME: A trivial copy of a union copies the object representation, even if
3452   // the union is empty.
3453   if (RD->isUnion())
3454     return !RD->field_empty();
3455   if (RD->isEmpty())
3456     return false;
3457 
3458   for (auto *Field : RD->fields())
3459     if (!Field->isUnnamedBitfield() &&
3460         isReadByLvalueToRvalueConversion(Field->getType()))
3461       return true;
3462 
3463   for (auto &BaseSpec : RD->bases())
3464     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3465       return true;
3466 
3467   return false;
3468 }
3469 
3470 /// Diagnose an attempt to read from any unreadable field within the specified
3471 /// type, which might be a class type.
3472 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3473                                   QualType T) {
3474   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3475   if (!RD)
3476     return false;
3477 
3478   if (!RD->hasMutableFields())
3479     return false;
3480 
3481   for (auto *Field : RD->fields()) {
3482     // If we're actually going to read this field in some way, then it can't
3483     // be mutable. If we're in a union, then assigning to a mutable field
3484     // (even an empty one) can change the active member, so that's not OK.
3485     // FIXME: Add core issue number for the union case.
3486     if (Field->isMutable() &&
3487         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3488       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3489       Info.Note(Field->getLocation(), diag::note_declared_at);
3490       return true;
3491     }
3492 
3493     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3494       return true;
3495   }
3496 
3497   for (auto &BaseSpec : RD->bases())
3498     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3499       return true;
3500 
3501   // All mutable fields were empty, and thus not actually read.
3502   return false;
3503 }
3504 
3505 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3506                                         APValue::LValueBase Base,
3507                                         bool MutableSubobject = false) {
3508   // A temporary or transient heap allocation we created.
3509   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3510     return true;
3511 
3512   switch (Info.IsEvaluatingDecl) {
3513   case EvalInfo::EvaluatingDeclKind::None:
3514     return false;
3515 
3516   case EvalInfo::EvaluatingDeclKind::Ctor:
3517     // The variable whose initializer we're evaluating.
3518     if (Info.EvaluatingDecl == Base)
3519       return true;
3520 
3521     // A temporary lifetime-extended by the variable whose initializer we're
3522     // evaluating.
3523     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3524       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3525         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3526     return false;
3527 
3528   case EvalInfo::EvaluatingDeclKind::Dtor:
3529     // C++2a [expr.const]p6:
3530     //   [during constant destruction] the lifetime of a and its non-mutable
3531     //   subobjects (but not its mutable subobjects) [are] considered to start
3532     //   within e.
3533     if (MutableSubobject || Base != Info.EvaluatingDecl)
3534       return false;
3535     // FIXME: We can meaningfully extend this to cover non-const objects, but
3536     // we will need special handling: we should be able to access only
3537     // subobjects of such objects that are themselves declared const.
3538     QualType T = getType(Base);
3539     return T.isConstQualified() || T->isReferenceType();
3540   }
3541 
3542   llvm_unreachable("unknown evaluating decl kind");
3543 }
3544 
3545 namespace {
3546 /// A handle to a complete object (an object that is not a subobject of
3547 /// another object).
3548 struct CompleteObject {
3549   /// The identity of the object.
3550   APValue::LValueBase Base;
3551   /// The value of the complete object.
3552   APValue *Value;
3553   /// The type of the complete object.
3554   QualType Type;
3555 
3556   CompleteObject() : Value(nullptr) {}
3557   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3558       : Base(Base), Value(Value), Type(Type) {}
3559 
3560   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3561     // If this isn't a "real" access (eg, if it's just accessing the type
3562     // info), allow it. We assume the type doesn't change dynamically for
3563     // subobjects of constexpr objects (even though we'd hit UB here if it
3564     // did). FIXME: Is this right?
3565     if (!isAnyAccess(AK))
3566       return true;
3567 
3568     // In C++14 onwards, it is permitted to read a mutable member whose
3569     // lifetime began within the evaluation.
3570     // FIXME: Should we also allow this in C++11?
3571     if (!Info.getLangOpts().CPlusPlus14)
3572       return false;
3573     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3574   }
3575 
3576   explicit operator bool() const { return !Type.isNull(); }
3577 };
3578 } // end anonymous namespace
3579 
3580 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3581                                  bool IsMutable = false) {
3582   // C++ [basic.type.qualifier]p1:
3583   // - A const object is an object of type const T or a non-mutable subobject
3584   //   of a const object.
3585   if (ObjType.isConstQualified() && !IsMutable)
3586     SubobjType.addConst();
3587   // - A volatile object is an object of type const T or a subobject of a
3588   //   volatile object.
3589   if (ObjType.isVolatileQualified())
3590     SubobjType.addVolatile();
3591   return SubobjType;
3592 }
3593 
3594 /// Find the designated sub-object of an rvalue.
3595 template<typename SubobjectHandler>
3596 typename SubobjectHandler::result_type
3597 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3598               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3599   if (Sub.Invalid)
3600     // A diagnostic will have already been produced.
3601     return handler.failed();
3602   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3603     if (Info.getLangOpts().CPlusPlus11)
3604       Info.FFDiag(E, Sub.isOnePastTheEnd()
3605                          ? diag::note_constexpr_access_past_end
3606                          : diag::note_constexpr_access_unsized_array)
3607           << handler.AccessKind;
3608     else
3609       Info.FFDiag(E);
3610     return handler.failed();
3611   }
3612 
3613   APValue *O = Obj.Value;
3614   QualType ObjType = Obj.Type;
3615   const FieldDecl *LastField = nullptr;
3616   const FieldDecl *VolatileField = nullptr;
3617 
3618   // Walk the designator's path to find the subobject.
3619   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3620     // Reading an indeterminate value is undefined, but assigning over one is OK.
3621     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3622         (O->isIndeterminate() &&
3623          !isValidIndeterminateAccess(handler.AccessKind))) {
3624       if (!Info.checkingPotentialConstantExpression())
3625         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3626             << handler.AccessKind << O->isIndeterminate();
3627       return handler.failed();
3628     }
3629 
3630     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3631     //    const and volatile semantics are not applied on an object under
3632     //    {con,de}struction.
3633     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3634         ObjType->isRecordType() &&
3635         Info.isEvaluatingCtorDtor(
3636             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3637                                          Sub.Entries.begin() + I)) !=
3638                           ConstructionPhase::None) {
3639       ObjType = Info.Ctx.getCanonicalType(ObjType);
3640       ObjType.removeLocalConst();
3641       ObjType.removeLocalVolatile();
3642     }
3643 
3644     // If this is our last pass, check that the final object type is OK.
3645     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3646       // Accesses to volatile objects are prohibited.
3647       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3648         if (Info.getLangOpts().CPlusPlus) {
3649           int DiagKind;
3650           SourceLocation Loc;
3651           const NamedDecl *Decl = nullptr;
3652           if (VolatileField) {
3653             DiagKind = 2;
3654             Loc = VolatileField->getLocation();
3655             Decl = VolatileField;
3656           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3657             DiagKind = 1;
3658             Loc = VD->getLocation();
3659             Decl = VD;
3660           } else {
3661             DiagKind = 0;
3662             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3663               Loc = E->getExprLoc();
3664           }
3665           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3666               << handler.AccessKind << DiagKind << Decl;
3667           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3668         } else {
3669           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3670         }
3671         return handler.failed();
3672       }
3673 
3674       // If we are reading an object of class type, there may still be more
3675       // things we need to check: if there are any mutable subobjects, we
3676       // cannot perform this read. (This only happens when performing a trivial
3677       // copy or assignment.)
3678       if (ObjType->isRecordType() &&
3679           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3680           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3681         return handler.failed();
3682     }
3683 
3684     if (I == N) {
3685       if (!handler.found(*O, ObjType))
3686         return false;
3687 
3688       // If we modified a bit-field, truncate it to the right width.
3689       if (isModification(handler.AccessKind) &&
3690           LastField && LastField->isBitField() &&
3691           !truncateBitfieldValue(Info, E, *O, LastField))
3692         return false;
3693 
3694       return true;
3695     }
3696 
3697     LastField = nullptr;
3698     if (ObjType->isArrayType()) {
3699       // Next subobject is an array element.
3700       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3701       assert(CAT && "vla in literal type?");
3702       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3703       if (CAT->getSize().ule(Index)) {
3704         // Note, it should not be possible to form a pointer with a valid
3705         // designator which points more than one past the end of the array.
3706         if (Info.getLangOpts().CPlusPlus11)
3707           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3708             << handler.AccessKind;
3709         else
3710           Info.FFDiag(E);
3711         return handler.failed();
3712       }
3713 
3714       ObjType = CAT->getElementType();
3715 
3716       if (O->getArrayInitializedElts() > Index)
3717         O = &O->getArrayInitializedElt(Index);
3718       else if (!isRead(handler.AccessKind)) {
3719         expandArray(*O, Index);
3720         O = &O->getArrayInitializedElt(Index);
3721       } else
3722         O = &O->getArrayFiller();
3723     } else if (ObjType->isAnyComplexType()) {
3724       // Next subobject is a complex number.
3725       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3726       if (Index > 1) {
3727         if (Info.getLangOpts().CPlusPlus11)
3728           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3729             << handler.AccessKind;
3730         else
3731           Info.FFDiag(E);
3732         return handler.failed();
3733       }
3734 
3735       ObjType = getSubobjectType(
3736           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3737 
3738       assert(I == N - 1 && "extracting subobject of scalar?");
3739       if (O->isComplexInt()) {
3740         return handler.found(Index ? O->getComplexIntImag()
3741                                    : O->getComplexIntReal(), ObjType);
3742       } else {
3743         assert(O->isComplexFloat());
3744         return handler.found(Index ? O->getComplexFloatImag()
3745                                    : O->getComplexFloatReal(), ObjType);
3746       }
3747     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3748       if (Field->isMutable() &&
3749           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3750         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3751           << handler.AccessKind << Field;
3752         Info.Note(Field->getLocation(), diag::note_declared_at);
3753         return handler.failed();
3754       }
3755 
3756       // Next subobject is a class, struct or union field.
3757       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3758       if (RD->isUnion()) {
3759         const FieldDecl *UnionField = O->getUnionField();
3760         if (!UnionField ||
3761             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3762           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3763             // Placement new onto an inactive union member makes it active.
3764             O->setUnion(Field, APValue());
3765           } else {
3766             // FIXME: If O->getUnionValue() is absent, report that there's no
3767             // active union member rather than reporting the prior active union
3768             // member. We'll need to fix nullptr_t to not use APValue() as its
3769             // representation first.
3770             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3771                 << handler.AccessKind << Field << !UnionField << UnionField;
3772             return handler.failed();
3773           }
3774         }
3775         O = &O->getUnionValue();
3776       } else
3777         O = &O->getStructField(Field->getFieldIndex());
3778 
3779       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3780       LastField = Field;
3781       if (Field->getType().isVolatileQualified())
3782         VolatileField = Field;
3783     } else {
3784       // Next subobject is a base class.
3785       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3786       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3787       O = &O->getStructBase(getBaseIndex(Derived, Base));
3788 
3789       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3790     }
3791   }
3792 }
3793 
3794 namespace {
3795 struct ExtractSubobjectHandler {
3796   EvalInfo &Info;
3797   const Expr *E;
3798   APValue &Result;
3799   const AccessKinds AccessKind;
3800 
3801   typedef bool result_type;
3802   bool failed() { return false; }
3803   bool found(APValue &Subobj, QualType SubobjType) {
3804     Result = Subobj;
3805     if (AccessKind == AK_ReadObjectRepresentation)
3806       return true;
3807     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3808   }
3809   bool found(APSInt &Value, QualType SubobjType) {
3810     Result = APValue(Value);
3811     return true;
3812   }
3813   bool found(APFloat &Value, QualType SubobjType) {
3814     Result = APValue(Value);
3815     return true;
3816   }
3817 };
3818 } // end anonymous namespace
3819 
3820 /// Extract the designated sub-object of an rvalue.
3821 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3822                              const CompleteObject &Obj,
3823                              const SubobjectDesignator &Sub, APValue &Result,
3824                              AccessKinds AK = AK_Read) {
3825   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3826   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3827   return findSubobject(Info, E, Obj, Sub, Handler);
3828 }
3829 
3830 namespace {
3831 struct ModifySubobjectHandler {
3832   EvalInfo &Info;
3833   APValue &NewVal;
3834   const Expr *E;
3835 
3836   typedef bool result_type;
3837   static const AccessKinds AccessKind = AK_Assign;
3838 
3839   bool checkConst(QualType QT) {
3840     // Assigning to a const object has undefined behavior.
3841     if (QT.isConstQualified()) {
3842       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3843       return false;
3844     }
3845     return true;
3846   }
3847 
3848   bool failed() { return false; }
3849   bool found(APValue &Subobj, QualType SubobjType) {
3850     if (!checkConst(SubobjType))
3851       return false;
3852     // We've been given ownership of NewVal, so just swap it in.
3853     Subobj.swap(NewVal);
3854     return true;
3855   }
3856   bool found(APSInt &Value, QualType SubobjType) {
3857     if (!checkConst(SubobjType))
3858       return false;
3859     if (!NewVal.isInt()) {
3860       // Maybe trying to write a cast pointer value into a complex?
3861       Info.FFDiag(E);
3862       return false;
3863     }
3864     Value = NewVal.getInt();
3865     return true;
3866   }
3867   bool found(APFloat &Value, QualType SubobjType) {
3868     if (!checkConst(SubobjType))
3869       return false;
3870     Value = NewVal.getFloat();
3871     return true;
3872   }
3873 };
3874 } // end anonymous namespace
3875 
3876 const AccessKinds ModifySubobjectHandler::AccessKind;
3877 
3878 /// Update the designated sub-object of an rvalue to the given value.
3879 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3880                             const CompleteObject &Obj,
3881                             const SubobjectDesignator &Sub,
3882                             APValue &NewVal) {
3883   ModifySubobjectHandler Handler = { Info, NewVal, E };
3884   return findSubobject(Info, E, Obj, Sub, Handler);
3885 }
3886 
3887 /// Find the position where two subobject designators diverge, or equivalently
3888 /// the length of the common initial subsequence.
3889 static unsigned FindDesignatorMismatch(QualType ObjType,
3890                                        const SubobjectDesignator &A,
3891                                        const SubobjectDesignator &B,
3892                                        bool &WasArrayIndex) {
3893   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3894   for (/**/; I != N; ++I) {
3895     if (!ObjType.isNull() &&
3896         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3897       // Next subobject is an array element.
3898       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3899         WasArrayIndex = true;
3900         return I;
3901       }
3902       if (ObjType->isAnyComplexType())
3903         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3904       else
3905         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3906     } else {
3907       if (A.Entries[I].getAsBaseOrMember() !=
3908           B.Entries[I].getAsBaseOrMember()) {
3909         WasArrayIndex = false;
3910         return I;
3911       }
3912       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3913         // Next subobject is a field.
3914         ObjType = FD->getType();
3915       else
3916         // Next subobject is a base class.
3917         ObjType = QualType();
3918     }
3919   }
3920   WasArrayIndex = false;
3921   return I;
3922 }
3923 
3924 /// Determine whether the given subobject designators refer to elements of the
3925 /// same array object.
3926 static bool AreElementsOfSameArray(QualType ObjType,
3927                                    const SubobjectDesignator &A,
3928                                    const SubobjectDesignator &B) {
3929   if (A.Entries.size() != B.Entries.size())
3930     return false;
3931 
3932   bool IsArray = A.MostDerivedIsArrayElement;
3933   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3934     // A is a subobject of the array element.
3935     return false;
3936 
3937   // If A (and B) designates an array element, the last entry will be the array
3938   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3939   // of length 1' case, and the entire path must match.
3940   bool WasArrayIndex;
3941   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3942   return CommonLength >= A.Entries.size() - IsArray;
3943 }
3944 
3945 /// Find the complete object to which an LValue refers.
3946 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3947                                          AccessKinds AK, const LValue &LVal,
3948                                          QualType LValType) {
3949   if (LVal.InvalidBase) {
3950     Info.FFDiag(E);
3951     return CompleteObject();
3952   }
3953 
3954   if (!LVal.Base) {
3955     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3956     return CompleteObject();
3957   }
3958 
3959   CallStackFrame *Frame = nullptr;
3960   unsigned Depth = 0;
3961   if (LVal.getLValueCallIndex()) {
3962     std::tie(Frame, Depth) =
3963         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3964     if (!Frame) {
3965       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3966         << AK << LVal.Base.is<const ValueDecl*>();
3967       NoteLValueLocation(Info, LVal.Base);
3968       return CompleteObject();
3969     }
3970   }
3971 
3972   bool IsAccess = isAnyAccess(AK);
3973 
3974   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3975   // is not a constant expression (even if the object is non-volatile). We also
3976   // apply this rule to C++98, in order to conform to the expected 'volatile'
3977   // semantics.
3978   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3979     if (Info.getLangOpts().CPlusPlus)
3980       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3981         << AK << LValType;
3982     else
3983       Info.FFDiag(E);
3984     return CompleteObject();
3985   }
3986 
3987   // Compute value storage location and type of base object.
3988   APValue *BaseVal = nullptr;
3989   QualType BaseType = getType(LVal.Base);
3990 
3991   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3992       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3993     // This is the object whose initializer we're evaluating, so its lifetime
3994     // started in the current evaluation.
3995     BaseVal = Info.EvaluatingDeclValue;
3996   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3997     // Allow reading from a GUID declaration.
3998     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3999       if (isModification(AK)) {
4000         // All the remaining cases do not permit modification of the object.
4001         Info.FFDiag(E, diag::note_constexpr_modify_global);
4002         return CompleteObject();
4003       }
4004       APValue &V = GD->getAsAPValue();
4005       if (V.isAbsent()) {
4006         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4007             << GD->getType();
4008         return CompleteObject();
4009       }
4010       return CompleteObject(LVal.Base, &V, GD->getType());
4011     }
4012 
4013     // Allow reading from template parameter objects.
4014     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4015       if (isModification(AK)) {
4016         Info.FFDiag(E, diag::note_constexpr_modify_global);
4017         return CompleteObject();
4018       }
4019       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4020                             TPO->getType());
4021     }
4022 
4023     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4024     // In C++11, constexpr, non-volatile variables initialized with constant
4025     // expressions are constant expressions too. Inside constexpr functions,
4026     // parameters are constant expressions even if they're non-const.
4027     // In C++1y, objects local to a constant expression (those with a Frame) are
4028     // both readable and writable inside constant expressions.
4029     // In C, such things can also be folded, although they are not ICEs.
4030     const VarDecl *VD = dyn_cast<VarDecl>(D);
4031     if (VD) {
4032       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4033         VD = VDef;
4034     }
4035     if (!VD || VD->isInvalidDecl()) {
4036       Info.FFDiag(E);
4037       return CompleteObject();
4038     }
4039 
4040     bool IsConstant = BaseType.isConstant(Info.Ctx);
4041 
4042     // Unless we're looking at a local variable or argument in a constexpr call,
4043     // the variable we're reading must be const.
4044     if (!Frame) {
4045       if (IsAccess && isa<ParmVarDecl>(VD)) {
4046         // Access of a parameter that's not associated with a frame isn't going
4047         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4048         // suitable diagnostic.
4049       } else if (Info.getLangOpts().CPlusPlus14 &&
4050                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4051         // OK, we can read and modify an object if we're in the process of
4052         // evaluating its initializer, because its lifetime began in this
4053         // evaluation.
4054       } else if (isModification(AK)) {
4055         // All the remaining cases do not permit modification of the object.
4056         Info.FFDiag(E, diag::note_constexpr_modify_global);
4057         return CompleteObject();
4058       } else if (VD->isConstexpr()) {
4059         // OK, we can read this variable.
4060       } else if (BaseType->isIntegralOrEnumerationType()) {
4061         if (!IsConstant) {
4062           if (!IsAccess)
4063             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4064           if (Info.getLangOpts().CPlusPlus) {
4065             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4066             Info.Note(VD->getLocation(), diag::note_declared_at);
4067           } else {
4068             Info.FFDiag(E);
4069           }
4070           return CompleteObject();
4071         }
4072       } else if (!IsAccess) {
4073         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4074       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4075                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4076         // This variable might end up being constexpr. Don't diagnose it yet.
4077       } else if (IsConstant) {
4078         // Keep evaluating to see what we can do. In particular, we support
4079         // folding of const floating-point types, in order to make static const
4080         // data members of such types (supported as an extension) more useful.
4081         if (Info.getLangOpts().CPlusPlus) {
4082           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4083                               ? diag::note_constexpr_ltor_non_constexpr
4084                               : diag::note_constexpr_ltor_non_integral, 1)
4085               << VD << BaseType;
4086           Info.Note(VD->getLocation(), diag::note_declared_at);
4087         } else {
4088           Info.CCEDiag(E);
4089         }
4090       } else {
4091         // Never allow reading a non-const value.
4092         if (Info.getLangOpts().CPlusPlus) {
4093           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4094                              ? diag::note_constexpr_ltor_non_constexpr
4095                              : diag::note_constexpr_ltor_non_integral, 1)
4096               << VD << BaseType;
4097           Info.Note(VD->getLocation(), diag::note_declared_at);
4098         } else {
4099           Info.FFDiag(E);
4100         }
4101         return CompleteObject();
4102       }
4103     }
4104 
4105     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4106       return CompleteObject();
4107   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4108     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4109     if (!Alloc) {
4110       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4111       return CompleteObject();
4112     }
4113     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4114                           LVal.Base.getDynamicAllocType());
4115   } else {
4116     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4117 
4118     if (!Frame) {
4119       if (const MaterializeTemporaryExpr *MTE =
4120               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4121         assert(MTE->getStorageDuration() == SD_Static &&
4122                "should have a frame for a non-global materialized temporary");
4123 
4124         // C++20 [expr.const]p4: [DR2126]
4125         //   An object or reference is usable in constant expressions if it is
4126         //   - a temporary object of non-volatile const-qualified literal type
4127         //     whose lifetime is extended to that of a variable that is usable
4128         //     in constant expressions
4129         //
4130         // C++20 [expr.const]p5:
4131         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4132         //   - a non-volatile glvalue that refers to an object that is usable
4133         //     in constant expressions, or
4134         //   - a non-volatile glvalue of literal type that refers to a
4135         //     non-volatile object whose lifetime began within the evaluation
4136         //     of E;
4137         //
4138         // C++11 misses the 'began within the evaluation of e' check and
4139         // instead allows all temporaries, including things like:
4140         //   int &&r = 1;
4141         //   int x = ++r;
4142         //   constexpr int k = r;
4143         // Therefore we use the C++14-onwards rules in C++11 too.
4144         //
4145         // Note that temporaries whose lifetimes began while evaluating a
4146         // variable's constructor are not usable while evaluating the
4147         // corresponding destructor, not even if they're of const-qualified
4148         // types.
4149         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4150             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4151           if (!IsAccess)
4152             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4153           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4154           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4155           return CompleteObject();
4156         }
4157 
4158         BaseVal = MTE->getOrCreateValue(false);
4159         assert(BaseVal && "got reference to unevaluated temporary");
4160       } else {
4161         if (!IsAccess)
4162           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4163         APValue Val;
4164         LVal.moveInto(Val);
4165         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4166             << AK
4167             << Val.getAsString(Info.Ctx,
4168                                Info.Ctx.getLValueReferenceType(LValType));
4169         NoteLValueLocation(Info, LVal.Base);
4170         return CompleteObject();
4171       }
4172     } else {
4173       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4174       assert(BaseVal && "missing value for temporary");
4175     }
4176   }
4177 
4178   // In C++14, we can't safely access any mutable state when we might be
4179   // evaluating after an unmodeled side effect. Parameters are modeled as state
4180   // in the caller, but aren't visible once the call returns, so they can be
4181   // modified in a speculatively-evaluated call.
4182   //
4183   // FIXME: Not all local state is mutable. Allow local constant subobjects
4184   // to be read here (but take care with 'mutable' fields).
4185   unsigned VisibleDepth = Depth;
4186   if (llvm::isa_and_nonnull<ParmVarDecl>(
4187           LVal.Base.dyn_cast<const ValueDecl *>()))
4188     ++VisibleDepth;
4189   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4190        Info.EvalStatus.HasSideEffects) ||
4191       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4192     return CompleteObject();
4193 
4194   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4195 }
4196 
4197 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4198 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4199 /// glvalue referred to by an entity of reference type.
4200 ///
4201 /// \param Info - Information about the ongoing evaluation.
4202 /// \param Conv - The expression for which we are performing the conversion.
4203 ///               Used for diagnostics.
4204 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4205 ///               case of a non-class type).
4206 /// \param LVal - The glvalue on which we are attempting to perform this action.
4207 /// \param RVal - The produced value will be placed here.
4208 /// \param WantObjectRepresentation - If true, we're looking for the object
4209 ///               representation rather than the value, and in particular,
4210 ///               there is no requirement that the result be fully initialized.
4211 static bool
4212 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4213                                const LValue &LVal, APValue &RVal,
4214                                bool WantObjectRepresentation = false) {
4215   if (LVal.Designator.Invalid)
4216     return false;
4217 
4218   // Check for special cases where there is no existing APValue to look at.
4219   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4220 
4221   AccessKinds AK =
4222       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4223 
4224   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4225     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4226       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4227       // initializer until now for such expressions. Such an expression can't be
4228       // an ICE in C, so this only matters for fold.
4229       if (Type.isVolatileQualified()) {
4230         Info.FFDiag(Conv);
4231         return false;
4232       }
4233       APValue Lit;
4234       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4235         return false;
4236       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4237       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4238     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4239       // Special-case character extraction so we don't have to construct an
4240       // APValue for the whole string.
4241       assert(LVal.Designator.Entries.size() <= 1 &&
4242              "Can only read characters from string literals");
4243       if (LVal.Designator.Entries.empty()) {
4244         // Fail for now for LValue to RValue conversion of an array.
4245         // (This shouldn't show up in C/C++, but it could be triggered by a
4246         // weird EvaluateAsRValue call from a tool.)
4247         Info.FFDiag(Conv);
4248         return false;
4249       }
4250       if (LVal.Designator.isOnePastTheEnd()) {
4251         if (Info.getLangOpts().CPlusPlus11)
4252           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4253         else
4254           Info.FFDiag(Conv);
4255         return false;
4256       }
4257       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4258       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4259       return true;
4260     }
4261   }
4262 
4263   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4264   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4265 }
4266 
4267 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4268 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4269                              QualType LValType, APValue &Val) {
4270   if (LVal.Designator.Invalid)
4271     return false;
4272 
4273   if (!Info.getLangOpts().CPlusPlus14) {
4274     Info.FFDiag(E);
4275     return false;
4276   }
4277 
4278   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4279   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4280 }
4281 
4282 namespace {
4283 struct CompoundAssignSubobjectHandler {
4284   EvalInfo &Info;
4285   const CompoundAssignOperator *E;
4286   QualType PromotedLHSType;
4287   BinaryOperatorKind Opcode;
4288   const APValue &RHS;
4289 
4290   static const AccessKinds AccessKind = AK_Assign;
4291 
4292   typedef bool result_type;
4293 
4294   bool checkConst(QualType QT) {
4295     // Assigning to a const object has undefined behavior.
4296     if (QT.isConstQualified()) {
4297       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4298       return false;
4299     }
4300     return true;
4301   }
4302 
4303   bool failed() { return false; }
4304   bool found(APValue &Subobj, QualType SubobjType) {
4305     switch (Subobj.getKind()) {
4306     case APValue::Int:
4307       return found(Subobj.getInt(), SubobjType);
4308     case APValue::Float:
4309       return found(Subobj.getFloat(), SubobjType);
4310     case APValue::ComplexInt:
4311     case APValue::ComplexFloat:
4312       // FIXME: Implement complex compound assignment.
4313       Info.FFDiag(E);
4314       return false;
4315     case APValue::LValue:
4316       return foundPointer(Subobj, SubobjType);
4317     case APValue::Vector:
4318       return foundVector(Subobj, SubobjType);
4319     default:
4320       // FIXME: can this happen?
4321       Info.FFDiag(E);
4322       return false;
4323     }
4324   }
4325 
4326   bool foundVector(APValue &Value, QualType SubobjType) {
4327     if (!checkConst(SubobjType))
4328       return false;
4329 
4330     if (!SubobjType->isVectorType()) {
4331       Info.FFDiag(E);
4332       return false;
4333     }
4334     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4335   }
4336 
4337   bool found(APSInt &Value, QualType SubobjType) {
4338     if (!checkConst(SubobjType))
4339       return false;
4340 
4341     if (!SubobjType->isIntegerType()) {
4342       // We don't support compound assignment on integer-cast-to-pointer
4343       // values.
4344       Info.FFDiag(E);
4345       return false;
4346     }
4347 
4348     if (RHS.isInt()) {
4349       APSInt LHS =
4350           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4351       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4352         return false;
4353       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4354       return true;
4355     } else if (RHS.isFloat()) {
4356       const FPOptions FPO = E->getFPFeaturesInEffect(
4357                                     Info.Ctx.getLangOpts());
4358       APFloat FValue(0.0);
4359       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4360                                   PromotedLHSType, FValue) &&
4361              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4362              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4363                                   Value);
4364     }
4365 
4366     Info.FFDiag(E);
4367     return false;
4368   }
4369   bool found(APFloat &Value, QualType SubobjType) {
4370     return checkConst(SubobjType) &&
4371            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4372                                   Value) &&
4373            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4374            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4375   }
4376   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4377     if (!checkConst(SubobjType))
4378       return false;
4379 
4380     QualType PointeeType;
4381     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4382       PointeeType = PT->getPointeeType();
4383 
4384     if (PointeeType.isNull() || !RHS.isInt() ||
4385         (Opcode != BO_Add && Opcode != BO_Sub)) {
4386       Info.FFDiag(E);
4387       return false;
4388     }
4389 
4390     APSInt Offset = RHS.getInt();
4391     if (Opcode == BO_Sub)
4392       negateAsSigned(Offset);
4393 
4394     LValue LVal;
4395     LVal.setFrom(Info.Ctx, Subobj);
4396     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4397       return false;
4398     LVal.moveInto(Subobj);
4399     return true;
4400   }
4401 };
4402 } // end anonymous namespace
4403 
4404 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4405 
4406 /// Perform a compound assignment of LVal <op>= RVal.
4407 static bool handleCompoundAssignment(EvalInfo &Info,
4408                                      const CompoundAssignOperator *E,
4409                                      const LValue &LVal, QualType LValType,
4410                                      QualType PromotedLValType,
4411                                      BinaryOperatorKind Opcode,
4412                                      const APValue &RVal) {
4413   if (LVal.Designator.Invalid)
4414     return false;
4415 
4416   if (!Info.getLangOpts().CPlusPlus14) {
4417     Info.FFDiag(E);
4418     return false;
4419   }
4420 
4421   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4422   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4423                                              RVal };
4424   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4425 }
4426 
4427 namespace {
4428 struct IncDecSubobjectHandler {
4429   EvalInfo &Info;
4430   const UnaryOperator *E;
4431   AccessKinds AccessKind;
4432   APValue *Old;
4433 
4434   typedef bool result_type;
4435 
4436   bool checkConst(QualType QT) {
4437     // Assigning to a const object has undefined behavior.
4438     if (QT.isConstQualified()) {
4439       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4440       return false;
4441     }
4442     return true;
4443   }
4444 
4445   bool failed() { return false; }
4446   bool found(APValue &Subobj, QualType SubobjType) {
4447     // Stash the old value. Also clear Old, so we don't clobber it later
4448     // if we're post-incrementing a complex.
4449     if (Old) {
4450       *Old = Subobj;
4451       Old = nullptr;
4452     }
4453 
4454     switch (Subobj.getKind()) {
4455     case APValue::Int:
4456       return found(Subobj.getInt(), SubobjType);
4457     case APValue::Float:
4458       return found(Subobj.getFloat(), SubobjType);
4459     case APValue::ComplexInt:
4460       return found(Subobj.getComplexIntReal(),
4461                    SubobjType->castAs<ComplexType>()->getElementType()
4462                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4463     case APValue::ComplexFloat:
4464       return found(Subobj.getComplexFloatReal(),
4465                    SubobjType->castAs<ComplexType>()->getElementType()
4466                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4467     case APValue::LValue:
4468       return foundPointer(Subobj, SubobjType);
4469     default:
4470       // FIXME: can this happen?
4471       Info.FFDiag(E);
4472       return false;
4473     }
4474   }
4475   bool found(APSInt &Value, QualType SubobjType) {
4476     if (!checkConst(SubobjType))
4477       return false;
4478 
4479     if (!SubobjType->isIntegerType()) {
4480       // We don't support increment / decrement on integer-cast-to-pointer
4481       // values.
4482       Info.FFDiag(E);
4483       return false;
4484     }
4485 
4486     if (Old) *Old = APValue(Value);
4487 
4488     // bool arithmetic promotes to int, and the conversion back to bool
4489     // doesn't reduce mod 2^n, so special-case it.
4490     if (SubobjType->isBooleanType()) {
4491       if (AccessKind == AK_Increment)
4492         Value = 1;
4493       else
4494         Value = !Value;
4495       return true;
4496     }
4497 
4498     bool WasNegative = Value.isNegative();
4499     if (AccessKind == AK_Increment) {
4500       ++Value;
4501 
4502       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4503         APSInt ActualValue(Value, /*IsUnsigned*/true);
4504         return HandleOverflow(Info, E, ActualValue, SubobjType);
4505       }
4506     } else {
4507       --Value;
4508 
4509       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4510         unsigned BitWidth = Value.getBitWidth();
4511         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4512         ActualValue.setBit(BitWidth);
4513         return HandleOverflow(Info, E, ActualValue, SubobjType);
4514       }
4515     }
4516     return true;
4517   }
4518   bool found(APFloat &Value, QualType SubobjType) {
4519     if (!checkConst(SubobjType))
4520       return false;
4521 
4522     if (Old) *Old = APValue(Value);
4523 
4524     APFloat One(Value.getSemantics(), 1);
4525     if (AccessKind == AK_Increment)
4526       Value.add(One, APFloat::rmNearestTiesToEven);
4527     else
4528       Value.subtract(One, APFloat::rmNearestTiesToEven);
4529     return true;
4530   }
4531   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4532     if (!checkConst(SubobjType))
4533       return false;
4534 
4535     QualType PointeeType;
4536     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4537       PointeeType = PT->getPointeeType();
4538     else {
4539       Info.FFDiag(E);
4540       return false;
4541     }
4542 
4543     LValue LVal;
4544     LVal.setFrom(Info.Ctx, Subobj);
4545     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4546                                      AccessKind == AK_Increment ? 1 : -1))
4547       return false;
4548     LVal.moveInto(Subobj);
4549     return true;
4550   }
4551 };
4552 } // end anonymous namespace
4553 
4554 /// Perform an increment or decrement on LVal.
4555 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4556                          QualType LValType, bool IsIncrement, APValue *Old) {
4557   if (LVal.Designator.Invalid)
4558     return false;
4559 
4560   if (!Info.getLangOpts().CPlusPlus14) {
4561     Info.FFDiag(E);
4562     return false;
4563   }
4564 
4565   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4566   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4567   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4568   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4569 }
4570 
4571 /// Build an lvalue for the object argument of a member function call.
4572 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4573                                    LValue &This) {
4574   if (Object->getType()->isPointerType() && Object->isPRValue())
4575     return EvaluatePointer(Object, This, Info);
4576 
4577   if (Object->isGLValue())
4578     return EvaluateLValue(Object, This, Info);
4579 
4580   if (Object->getType()->isLiteralType(Info.Ctx))
4581     return EvaluateTemporary(Object, This, Info);
4582 
4583   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4584   return false;
4585 }
4586 
4587 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4588 /// lvalue referring to the result.
4589 ///
4590 /// \param Info - Information about the ongoing evaluation.
4591 /// \param LV - An lvalue referring to the base of the member pointer.
4592 /// \param RHS - The member pointer expression.
4593 /// \param IncludeMember - Specifies whether the member itself is included in
4594 ///        the resulting LValue subobject designator. This is not possible when
4595 ///        creating a bound member function.
4596 /// \return The field or method declaration to which the member pointer refers,
4597 ///         or 0 if evaluation fails.
4598 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4599                                                   QualType LVType,
4600                                                   LValue &LV,
4601                                                   const Expr *RHS,
4602                                                   bool IncludeMember = true) {
4603   MemberPtr MemPtr;
4604   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4605     return nullptr;
4606 
4607   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4608   // member value, the behavior is undefined.
4609   if (!MemPtr.getDecl()) {
4610     // FIXME: Specific diagnostic.
4611     Info.FFDiag(RHS);
4612     return nullptr;
4613   }
4614 
4615   if (MemPtr.isDerivedMember()) {
4616     // This is a member of some derived class. Truncate LV appropriately.
4617     // The end of the derived-to-base path for the base object must match the
4618     // derived-to-base path for the member pointer.
4619     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4620         LV.Designator.Entries.size()) {
4621       Info.FFDiag(RHS);
4622       return nullptr;
4623     }
4624     unsigned PathLengthToMember =
4625         LV.Designator.Entries.size() - MemPtr.Path.size();
4626     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4627       const CXXRecordDecl *LVDecl = getAsBaseClass(
4628           LV.Designator.Entries[PathLengthToMember + I]);
4629       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4630       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4631         Info.FFDiag(RHS);
4632         return nullptr;
4633       }
4634     }
4635 
4636     // Truncate the lvalue to the appropriate derived class.
4637     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4638                             PathLengthToMember))
4639       return nullptr;
4640   } else if (!MemPtr.Path.empty()) {
4641     // Extend the LValue path with the member pointer's path.
4642     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4643                                   MemPtr.Path.size() + IncludeMember);
4644 
4645     // Walk down to the appropriate base class.
4646     if (const PointerType *PT = LVType->getAs<PointerType>())
4647       LVType = PT->getPointeeType();
4648     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4649     assert(RD && "member pointer access on non-class-type expression");
4650     // The first class in the path is that of the lvalue.
4651     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4652       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4653       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4654         return nullptr;
4655       RD = Base;
4656     }
4657     // Finally cast to the class containing the member.
4658     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4659                                 MemPtr.getContainingRecord()))
4660       return nullptr;
4661   }
4662 
4663   // Add the member. Note that we cannot build bound member functions here.
4664   if (IncludeMember) {
4665     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4666       if (!HandleLValueMember(Info, RHS, LV, FD))
4667         return nullptr;
4668     } else if (const IndirectFieldDecl *IFD =
4669                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4670       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4671         return nullptr;
4672     } else {
4673       llvm_unreachable("can't construct reference to bound member function");
4674     }
4675   }
4676 
4677   return MemPtr.getDecl();
4678 }
4679 
4680 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4681                                                   const BinaryOperator *BO,
4682                                                   LValue &LV,
4683                                                   bool IncludeMember = true) {
4684   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4685 
4686   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4687     if (Info.noteFailure()) {
4688       MemberPtr MemPtr;
4689       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4690     }
4691     return nullptr;
4692   }
4693 
4694   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4695                                    BO->getRHS(), IncludeMember);
4696 }
4697 
4698 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4699 /// the provided lvalue, which currently refers to the base object.
4700 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4701                                     LValue &Result) {
4702   SubobjectDesignator &D = Result.Designator;
4703   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4704     return false;
4705 
4706   QualType TargetQT = E->getType();
4707   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4708     TargetQT = PT->getPointeeType();
4709 
4710   // Check this cast lands within the final derived-to-base subobject path.
4711   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4712     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4713       << D.MostDerivedType << TargetQT;
4714     return false;
4715   }
4716 
4717   // Check the type of the final cast. We don't need to check the path,
4718   // since a cast can only be formed if the path is unique.
4719   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4720   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4721   const CXXRecordDecl *FinalType;
4722   if (NewEntriesSize == D.MostDerivedPathLength)
4723     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4724   else
4725     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4726   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4727     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4728       << D.MostDerivedType << TargetQT;
4729     return false;
4730   }
4731 
4732   // Truncate the lvalue to the appropriate derived class.
4733   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4734 }
4735 
4736 /// Get the value to use for a default-initialized object of type T.
4737 /// Return false if it encounters something invalid.
4738 static bool getDefaultInitValue(QualType T, APValue &Result) {
4739   bool Success = true;
4740   if (auto *RD = T->getAsCXXRecordDecl()) {
4741     if (RD->isInvalidDecl()) {
4742       Result = APValue();
4743       return false;
4744     }
4745     if (RD->isUnion()) {
4746       Result = APValue((const FieldDecl *)nullptr);
4747       return true;
4748     }
4749     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4750                      std::distance(RD->field_begin(), RD->field_end()));
4751 
4752     unsigned Index = 0;
4753     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4754                                                   End = RD->bases_end();
4755          I != End; ++I, ++Index)
4756       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4757 
4758     for (const auto *I : RD->fields()) {
4759       if (I->isUnnamedBitfield())
4760         continue;
4761       Success &= getDefaultInitValue(I->getType(),
4762                                      Result.getStructField(I->getFieldIndex()));
4763     }
4764     return Success;
4765   }
4766 
4767   if (auto *AT =
4768           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4769     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4770     if (Result.hasArrayFiller())
4771       Success &=
4772           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4773 
4774     return Success;
4775   }
4776 
4777   Result = APValue::IndeterminateValue();
4778   return true;
4779 }
4780 
4781 namespace {
4782 enum EvalStmtResult {
4783   /// Evaluation failed.
4784   ESR_Failed,
4785   /// Hit a 'return' statement.
4786   ESR_Returned,
4787   /// Evaluation succeeded.
4788   ESR_Succeeded,
4789   /// Hit a 'continue' statement.
4790   ESR_Continue,
4791   /// Hit a 'break' statement.
4792   ESR_Break,
4793   /// Still scanning for 'case' or 'default' statement.
4794   ESR_CaseNotFound
4795 };
4796 }
4797 
4798 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4799   // We don't need to evaluate the initializer for a static local.
4800   if (!VD->hasLocalStorage())
4801     return true;
4802 
4803   LValue Result;
4804   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4805                                                    ScopeKind::Block, Result);
4806 
4807   const Expr *InitE = VD->getInit();
4808   if (!InitE) {
4809     if (VD->getType()->isDependentType())
4810       return Info.noteSideEffect();
4811     return getDefaultInitValue(VD->getType(), Val);
4812   }
4813   if (InitE->isValueDependent())
4814     return false;
4815 
4816   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4817     // Wipe out any partially-computed value, to allow tracking that this
4818     // evaluation failed.
4819     Val = APValue();
4820     return false;
4821   }
4822 
4823   return true;
4824 }
4825 
4826 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4827   bool OK = true;
4828 
4829   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4830     OK &= EvaluateVarDecl(Info, VD);
4831 
4832   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4833     for (auto *BD : DD->bindings())
4834       if (auto *VD = BD->getHoldingVar())
4835         OK &= EvaluateDecl(Info, VD);
4836 
4837   return OK;
4838 }
4839 
4840 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4841   assert(E->isValueDependent());
4842   if (Info.noteSideEffect())
4843     return true;
4844   assert(E->containsErrors() && "valid value-dependent expression should never "
4845                                 "reach invalid code path.");
4846   return false;
4847 }
4848 
4849 /// Evaluate a condition (either a variable declaration or an expression).
4850 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4851                          const Expr *Cond, bool &Result) {
4852   if (Cond->isValueDependent())
4853     return false;
4854   FullExpressionRAII Scope(Info);
4855   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4856     return false;
4857   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4858     return false;
4859   return Scope.destroy();
4860 }
4861 
4862 namespace {
4863 /// A location where the result (returned value) of evaluating a
4864 /// statement should be stored.
4865 struct StmtResult {
4866   /// The APValue that should be filled in with the returned value.
4867   APValue &Value;
4868   /// The location containing the result, if any (used to support RVO).
4869   const LValue *Slot;
4870 };
4871 
4872 struct TempVersionRAII {
4873   CallStackFrame &Frame;
4874 
4875   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4876     Frame.pushTempVersion();
4877   }
4878 
4879   ~TempVersionRAII() {
4880     Frame.popTempVersion();
4881   }
4882 };
4883 
4884 }
4885 
4886 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4887                                    const Stmt *S,
4888                                    const SwitchCase *SC = nullptr);
4889 
4890 /// Evaluate the body of a loop, and translate the result as appropriate.
4891 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4892                                        const Stmt *Body,
4893                                        const SwitchCase *Case = nullptr) {
4894   BlockScopeRAII Scope(Info);
4895 
4896   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4897   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4898     ESR = ESR_Failed;
4899 
4900   switch (ESR) {
4901   case ESR_Break:
4902     return ESR_Succeeded;
4903   case ESR_Succeeded:
4904   case ESR_Continue:
4905     return ESR_Continue;
4906   case ESR_Failed:
4907   case ESR_Returned:
4908   case ESR_CaseNotFound:
4909     return ESR;
4910   }
4911   llvm_unreachable("Invalid EvalStmtResult!");
4912 }
4913 
4914 /// Evaluate a switch statement.
4915 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4916                                      const SwitchStmt *SS) {
4917   BlockScopeRAII Scope(Info);
4918 
4919   // Evaluate the switch condition.
4920   APSInt Value;
4921   {
4922     if (const Stmt *Init = SS->getInit()) {
4923       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4924       if (ESR != ESR_Succeeded) {
4925         if (ESR != ESR_Failed && !Scope.destroy())
4926           ESR = ESR_Failed;
4927         return ESR;
4928       }
4929     }
4930 
4931     FullExpressionRAII CondScope(Info);
4932     if (SS->getConditionVariable() &&
4933         !EvaluateDecl(Info, SS->getConditionVariable()))
4934       return ESR_Failed;
4935     if (!EvaluateInteger(SS->getCond(), Value, Info))
4936       return ESR_Failed;
4937     if (!CondScope.destroy())
4938       return ESR_Failed;
4939   }
4940 
4941   // Find the switch case corresponding to the value of the condition.
4942   // FIXME: Cache this lookup.
4943   const SwitchCase *Found = nullptr;
4944   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4945        SC = SC->getNextSwitchCase()) {
4946     if (isa<DefaultStmt>(SC)) {
4947       Found = SC;
4948       continue;
4949     }
4950 
4951     const CaseStmt *CS = cast<CaseStmt>(SC);
4952     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4953     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4954                               : LHS;
4955     if (LHS <= Value && Value <= RHS) {
4956       Found = SC;
4957       break;
4958     }
4959   }
4960 
4961   if (!Found)
4962     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4963 
4964   // Search the switch body for the switch case and evaluate it from there.
4965   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4966   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4967     return ESR_Failed;
4968 
4969   switch (ESR) {
4970   case ESR_Break:
4971     return ESR_Succeeded;
4972   case ESR_Succeeded:
4973   case ESR_Continue:
4974   case ESR_Failed:
4975   case ESR_Returned:
4976     return ESR;
4977   case ESR_CaseNotFound:
4978     // This can only happen if the switch case is nested within a statement
4979     // expression. We have no intention of supporting that.
4980     Info.FFDiag(Found->getBeginLoc(),
4981                 diag::note_constexpr_stmt_expr_unsupported);
4982     return ESR_Failed;
4983   }
4984   llvm_unreachable("Invalid EvalStmtResult!");
4985 }
4986 
4987 // Evaluate a statement.
4988 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4989                                    const Stmt *S, const SwitchCase *Case) {
4990   if (!Info.nextStep(S))
4991     return ESR_Failed;
4992 
4993   // If we're hunting down a 'case' or 'default' label, recurse through
4994   // substatements until we hit the label.
4995   if (Case) {
4996     switch (S->getStmtClass()) {
4997     case Stmt::CompoundStmtClass:
4998       // FIXME: Precompute which substatement of a compound statement we
4999       // would jump to, and go straight there rather than performing a
5000       // linear scan each time.
5001     case Stmt::LabelStmtClass:
5002     case Stmt::AttributedStmtClass:
5003     case Stmt::DoStmtClass:
5004       break;
5005 
5006     case Stmt::CaseStmtClass:
5007     case Stmt::DefaultStmtClass:
5008       if (Case == S)
5009         Case = nullptr;
5010       break;
5011 
5012     case Stmt::IfStmtClass: {
5013       // FIXME: Precompute which side of an 'if' we would jump to, and go
5014       // straight there rather than scanning both sides.
5015       const IfStmt *IS = cast<IfStmt>(S);
5016 
5017       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5018       // preceded by our switch label.
5019       BlockScopeRAII Scope(Info);
5020 
5021       // Step into the init statement in case it brings an (uninitialized)
5022       // variable into scope.
5023       if (const Stmt *Init = IS->getInit()) {
5024         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5025         if (ESR != ESR_CaseNotFound) {
5026           assert(ESR != ESR_Succeeded);
5027           return ESR;
5028         }
5029       }
5030 
5031       // Condition variable must be initialized if it exists.
5032       // FIXME: We can skip evaluating the body if there's a condition
5033       // variable, as there can't be any case labels within it.
5034       // (The same is true for 'for' statements.)
5035 
5036       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5037       if (ESR == ESR_Failed)
5038         return ESR;
5039       if (ESR != ESR_CaseNotFound)
5040         return Scope.destroy() ? ESR : ESR_Failed;
5041       if (!IS->getElse())
5042         return ESR_CaseNotFound;
5043 
5044       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5045       if (ESR == ESR_Failed)
5046         return ESR;
5047       if (ESR != ESR_CaseNotFound)
5048         return Scope.destroy() ? ESR : ESR_Failed;
5049       return ESR_CaseNotFound;
5050     }
5051 
5052     case Stmt::WhileStmtClass: {
5053       EvalStmtResult ESR =
5054           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5055       if (ESR != ESR_Continue)
5056         return ESR;
5057       break;
5058     }
5059 
5060     case Stmt::ForStmtClass: {
5061       const ForStmt *FS = cast<ForStmt>(S);
5062       BlockScopeRAII Scope(Info);
5063 
5064       // Step into the init statement in case it brings an (uninitialized)
5065       // variable into scope.
5066       if (const Stmt *Init = FS->getInit()) {
5067         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5068         if (ESR != ESR_CaseNotFound) {
5069           assert(ESR != ESR_Succeeded);
5070           return ESR;
5071         }
5072       }
5073 
5074       EvalStmtResult ESR =
5075           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5076       if (ESR != ESR_Continue)
5077         return ESR;
5078       if (const auto *Inc = FS->getInc()) {
5079         if (Inc->isValueDependent()) {
5080           if (!EvaluateDependentExpr(Inc, Info))
5081             return ESR_Failed;
5082         } else {
5083           FullExpressionRAII IncScope(Info);
5084           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5085             return ESR_Failed;
5086         }
5087       }
5088       break;
5089     }
5090 
5091     case Stmt::DeclStmtClass: {
5092       // Start the lifetime of any uninitialized variables we encounter. They
5093       // might be used by the selected branch of the switch.
5094       const DeclStmt *DS = cast<DeclStmt>(S);
5095       for (const auto *D : DS->decls()) {
5096         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5097           if (VD->hasLocalStorage() && !VD->getInit())
5098             if (!EvaluateVarDecl(Info, VD))
5099               return ESR_Failed;
5100           // FIXME: If the variable has initialization that can't be jumped
5101           // over, bail out of any immediately-surrounding compound-statement
5102           // too. There can't be any case labels here.
5103         }
5104       }
5105       return ESR_CaseNotFound;
5106     }
5107 
5108     default:
5109       return ESR_CaseNotFound;
5110     }
5111   }
5112 
5113   switch (S->getStmtClass()) {
5114   default:
5115     if (const Expr *E = dyn_cast<Expr>(S)) {
5116       if (E->isValueDependent()) {
5117         if (!EvaluateDependentExpr(E, Info))
5118           return ESR_Failed;
5119       } else {
5120         // Don't bother evaluating beyond an expression-statement which couldn't
5121         // be evaluated.
5122         // FIXME: Do we need the FullExpressionRAII object here?
5123         // VisitExprWithCleanups should create one when necessary.
5124         FullExpressionRAII Scope(Info);
5125         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5126           return ESR_Failed;
5127       }
5128       return ESR_Succeeded;
5129     }
5130 
5131     Info.FFDiag(S->getBeginLoc());
5132     return ESR_Failed;
5133 
5134   case Stmt::NullStmtClass:
5135     return ESR_Succeeded;
5136 
5137   case Stmt::DeclStmtClass: {
5138     const DeclStmt *DS = cast<DeclStmt>(S);
5139     for (const auto *D : DS->decls()) {
5140       // Each declaration initialization is its own full-expression.
5141       FullExpressionRAII Scope(Info);
5142       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5143         return ESR_Failed;
5144       if (!Scope.destroy())
5145         return ESR_Failed;
5146     }
5147     return ESR_Succeeded;
5148   }
5149 
5150   case Stmt::ReturnStmtClass: {
5151     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5152     FullExpressionRAII Scope(Info);
5153     if (RetExpr && RetExpr->isValueDependent()) {
5154       EvaluateDependentExpr(RetExpr, Info);
5155       // We know we returned, but we don't know what the value is.
5156       return ESR_Failed;
5157     }
5158     if (RetExpr &&
5159         !(Result.Slot
5160               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5161               : Evaluate(Result.Value, Info, RetExpr)))
5162       return ESR_Failed;
5163     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5164   }
5165 
5166   case Stmt::CompoundStmtClass: {
5167     BlockScopeRAII Scope(Info);
5168 
5169     const CompoundStmt *CS = cast<CompoundStmt>(S);
5170     for (const auto *BI : CS->body()) {
5171       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5172       if (ESR == ESR_Succeeded)
5173         Case = nullptr;
5174       else if (ESR != ESR_CaseNotFound) {
5175         if (ESR != ESR_Failed && !Scope.destroy())
5176           return ESR_Failed;
5177         return ESR;
5178       }
5179     }
5180     if (Case)
5181       return ESR_CaseNotFound;
5182     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5183   }
5184 
5185   case Stmt::IfStmtClass: {
5186     const IfStmt *IS = cast<IfStmt>(S);
5187 
5188     // Evaluate the condition, as either a var decl or as an expression.
5189     BlockScopeRAII Scope(Info);
5190     if (const Stmt *Init = IS->getInit()) {
5191       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5192       if (ESR != ESR_Succeeded) {
5193         if (ESR != ESR_Failed && !Scope.destroy())
5194           return ESR_Failed;
5195         return ESR;
5196       }
5197     }
5198     bool Cond;
5199     if (IS->isConsteval())
5200       Cond = IS->isNonNegatedConsteval();
5201     else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5202                            Cond))
5203       return ESR_Failed;
5204 
5205     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5206       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5207       if (ESR != ESR_Succeeded) {
5208         if (ESR != ESR_Failed && !Scope.destroy())
5209           return ESR_Failed;
5210         return ESR;
5211       }
5212     }
5213     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5214   }
5215 
5216   case Stmt::WhileStmtClass: {
5217     const WhileStmt *WS = cast<WhileStmt>(S);
5218     while (true) {
5219       BlockScopeRAII Scope(Info);
5220       bool Continue;
5221       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5222                         Continue))
5223         return ESR_Failed;
5224       if (!Continue)
5225         break;
5226 
5227       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5228       if (ESR != ESR_Continue) {
5229         if (ESR != ESR_Failed && !Scope.destroy())
5230           return ESR_Failed;
5231         return ESR;
5232       }
5233       if (!Scope.destroy())
5234         return ESR_Failed;
5235     }
5236     return ESR_Succeeded;
5237   }
5238 
5239   case Stmt::DoStmtClass: {
5240     const DoStmt *DS = cast<DoStmt>(S);
5241     bool Continue;
5242     do {
5243       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5244       if (ESR != ESR_Continue)
5245         return ESR;
5246       Case = nullptr;
5247 
5248       if (DS->getCond()->isValueDependent()) {
5249         EvaluateDependentExpr(DS->getCond(), Info);
5250         // Bailout as we don't know whether to keep going or terminate the loop.
5251         return ESR_Failed;
5252       }
5253       FullExpressionRAII CondScope(Info);
5254       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5255           !CondScope.destroy())
5256         return ESR_Failed;
5257     } while (Continue);
5258     return ESR_Succeeded;
5259   }
5260 
5261   case Stmt::ForStmtClass: {
5262     const ForStmt *FS = cast<ForStmt>(S);
5263     BlockScopeRAII ForScope(Info);
5264     if (FS->getInit()) {
5265       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5266       if (ESR != ESR_Succeeded) {
5267         if (ESR != ESR_Failed && !ForScope.destroy())
5268           return ESR_Failed;
5269         return ESR;
5270       }
5271     }
5272     while (true) {
5273       BlockScopeRAII IterScope(Info);
5274       bool Continue = true;
5275       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5276                                          FS->getCond(), Continue))
5277         return ESR_Failed;
5278       if (!Continue)
5279         break;
5280 
5281       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5282       if (ESR != ESR_Continue) {
5283         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5284           return ESR_Failed;
5285         return ESR;
5286       }
5287 
5288       if (const auto *Inc = FS->getInc()) {
5289         if (Inc->isValueDependent()) {
5290           if (!EvaluateDependentExpr(Inc, Info))
5291             return ESR_Failed;
5292         } else {
5293           FullExpressionRAII IncScope(Info);
5294           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5295             return ESR_Failed;
5296         }
5297       }
5298 
5299       if (!IterScope.destroy())
5300         return ESR_Failed;
5301     }
5302     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5303   }
5304 
5305   case Stmt::CXXForRangeStmtClass: {
5306     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5307     BlockScopeRAII Scope(Info);
5308 
5309     // Evaluate the init-statement if present.
5310     if (FS->getInit()) {
5311       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5312       if (ESR != ESR_Succeeded) {
5313         if (ESR != ESR_Failed && !Scope.destroy())
5314           return ESR_Failed;
5315         return ESR;
5316       }
5317     }
5318 
5319     // Initialize the __range variable.
5320     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5321     if (ESR != ESR_Succeeded) {
5322       if (ESR != ESR_Failed && !Scope.destroy())
5323         return ESR_Failed;
5324       return ESR;
5325     }
5326 
5327     // In error-recovery cases it's possible to get here even if we failed to
5328     // synthesize the __begin and __end variables.
5329     if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5330       return ESR_Failed;
5331 
5332     // Create the __begin and __end iterators.
5333     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5334     if (ESR != ESR_Succeeded) {
5335       if (ESR != ESR_Failed && !Scope.destroy())
5336         return ESR_Failed;
5337       return ESR;
5338     }
5339     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5340     if (ESR != ESR_Succeeded) {
5341       if (ESR != ESR_Failed && !Scope.destroy())
5342         return ESR_Failed;
5343       return ESR;
5344     }
5345 
5346     while (true) {
5347       // Condition: __begin != __end.
5348       {
5349         if (FS->getCond()->isValueDependent()) {
5350           EvaluateDependentExpr(FS->getCond(), Info);
5351           // We don't know whether to keep going or terminate the loop.
5352           return ESR_Failed;
5353         }
5354         bool Continue = true;
5355         FullExpressionRAII CondExpr(Info);
5356         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5357           return ESR_Failed;
5358         if (!Continue)
5359           break;
5360       }
5361 
5362       // User's variable declaration, initialized by *__begin.
5363       BlockScopeRAII InnerScope(Info);
5364       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5365       if (ESR != ESR_Succeeded) {
5366         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5367           return ESR_Failed;
5368         return ESR;
5369       }
5370 
5371       // Loop body.
5372       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5373       if (ESR != ESR_Continue) {
5374         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5375           return ESR_Failed;
5376         return ESR;
5377       }
5378       if (FS->getInc()->isValueDependent()) {
5379         if (!EvaluateDependentExpr(FS->getInc(), Info))
5380           return ESR_Failed;
5381       } else {
5382         // Increment: ++__begin
5383         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5384           return ESR_Failed;
5385       }
5386 
5387       if (!InnerScope.destroy())
5388         return ESR_Failed;
5389     }
5390 
5391     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5392   }
5393 
5394   case Stmt::SwitchStmtClass:
5395     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5396 
5397   case Stmt::ContinueStmtClass:
5398     return ESR_Continue;
5399 
5400   case Stmt::BreakStmtClass:
5401     return ESR_Break;
5402 
5403   case Stmt::LabelStmtClass:
5404     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5405 
5406   case Stmt::AttributedStmtClass:
5407     // As a general principle, C++11 attributes can be ignored without
5408     // any semantic impact.
5409     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5410                         Case);
5411 
5412   case Stmt::CaseStmtClass:
5413   case Stmt::DefaultStmtClass:
5414     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5415   case Stmt::CXXTryStmtClass:
5416     // Evaluate try blocks by evaluating all sub statements.
5417     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5418   }
5419 }
5420 
5421 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5422 /// default constructor. If so, we'll fold it whether or not it's marked as
5423 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5424 /// so we need special handling.
5425 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5426                                            const CXXConstructorDecl *CD,
5427                                            bool IsValueInitialization) {
5428   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5429     return false;
5430 
5431   // Value-initialization does not call a trivial default constructor, so such a
5432   // call is a core constant expression whether or not the constructor is
5433   // constexpr.
5434   if (!CD->isConstexpr() && !IsValueInitialization) {
5435     if (Info.getLangOpts().CPlusPlus11) {
5436       // FIXME: If DiagDecl is an implicitly-declared special member function,
5437       // we should be much more explicit about why it's not constexpr.
5438       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5439         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5440       Info.Note(CD->getLocation(), diag::note_declared_at);
5441     } else {
5442       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5443     }
5444   }
5445   return true;
5446 }
5447 
5448 /// CheckConstexprFunction - Check that a function can be called in a constant
5449 /// expression.
5450 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5451                                    const FunctionDecl *Declaration,
5452                                    const FunctionDecl *Definition,
5453                                    const Stmt *Body) {
5454   // Potential constant expressions can contain calls to declared, but not yet
5455   // defined, constexpr functions.
5456   if (Info.checkingPotentialConstantExpression() && !Definition &&
5457       Declaration->isConstexpr())
5458     return false;
5459 
5460   // Bail out if the function declaration itself is invalid.  We will
5461   // have produced a relevant diagnostic while parsing it, so just
5462   // note the problematic sub-expression.
5463   if (Declaration->isInvalidDecl()) {
5464     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5465     return false;
5466   }
5467 
5468   // DR1872: An instantiated virtual constexpr function can't be called in a
5469   // constant expression (prior to C++20). We can still constant-fold such a
5470   // call.
5471   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5472       cast<CXXMethodDecl>(Declaration)->isVirtual())
5473     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5474 
5475   if (Definition && Definition->isInvalidDecl()) {
5476     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5477     return false;
5478   }
5479 
5480   // Can we evaluate this function call?
5481   if (Definition && Definition->isConstexpr() && Body)
5482     return true;
5483 
5484   if (Info.getLangOpts().CPlusPlus11) {
5485     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5486 
5487     // If this function is not constexpr because it is an inherited
5488     // non-constexpr constructor, diagnose that directly.
5489     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5490     if (CD && CD->isInheritingConstructor()) {
5491       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5492       if (!Inherited->isConstexpr())
5493         DiagDecl = CD = Inherited;
5494     }
5495 
5496     // FIXME: If DiagDecl is an implicitly-declared special member function
5497     // or an inheriting constructor, we should be much more explicit about why
5498     // it's not constexpr.
5499     if (CD && CD->isInheritingConstructor())
5500       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5501         << CD->getInheritedConstructor().getConstructor()->getParent();
5502     else
5503       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5504         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5505     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5506   } else {
5507     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5508   }
5509   return false;
5510 }
5511 
5512 namespace {
5513 struct CheckDynamicTypeHandler {
5514   AccessKinds AccessKind;
5515   typedef bool result_type;
5516   bool failed() { return false; }
5517   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5518   bool found(APSInt &Value, QualType SubobjType) { return true; }
5519   bool found(APFloat &Value, QualType SubobjType) { return true; }
5520 };
5521 } // end anonymous namespace
5522 
5523 /// Check that we can access the notional vptr of an object / determine its
5524 /// dynamic type.
5525 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5526                              AccessKinds AK, bool Polymorphic) {
5527   if (This.Designator.Invalid)
5528     return false;
5529 
5530   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5531 
5532   if (!Obj)
5533     return false;
5534 
5535   if (!Obj.Value) {
5536     // The object is not usable in constant expressions, so we can't inspect
5537     // its value to see if it's in-lifetime or what the active union members
5538     // are. We can still check for a one-past-the-end lvalue.
5539     if (This.Designator.isOnePastTheEnd() ||
5540         This.Designator.isMostDerivedAnUnsizedArray()) {
5541       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5542                          ? diag::note_constexpr_access_past_end
5543                          : diag::note_constexpr_access_unsized_array)
5544           << AK;
5545       return false;
5546     } else if (Polymorphic) {
5547       // Conservatively refuse to perform a polymorphic operation if we would
5548       // not be able to read a notional 'vptr' value.
5549       APValue Val;
5550       This.moveInto(Val);
5551       QualType StarThisType =
5552           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5553       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5554           << AK << Val.getAsString(Info.Ctx, StarThisType);
5555       return false;
5556     }
5557     return true;
5558   }
5559 
5560   CheckDynamicTypeHandler Handler{AK};
5561   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5562 }
5563 
5564 /// Check that the pointee of the 'this' pointer in a member function call is
5565 /// either within its lifetime or in its period of construction or destruction.
5566 static bool
5567 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5568                                      const LValue &This,
5569                                      const CXXMethodDecl *NamedMember) {
5570   return checkDynamicType(
5571       Info, E, This,
5572       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5573 }
5574 
5575 struct DynamicType {
5576   /// The dynamic class type of the object.
5577   const CXXRecordDecl *Type;
5578   /// The corresponding path length in the lvalue.
5579   unsigned PathLength;
5580 };
5581 
5582 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5583                                              unsigned PathLength) {
5584   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5585       Designator.Entries.size() && "invalid path length");
5586   return (PathLength == Designator.MostDerivedPathLength)
5587              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5588              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5589 }
5590 
5591 /// Determine the dynamic type of an object.
5592 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5593                                                 LValue &This, AccessKinds AK) {
5594   // If we don't have an lvalue denoting an object of class type, there is no
5595   // meaningful dynamic type. (We consider objects of non-class type to have no
5596   // dynamic type.)
5597   if (!checkDynamicType(Info, E, This, AK, true))
5598     return None;
5599 
5600   // Refuse to compute a dynamic type in the presence of virtual bases. This
5601   // shouldn't happen other than in constant-folding situations, since literal
5602   // types can't have virtual bases.
5603   //
5604   // Note that consumers of DynamicType assume that the type has no virtual
5605   // bases, and will need modifications if this restriction is relaxed.
5606   const CXXRecordDecl *Class =
5607       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5608   if (!Class || Class->getNumVBases()) {
5609     Info.FFDiag(E);
5610     return None;
5611   }
5612 
5613   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5614   // binary search here instead. But the overwhelmingly common case is that
5615   // we're not in the middle of a constructor, so it probably doesn't matter
5616   // in practice.
5617   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5618   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5619        PathLength <= Path.size(); ++PathLength) {
5620     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5621                                       Path.slice(0, PathLength))) {
5622     case ConstructionPhase::Bases:
5623     case ConstructionPhase::DestroyingBases:
5624       // We're constructing or destroying a base class. This is not the dynamic
5625       // type.
5626       break;
5627 
5628     case ConstructionPhase::None:
5629     case ConstructionPhase::AfterBases:
5630     case ConstructionPhase::AfterFields:
5631     case ConstructionPhase::Destroying:
5632       // We've finished constructing the base classes and not yet started
5633       // destroying them again, so this is the dynamic type.
5634       return DynamicType{getBaseClassType(This.Designator, PathLength),
5635                          PathLength};
5636     }
5637   }
5638 
5639   // CWG issue 1517: we're constructing a base class of the object described by
5640   // 'This', so that object has not yet begun its period of construction and
5641   // any polymorphic operation on it results in undefined behavior.
5642   Info.FFDiag(E);
5643   return None;
5644 }
5645 
5646 /// Perform virtual dispatch.
5647 static const CXXMethodDecl *HandleVirtualDispatch(
5648     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5649     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5650   Optional<DynamicType> DynType = ComputeDynamicType(
5651       Info, E, This,
5652       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5653   if (!DynType)
5654     return nullptr;
5655 
5656   // Find the final overrider. It must be declared in one of the classes on the
5657   // path from the dynamic type to the static type.
5658   // FIXME: If we ever allow literal types to have virtual base classes, that
5659   // won't be true.
5660   const CXXMethodDecl *Callee = Found;
5661   unsigned PathLength = DynType->PathLength;
5662   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5663     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5664     const CXXMethodDecl *Overrider =
5665         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5666     if (Overrider) {
5667       Callee = Overrider;
5668       break;
5669     }
5670   }
5671 
5672   // C++2a [class.abstract]p6:
5673   //   the effect of making a virtual call to a pure virtual function [...] is
5674   //   undefined
5675   if (Callee->isPure()) {
5676     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5677     Info.Note(Callee->getLocation(), diag::note_declared_at);
5678     return nullptr;
5679   }
5680 
5681   // If necessary, walk the rest of the path to determine the sequence of
5682   // covariant adjustment steps to apply.
5683   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5684                                        Found->getReturnType())) {
5685     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5686     for (unsigned CovariantPathLength = PathLength + 1;
5687          CovariantPathLength != This.Designator.Entries.size();
5688          ++CovariantPathLength) {
5689       const CXXRecordDecl *NextClass =
5690           getBaseClassType(This.Designator, CovariantPathLength);
5691       const CXXMethodDecl *Next =
5692           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5693       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5694                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5695         CovariantAdjustmentPath.push_back(Next->getReturnType());
5696     }
5697     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5698                                          CovariantAdjustmentPath.back()))
5699       CovariantAdjustmentPath.push_back(Found->getReturnType());
5700   }
5701 
5702   // Perform 'this' adjustment.
5703   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5704     return nullptr;
5705 
5706   return Callee;
5707 }
5708 
5709 /// Perform the adjustment from a value returned by a virtual function to
5710 /// a value of the statically expected type, which may be a pointer or
5711 /// reference to a base class of the returned type.
5712 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5713                                             APValue &Result,
5714                                             ArrayRef<QualType> Path) {
5715   assert(Result.isLValue() &&
5716          "unexpected kind of APValue for covariant return");
5717   if (Result.isNullPointer())
5718     return true;
5719 
5720   LValue LVal;
5721   LVal.setFrom(Info.Ctx, Result);
5722 
5723   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5724   for (unsigned I = 1; I != Path.size(); ++I) {
5725     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5726     assert(OldClass && NewClass && "unexpected kind of covariant return");
5727     if (OldClass != NewClass &&
5728         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5729       return false;
5730     OldClass = NewClass;
5731   }
5732 
5733   LVal.moveInto(Result);
5734   return true;
5735 }
5736 
5737 /// Determine whether \p Base, which is known to be a direct base class of
5738 /// \p Derived, is a public base class.
5739 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5740                               const CXXRecordDecl *Base) {
5741   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5742     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5743     if (BaseClass && declaresSameEntity(BaseClass, Base))
5744       return BaseSpec.getAccessSpecifier() == AS_public;
5745   }
5746   llvm_unreachable("Base is not a direct base of Derived");
5747 }
5748 
5749 /// Apply the given dynamic cast operation on the provided lvalue.
5750 ///
5751 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5752 /// to find a suitable target subobject.
5753 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5754                               LValue &Ptr) {
5755   // We can't do anything with a non-symbolic pointer value.
5756   SubobjectDesignator &D = Ptr.Designator;
5757   if (D.Invalid)
5758     return false;
5759 
5760   // C++ [expr.dynamic.cast]p6:
5761   //   If v is a null pointer value, the result is a null pointer value.
5762   if (Ptr.isNullPointer() && !E->isGLValue())
5763     return true;
5764 
5765   // For all the other cases, we need the pointer to point to an object within
5766   // its lifetime / period of construction / destruction, and we need to know
5767   // its dynamic type.
5768   Optional<DynamicType> DynType =
5769       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5770   if (!DynType)
5771     return false;
5772 
5773   // C++ [expr.dynamic.cast]p7:
5774   //   If T is "pointer to cv void", then the result is a pointer to the most
5775   //   derived object
5776   if (E->getType()->isVoidPointerType())
5777     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5778 
5779   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5780   assert(C && "dynamic_cast target is not void pointer nor class");
5781   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5782 
5783   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5784     // C++ [expr.dynamic.cast]p9:
5785     if (!E->isGLValue()) {
5786       //   The value of a failed cast to pointer type is the null pointer value
5787       //   of the required result type.
5788       Ptr.setNull(Info.Ctx, E->getType());
5789       return true;
5790     }
5791 
5792     //   A failed cast to reference type throws [...] std::bad_cast.
5793     unsigned DiagKind;
5794     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5795                    DynType->Type->isDerivedFrom(C)))
5796       DiagKind = 0;
5797     else if (!Paths || Paths->begin() == Paths->end())
5798       DiagKind = 1;
5799     else if (Paths->isAmbiguous(CQT))
5800       DiagKind = 2;
5801     else {
5802       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5803       DiagKind = 3;
5804     }
5805     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5806         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5807         << Info.Ctx.getRecordType(DynType->Type)
5808         << E->getType().getUnqualifiedType();
5809     return false;
5810   };
5811 
5812   // Runtime check, phase 1:
5813   //   Walk from the base subobject towards the derived object looking for the
5814   //   target type.
5815   for (int PathLength = Ptr.Designator.Entries.size();
5816        PathLength >= (int)DynType->PathLength; --PathLength) {
5817     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5818     if (declaresSameEntity(Class, C))
5819       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5820     // We can only walk across public inheritance edges.
5821     if (PathLength > (int)DynType->PathLength &&
5822         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5823                            Class))
5824       return RuntimeCheckFailed(nullptr);
5825   }
5826 
5827   // Runtime check, phase 2:
5828   //   Search the dynamic type for an unambiguous public base of type C.
5829   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5830                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5831   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5832       Paths.front().Access == AS_public) {
5833     // Downcast to the dynamic type...
5834     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5835       return false;
5836     // ... then upcast to the chosen base class subobject.
5837     for (CXXBasePathElement &Elem : Paths.front())
5838       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5839         return false;
5840     return true;
5841   }
5842 
5843   // Otherwise, the runtime check fails.
5844   return RuntimeCheckFailed(&Paths);
5845 }
5846 
5847 namespace {
5848 struct StartLifetimeOfUnionMemberHandler {
5849   EvalInfo &Info;
5850   const Expr *LHSExpr;
5851   const FieldDecl *Field;
5852   bool DuringInit;
5853   bool Failed = false;
5854   static const AccessKinds AccessKind = AK_Assign;
5855 
5856   typedef bool result_type;
5857   bool failed() { return Failed; }
5858   bool found(APValue &Subobj, QualType SubobjType) {
5859     // We are supposed to perform no initialization but begin the lifetime of
5860     // the object. We interpret that as meaning to do what default
5861     // initialization of the object would do if all constructors involved were
5862     // trivial:
5863     //  * All base, non-variant member, and array element subobjects' lifetimes
5864     //    begin
5865     //  * No variant members' lifetimes begin
5866     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5867     assert(SubobjType->isUnionType());
5868     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5869       // This union member is already active. If it's also in-lifetime, there's
5870       // nothing to do.
5871       if (Subobj.getUnionValue().hasValue())
5872         return true;
5873     } else if (DuringInit) {
5874       // We're currently in the process of initializing a different union
5875       // member.  If we carried on, that initialization would attempt to
5876       // store to an inactive union member, resulting in undefined behavior.
5877       Info.FFDiag(LHSExpr,
5878                   diag::note_constexpr_union_member_change_during_init);
5879       return false;
5880     }
5881     APValue Result;
5882     Failed = !getDefaultInitValue(Field->getType(), Result);
5883     Subobj.setUnion(Field, Result);
5884     return true;
5885   }
5886   bool found(APSInt &Value, QualType SubobjType) {
5887     llvm_unreachable("wrong value kind for union object");
5888   }
5889   bool found(APFloat &Value, QualType SubobjType) {
5890     llvm_unreachable("wrong value kind for union object");
5891   }
5892 };
5893 } // end anonymous namespace
5894 
5895 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5896 
5897 /// Handle a builtin simple-assignment or a call to a trivial assignment
5898 /// operator whose left-hand side might involve a union member access. If it
5899 /// does, implicitly start the lifetime of any accessed union elements per
5900 /// C++20 [class.union]5.
5901 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5902                                           const LValue &LHS) {
5903   if (LHS.InvalidBase || LHS.Designator.Invalid)
5904     return false;
5905 
5906   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5907   // C++ [class.union]p5:
5908   //   define the set S(E) of subexpressions of E as follows:
5909   unsigned PathLength = LHS.Designator.Entries.size();
5910   for (const Expr *E = LHSExpr; E != nullptr;) {
5911     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5912     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5913       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5914       // Note that we can't implicitly start the lifetime of a reference,
5915       // so we don't need to proceed any further if we reach one.
5916       if (!FD || FD->getType()->isReferenceType())
5917         break;
5918 
5919       //    ... and also contains A.B if B names a union member ...
5920       if (FD->getParent()->isUnion()) {
5921         //    ... of a non-class, non-array type, or of a class type with a
5922         //    trivial default constructor that is not deleted, or an array of
5923         //    such types.
5924         auto *RD =
5925             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5926         if (!RD || RD->hasTrivialDefaultConstructor())
5927           UnionPathLengths.push_back({PathLength - 1, FD});
5928       }
5929 
5930       E = ME->getBase();
5931       --PathLength;
5932       assert(declaresSameEntity(FD,
5933                                 LHS.Designator.Entries[PathLength]
5934                                     .getAsBaseOrMember().getPointer()));
5935 
5936       //   -- If E is of the form A[B] and is interpreted as a built-in array
5937       //      subscripting operator, S(E) is [S(the array operand, if any)].
5938     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5939       // Step over an ArrayToPointerDecay implicit cast.
5940       auto *Base = ASE->getBase()->IgnoreImplicit();
5941       if (!Base->getType()->isArrayType())
5942         break;
5943 
5944       E = Base;
5945       --PathLength;
5946 
5947     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5948       // Step over a derived-to-base conversion.
5949       E = ICE->getSubExpr();
5950       if (ICE->getCastKind() == CK_NoOp)
5951         continue;
5952       if (ICE->getCastKind() != CK_DerivedToBase &&
5953           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5954         break;
5955       // Walk path backwards as we walk up from the base to the derived class.
5956       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5957         --PathLength;
5958         (void)Elt;
5959         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5960                                   LHS.Designator.Entries[PathLength]
5961                                       .getAsBaseOrMember().getPointer()));
5962       }
5963 
5964     //   -- Otherwise, S(E) is empty.
5965     } else {
5966       break;
5967     }
5968   }
5969 
5970   // Common case: no unions' lifetimes are started.
5971   if (UnionPathLengths.empty())
5972     return true;
5973 
5974   //   if modification of X [would access an inactive union member], an object
5975   //   of the type of X is implicitly created
5976   CompleteObject Obj =
5977       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5978   if (!Obj)
5979     return false;
5980   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5981            llvm::reverse(UnionPathLengths)) {
5982     // Form a designator for the union object.
5983     SubobjectDesignator D = LHS.Designator;
5984     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5985 
5986     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5987                       ConstructionPhase::AfterBases;
5988     StartLifetimeOfUnionMemberHandler StartLifetime{
5989         Info, LHSExpr, LengthAndField.second, DuringInit};
5990     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5991       return false;
5992   }
5993 
5994   return true;
5995 }
5996 
5997 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5998                             CallRef Call, EvalInfo &Info,
5999                             bool NonNull = false) {
6000   LValue LV;
6001   // Create the parameter slot and register its destruction. For a vararg
6002   // argument, create a temporary.
6003   // FIXME: For calling conventions that destroy parameters in the callee,
6004   // should we consider performing destruction when the function returns
6005   // instead?
6006   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6007                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6008                                                        ScopeKind::Call, LV);
6009   if (!EvaluateInPlace(V, Info, LV, Arg))
6010     return false;
6011 
6012   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6013   // undefined behavior, so is non-constant.
6014   if (NonNull && V.isLValue() && V.isNullPointer()) {
6015     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6016     return false;
6017   }
6018 
6019   return true;
6020 }
6021 
6022 /// Evaluate the arguments to a function call.
6023 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6024                          EvalInfo &Info, const FunctionDecl *Callee,
6025                          bool RightToLeft = false) {
6026   bool Success = true;
6027   llvm::SmallBitVector ForbiddenNullArgs;
6028   if (Callee->hasAttr<NonNullAttr>()) {
6029     ForbiddenNullArgs.resize(Args.size());
6030     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6031       if (!Attr->args_size()) {
6032         ForbiddenNullArgs.set();
6033         break;
6034       } else
6035         for (auto Idx : Attr->args()) {
6036           unsigned ASTIdx = Idx.getASTIndex();
6037           if (ASTIdx >= Args.size())
6038             continue;
6039           ForbiddenNullArgs[ASTIdx] = 1;
6040         }
6041     }
6042   }
6043   for (unsigned I = 0; I < Args.size(); I++) {
6044     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6045     const ParmVarDecl *PVD =
6046         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6047     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6048     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6049       // If we're checking for a potential constant expression, evaluate all
6050       // initializers even if some of them fail.
6051       if (!Info.noteFailure())
6052         return false;
6053       Success = false;
6054     }
6055   }
6056   return Success;
6057 }
6058 
6059 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6060 /// constructor or assignment operator.
6061 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6062                               const Expr *E, APValue &Result,
6063                               bool CopyObjectRepresentation) {
6064   // Find the reference argument.
6065   CallStackFrame *Frame = Info.CurrentCall;
6066   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6067   if (!RefValue) {
6068     Info.FFDiag(E);
6069     return false;
6070   }
6071 
6072   // Copy out the contents of the RHS object.
6073   LValue RefLValue;
6074   RefLValue.setFrom(Info.Ctx, *RefValue);
6075   return handleLValueToRValueConversion(
6076       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6077       CopyObjectRepresentation);
6078 }
6079 
6080 /// Evaluate a function call.
6081 static bool HandleFunctionCall(SourceLocation CallLoc,
6082                                const FunctionDecl *Callee, const LValue *This,
6083                                ArrayRef<const Expr *> Args, CallRef Call,
6084                                const Stmt *Body, EvalInfo &Info,
6085                                APValue &Result, const LValue *ResultSlot) {
6086   if (!Info.CheckCallLimit(CallLoc))
6087     return false;
6088 
6089   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6090 
6091   // For a trivial copy or move assignment, perform an APValue copy. This is
6092   // essential for unions, where the operations performed by the assignment
6093   // operator cannot be represented as statements.
6094   //
6095   // Skip this for non-union classes with no fields; in that case, the defaulted
6096   // copy/move does not actually read the object.
6097   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6098   if (MD && MD->isDefaulted() &&
6099       (MD->getParent()->isUnion() ||
6100        (MD->isTrivial() &&
6101         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6102     assert(This &&
6103            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6104     APValue RHSValue;
6105     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6106                            MD->getParent()->isUnion()))
6107       return false;
6108     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6109         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6110       return false;
6111     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6112                           RHSValue))
6113       return false;
6114     This->moveInto(Result);
6115     return true;
6116   } else if (MD && isLambdaCallOperator(MD)) {
6117     // We're in a lambda; determine the lambda capture field maps unless we're
6118     // just constexpr checking a lambda's call operator. constexpr checking is
6119     // done before the captures have been added to the closure object (unless
6120     // we're inferring constexpr-ness), so we don't have access to them in this
6121     // case. But since we don't need the captures to constexpr check, we can
6122     // just ignore them.
6123     if (!Info.checkingPotentialConstantExpression())
6124       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6125                                         Frame.LambdaThisCaptureField);
6126   }
6127 
6128   StmtResult Ret = {Result, ResultSlot};
6129   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6130   if (ESR == ESR_Succeeded) {
6131     if (Callee->getReturnType()->isVoidType())
6132       return true;
6133     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6134   }
6135   return ESR == ESR_Returned;
6136 }
6137 
6138 /// Evaluate a constructor call.
6139 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6140                                   CallRef Call,
6141                                   const CXXConstructorDecl *Definition,
6142                                   EvalInfo &Info, APValue &Result) {
6143   SourceLocation CallLoc = E->getExprLoc();
6144   if (!Info.CheckCallLimit(CallLoc))
6145     return false;
6146 
6147   const CXXRecordDecl *RD = Definition->getParent();
6148   if (RD->getNumVBases()) {
6149     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6150     return false;
6151   }
6152 
6153   EvalInfo::EvaluatingConstructorRAII EvalObj(
6154       Info,
6155       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6156       RD->getNumBases());
6157   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6158 
6159   // FIXME: Creating an APValue just to hold a nonexistent return value is
6160   // wasteful.
6161   APValue RetVal;
6162   StmtResult Ret = {RetVal, nullptr};
6163 
6164   // If it's a delegating constructor, delegate.
6165   if (Definition->isDelegatingConstructor()) {
6166     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6167     if ((*I)->getInit()->isValueDependent()) {
6168       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6169         return false;
6170     } else {
6171       FullExpressionRAII InitScope(Info);
6172       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6173           !InitScope.destroy())
6174         return false;
6175     }
6176     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6177   }
6178 
6179   // For a trivial copy or move constructor, perform an APValue copy. This is
6180   // essential for unions (or classes with anonymous union members), where the
6181   // operations performed by the constructor cannot be represented by
6182   // ctor-initializers.
6183   //
6184   // Skip this for empty non-union classes; we should not perform an
6185   // lvalue-to-rvalue conversion on them because their copy constructor does not
6186   // actually read them.
6187   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6188       (Definition->getParent()->isUnion() ||
6189        (Definition->isTrivial() &&
6190         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6191     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6192                              Definition->getParent()->isUnion());
6193   }
6194 
6195   // Reserve space for the struct members.
6196   if (!Result.hasValue()) {
6197     if (!RD->isUnion())
6198       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6199                        std::distance(RD->field_begin(), RD->field_end()));
6200     else
6201       // A union starts with no active member.
6202       Result = APValue((const FieldDecl*)nullptr);
6203   }
6204 
6205   if (RD->isInvalidDecl()) return false;
6206   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6207 
6208   // A scope for temporaries lifetime-extended by reference members.
6209   BlockScopeRAII LifetimeExtendedScope(Info);
6210 
6211   bool Success = true;
6212   unsigned BasesSeen = 0;
6213 #ifndef NDEBUG
6214   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6215 #endif
6216   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6217   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6218     // We might be initializing the same field again if this is an indirect
6219     // field initialization.
6220     if (FieldIt == RD->field_end() ||
6221         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6222       assert(Indirect && "fields out of order?");
6223       return;
6224     }
6225 
6226     // Default-initialize any fields with no explicit initializer.
6227     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6228       assert(FieldIt != RD->field_end() && "missing field?");
6229       if (!FieldIt->isUnnamedBitfield())
6230         Success &= getDefaultInitValue(
6231             FieldIt->getType(),
6232             Result.getStructField(FieldIt->getFieldIndex()));
6233     }
6234     ++FieldIt;
6235   };
6236   for (const auto *I : Definition->inits()) {
6237     LValue Subobject = This;
6238     LValue SubobjectParent = This;
6239     APValue *Value = &Result;
6240 
6241     // Determine the subobject to initialize.
6242     FieldDecl *FD = nullptr;
6243     if (I->isBaseInitializer()) {
6244       QualType BaseType(I->getBaseClass(), 0);
6245 #ifndef NDEBUG
6246       // Non-virtual base classes are initialized in the order in the class
6247       // definition. We have already checked for virtual base classes.
6248       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6249       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6250              "base class initializers not in expected order");
6251       ++BaseIt;
6252 #endif
6253       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6254                                   BaseType->getAsCXXRecordDecl(), &Layout))
6255         return false;
6256       Value = &Result.getStructBase(BasesSeen++);
6257     } else if ((FD = I->getMember())) {
6258       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6259         return false;
6260       if (RD->isUnion()) {
6261         Result = APValue(FD);
6262         Value = &Result.getUnionValue();
6263       } else {
6264         SkipToField(FD, false);
6265         Value = &Result.getStructField(FD->getFieldIndex());
6266       }
6267     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6268       // Walk the indirect field decl's chain to find the object to initialize,
6269       // and make sure we've initialized every step along it.
6270       auto IndirectFieldChain = IFD->chain();
6271       for (auto *C : IndirectFieldChain) {
6272         FD = cast<FieldDecl>(C);
6273         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6274         // Switch the union field if it differs. This happens if we had
6275         // preceding zero-initialization, and we're now initializing a union
6276         // subobject other than the first.
6277         // FIXME: In this case, the values of the other subobjects are
6278         // specified, since zero-initialization sets all padding bits to zero.
6279         if (!Value->hasValue() ||
6280             (Value->isUnion() && Value->getUnionField() != FD)) {
6281           if (CD->isUnion())
6282             *Value = APValue(FD);
6283           else
6284             // FIXME: This immediately starts the lifetime of all members of
6285             // an anonymous struct. It would be preferable to strictly start
6286             // member lifetime in initialization order.
6287             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6288         }
6289         // Store Subobject as its parent before updating it for the last element
6290         // in the chain.
6291         if (C == IndirectFieldChain.back())
6292           SubobjectParent = Subobject;
6293         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6294           return false;
6295         if (CD->isUnion())
6296           Value = &Value->getUnionValue();
6297         else {
6298           if (C == IndirectFieldChain.front() && !RD->isUnion())
6299             SkipToField(FD, true);
6300           Value = &Value->getStructField(FD->getFieldIndex());
6301         }
6302       }
6303     } else {
6304       llvm_unreachable("unknown base initializer kind");
6305     }
6306 
6307     // Need to override This for implicit field initializers as in this case
6308     // This refers to innermost anonymous struct/union containing initializer,
6309     // not to currently constructed class.
6310     const Expr *Init = I->getInit();
6311     if (Init->isValueDependent()) {
6312       if (!EvaluateDependentExpr(Init, Info))
6313         return false;
6314     } else {
6315       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6316                                     isa<CXXDefaultInitExpr>(Init));
6317       FullExpressionRAII InitScope(Info);
6318       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6319           (FD && FD->isBitField() &&
6320            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6321         // If we're checking for a potential constant expression, evaluate all
6322         // initializers even if some of them fail.
6323         if (!Info.noteFailure())
6324           return false;
6325         Success = false;
6326       }
6327     }
6328 
6329     // This is the point at which the dynamic type of the object becomes this
6330     // class type.
6331     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6332       EvalObj.finishedConstructingBases();
6333   }
6334 
6335   // Default-initialize any remaining fields.
6336   if (!RD->isUnion()) {
6337     for (; FieldIt != RD->field_end(); ++FieldIt) {
6338       if (!FieldIt->isUnnamedBitfield())
6339         Success &= getDefaultInitValue(
6340             FieldIt->getType(),
6341             Result.getStructField(FieldIt->getFieldIndex()));
6342     }
6343   }
6344 
6345   EvalObj.finishedConstructingFields();
6346 
6347   return Success &&
6348          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6349          LifetimeExtendedScope.destroy();
6350 }
6351 
6352 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6353                                   ArrayRef<const Expr*> Args,
6354                                   const CXXConstructorDecl *Definition,
6355                                   EvalInfo &Info, APValue &Result) {
6356   CallScopeRAII CallScope(Info);
6357   CallRef Call = Info.CurrentCall->createCall(Definition);
6358   if (!EvaluateArgs(Args, Call, Info, Definition))
6359     return false;
6360 
6361   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6362          CallScope.destroy();
6363 }
6364 
6365 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6366                                   const LValue &This, APValue &Value,
6367                                   QualType T) {
6368   // Objects can only be destroyed while they're within their lifetimes.
6369   // FIXME: We have no representation for whether an object of type nullptr_t
6370   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6371   // as indeterminate instead?
6372   if (Value.isAbsent() && !T->isNullPtrType()) {
6373     APValue Printable;
6374     This.moveInto(Printable);
6375     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6376       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6377     return false;
6378   }
6379 
6380   // Invent an expression for location purposes.
6381   // FIXME: We shouldn't need to do this.
6382   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6383 
6384   // For arrays, destroy elements right-to-left.
6385   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6386     uint64_t Size = CAT->getSize().getZExtValue();
6387     QualType ElemT = CAT->getElementType();
6388 
6389     LValue ElemLV = This;
6390     ElemLV.addArray(Info, &LocE, CAT);
6391     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6392       return false;
6393 
6394     // Ensure that we have actual array elements available to destroy; the
6395     // destructors might mutate the value, so we can't run them on the array
6396     // filler.
6397     if (Size && Size > Value.getArrayInitializedElts())
6398       expandArray(Value, Value.getArraySize() - 1);
6399 
6400     for (; Size != 0; --Size) {
6401       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6402       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6403           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6404         return false;
6405     }
6406 
6407     // End the lifetime of this array now.
6408     Value = APValue();
6409     return true;
6410   }
6411 
6412   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6413   if (!RD) {
6414     if (T.isDestructedType()) {
6415       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6416       return false;
6417     }
6418 
6419     Value = APValue();
6420     return true;
6421   }
6422 
6423   if (RD->getNumVBases()) {
6424     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6425     return false;
6426   }
6427 
6428   const CXXDestructorDecl *DD = RD->getDestructor();
6429   if (!DD && !RD->hasTrivialDestructor()) {
6430     Info.FFDiag(CallLoc);
6431     return false;
6432   }
6433 
6434   if (!DD || DD->isTrivial() ||
6435       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6436     // A trivial destructor just ends the lifetime of the object. Check for
6437     // this case before checking for a body, because we might not bother
6438     // building a body for a trivial destructor. Note that it doesn't matter
6439     // whether the destructor is constexpr in this case; all trivial
6440     // destructors are constexpr.
6441     //
6442     // If an anonymous union would be destroyed, some enclosing destructor must
6443     // have been explicitly defined, and the anonymous union destruction should
6444     // have no effect.
6445     Value = APValue();
6446     return true;
6447   }
6448 
6449   if (!Info.CheckCallLimit(CallLoc))
6450     return false;
6451 
6452   const FunctionDecl *Definition = nullptr;
6453   const Stmt *Body = DD->getBody(Definition);
6454 
6455   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6456     return false;
6457 
6458   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6459 
6460   // We're now in the period of destruction of this object.
6461   unsigned BasesLeft = RD->getNumBases();
6462   EvalInfo::EvaluatingDestructorRAII EvalObj(
6463       Info,
6464       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6465   if (!EvalObj.DidInsert) {
6466     // C++2a [class.dtor]p19:
6467     //   the behavior is undefined if the destructor is invoked for an object
6468     //   whose lifetime has ended
6469     // (Note that formally the lifetime ends when the period of destruction
6470     // begins, even though certain uses of the object remain valid until the
6471     // period of destruction ends.)
6472     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6473     return false;
6474   }
6475 
6476   // FIXME: Creating an APValue just to hold a nonexistent return value is
6477   // wasteful.
6478   APValue RetVal;
6479   StmtResult Ret = {RetVal, nullptr};
6480   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6481     return false;
6482 
6483   // A union destructor does not implicitly destroy its members.
6484   if (RD->isUnion())
6485     return true;
6486 
6487   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6488 
6489   // We don't have a good way to iterate fields in reverse, so collect all the
6490   // fields first and then walk them backwards.
6491   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6492   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6493     if (FD->isUnnamedBitfield())
6494       continue;
6495 
6496     LValue Subobject = This;
6497     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6498       return false;
6499 
6500     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6501     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6502                                FD->getType()))
6503       return false;
6504   }
6505 
6506   if (BasesLeft != 0)
6507     EvalObj.startedDestroyingBases();
6508 
6509   // Destroy base classes in reverse order.
6510   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6511     --BasesLeft;
6512 
6513     QualType BaseType = Base.getType();
6514     LValue Subobject = This;
6515     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6516                                 BaseType->getAsCXXRecordDecl(), &Layout))
6517       return false;
6518 
6519     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6520     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6521                                BaseType))
6522       return false;
6523   }
6524   assert(BasesLeft == 0 && "NumBases was wrong?");
6525 
6526   // The period of destruction ends now. The object is gone.
6527   Value = APValue();
6528   return true;
6529 }
6530 
6531 namespace {
6532 struct DestroyObjectHandler {
6533   EvalInfo &Info;
6534   const Expr *E;
6535   const LValue &This;
6536   const AccessKinds AccessKind;
6537 
6538   typedef bool result_type;
6539   bool failed() { return false; }
6540   bool found(APValue &Subobj, QualType SubobjType) {
6541     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6542                                  SubobjType);
6543   }
6544   bool found(APSInt &Value, QualType SubobjType) {
6545     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6546     return false;
6547   }
6548   bool found(APFloat &Value, QualType SubobjType) {
6549     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6550     return false;
6551   }
6552 };
6553 }
6554 
6555 /// Perform a destructor or pseudo-destructor call on the given object, which
6556 /// might in general not be a complete object.
6557 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6558                               const LValue &This, QualType ThisType) {
6559   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6560   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6561   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6562 }
6563 
6564 /// Destroy and end the lifetime of the given complete object.
6565 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6566                               APValue::LValueBase LVBase, APValue &Value,
6567                               QualType T) {
6568   // If we've had an unmodeled side-effect, we can't rely on mutable state
6569   // (such as the object we're about to destroy) being correct.
6570   if (Info.EvalStatus.HasSideEffects)
6571     return false;
6572 
6573   LValue LV;
6574   LV.set({LVBase});
6575   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6576 }
6577 
6578 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6579 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6580                                   LValue &Result) {
6581   if (Info.checkingPotentialConstantExpression() ||
6582       Info.SpeculativeEvaluationDepth)
6583     return false;
6584 
6585   // This is permitted only within a call to std::allocator<T>::allocate.
6586   auto Caller = Info.getStdAllocatorCaller("allocate");
6587   if (!Caller) {
6588     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6589                                      ? diag::note_constexpr_new_untyped
6590                                      : diag::note_constexpr_new);
6591     return false;
6592   }
6593 
6594   QualType ElemType = Caller.ElemType;
6595   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6596     Info.FFDiag(E->getExprLoc(),
6597                 diag::note_constexpr_new_not_complete_object_type)
6598         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6599     return false;
6600   }
6601 
6602   APSInt ByteSize;
6603   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6604     return false;
6605   bool IsNothrow = false;
6606   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6607     EvaluateIgnoredValue(Info, E->getArg(I));
6608     IsNothrow |= E->getType()->isNothrowT();
6609   }
6610 
6611   CharUnits ElemSize;
6612   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6613     return false;
6614   APInt Size, Remainder;
6615   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6616   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6617   if (Remainder != 0) {
6618     // This likely indicates a bug in the implementation of 'std::allocator'.
6619     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6620         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6621     return false;
6622   }
6623 
6624   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6625     if (IsNothrow) {
6626       Result.setNull(Info.Ctx, E->getType());
6627       return true;
6628     }
6629 
6630     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6631     return false;
6632   }
6633 
6634   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6635                                                      ArrayType::Normal, 0);
6636   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6637   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6638   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6639   return true;
6640 }
6641 
6642 static bool hasVirtualDestructor(QualType T) {
6643   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6644     if (CXXDestructorDecl *DD = RD->getDestructor())
6645       return DD->isVirtual();
6646   return false;
6647 }
6648 
6649 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6650   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6651     if (CXXDestructorDecl *DD = RD->getDestructor())
6652       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6653   return nullptr;
6654 }
6655 
6656 /// Check that the given object is a suitable pointer to a heap allocation that
6657 /// still exists and is of the right kind for the purpose of a deletion.
6658 ///
6659 /// On success, returns the heap allocation to deallocate. On failure, produces
6660 /// a diagnostic and returns None.
6661 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6662                                             const LValue &Pointer,
6663                                             DynAlloc::Kind DeallocKind) {
6664   auto PointerAsString = [&] {
6665     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6666   };
6667 
6668   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6669   if (!DA) {
6670     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6671         << PointerAsString();
6672     if (Pointer.Base)
6673       NoteLValueLocation(Info, Pointer.Base);
6674     return None;
6675   }
6676 
6677   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6678   if (!Alloc) {
6679     Info.FFDiag(E, diag::note_constexpr_double_delete);
6680     return None;
6681   }
6682 
6683   QualType AllocType = Pointer.Base.getDynamicAllocType();
6684   if (DeallocKind != (*Alloc)->getKind()) {
6685     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6686         << DeallocKind << (*Alloc)->getKind() << AllocType;
6687     NoteLValueLocation(Info, Pointer.Base);
6688     return None;
6689   }
6690 
6691   bool Subobject = false;
6692   if (DeallocKind == DynAlloc::New) {
6693     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6694                 Pointer.Designator.isOnePastTheEnd();
6695   } else {
6696     Subobject = Pointer.Designator.Entries.size() != 1 ||
6697                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6698   }
6699   if (Subobject) {
6700     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6701         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6702     return None;
6703   }
6704 
6705   return Alloc;
6706 }
6707 
6708 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6709 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6710   if (Info.checkingPotentialConstantExpression() ||
6711       Info.SpeculativeEvaluationDepth)
6712     return false;
6713 
6714   // This is permitted only within a call to std::allocator<T>::deallocate.
6715   if (!Info.getStdAllocatorCaller("deallocate")) {
6716     Info.FFDiag(E->getExprLoc());
6717     return true;
6718   }
6719 
6720   LValue Pointer;
6721   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6722     return false;
6723   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6724     EvaluateIgnoredValue(Info, E->getArg(I));
6725 
6726   if (Pointer.Designator.Invalid)
6727     return false;
6728 
6729   // Deleting a null pointer would have no effect, but it's not permitted by
6730   // std::allocator<T>::deallocate's contract.
6731   if (Pointer.isNullPointer()) {
6732     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6733     return true;
6734   }
6735 
6736   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6737     return false;
6738 
6739   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6740   return true;
6741 }
6742 
6743 //===----------------------------------------------------------------------===//
6744 // Generic Evaluation
6745 //===----------------------------------------------------------------------===//
6746 namespace {
6747 
6748 class BitCastBuffer {
6749   // FIXME: We're going to need bit-level granularity when we support
6750   // bit-fields.
6751   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6752   // we don't support a host or target where that is the case. Still, we should
6753   // use a more generic type in case we ever do.
6754   SmallVector<Optional<unsigned char>, 32> Bytes;
6755 
6756   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6757                 "Need at least 8 bit unsigned char");
6758 
6759   bool TargetIsLittleEndian;
6760 
6761 public:
6762   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6763       : Bytes(Width.getQuantity()),
6764         TargetIsLittleEndian(TargetIsLittleEndian) {}
6765 
6766   LLVM_NODISCARD
6767   bool readObject(CharUnits Offset, CharUnits Width,
6768                   SmallVectorImpl<unsigned char> &Output) const {
6769     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6770       // If a byte of an integer is uninitialized, then the whole integer is
6771       // uninitialized.
6772       if (!Bytes[I.getQuantity()])
6773         return false;
6774       Output.push_back(*Bytes[I.getQuantity()]);
6775     }
6776     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6777       std::reverse(Output.begin(), Output.end());
6778     return true;
6779   }
6780 
6781   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6782     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6783       std::reverse(Input.begin(), Input.end());
6784 
6785     size_t Index = 0;
6786     for (unsigned char Byte : Input) {
6787       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6788       Bytes[Offset.getQuantity() + Index] = Byte;
6789       ++Index;
6790     }
6791   }
6792 
6793   size_t size() { return Bytes.size(); }
6794 };
6795 
6796 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6797 /// target would represent the value at runtime.
6798 class APValueToBufferConverter {
6799   EvalInfo &Info;
6800   BitCastBuffer Buffer;
6801   const CastExpr *BCE;
6802 
6803   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6804                            const CastExpr *BCE)
6805       : Info(Info),
6806         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6807         BCE(BCE) {}
6808 
6809   bool visit(const APValue &Val, QualType Ty) {
6810     return visit(Val, Ty, CharUnits::fromQuantity(0));
6811   }
6812 
6813   // Write out Val with type Ty into Buffer starting at Offset.
6814   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6815     assert((size_t)Offset.getQuantity() <= Buffer.size());
6816 
6817     // As a special case, nullptr_t has an indeterminate value.
6818     if (Ty->isNullPtrType())
6819       return true;
6820 
6821     // Dig through Src to find the byte at SrcOffset.
6822     switch (Val.getKind()) {
6823     case APValue::Indeterminate:
6824     case APValue::None:
6825       return true;
6826 
6827     case APValue::Int:
6828       return visitInt(Val.getInt(), Ty, Offset);
6829     case APValue::Float:
6830       return visitFloat(Val.getFloat(), Ty, Offset);
6831     case APValue::Array:
6832       return visitArray(Val, Ty, Offset);
6833     case APValue::Struct:
6834       return visitRecord(Val, Ty, Offset);
6835 
6836     case APValue::ComplexInt:
6837     case APValue::ComplexFloat:
6838     case APValue::Vector:
6839     case APValue::FixedPoint:
6840       // FIXME: We should support these.
6841 
6842     case APValue::Union:
6843     case APValue::MemberPointer:
6844     case APValue::AddrLabelDiff: {
6845       Info.FFDiag(BCE->getBeginLoc(),
6846                   diag::note_constexpr_bit_cast_unsupported_type)
6847           << Ty;
6848       return false;
6849     }
6850 
6851     case APValue::LValue:
6852       llvm_unreachable("LValue subobject in bit_cast?");
6853     }
6854     llvm_unreachable("Unhandled APValue::ValueKind");
6855   }
6856 
6857   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6858     const RecordDecl *RD = Ty->getAsRecordDecl();
6859     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6860 
6861     // Visit the base classes.
6862     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6863       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6864         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6865         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6866 
6867         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6868                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6869           return false;
6870       }
6871     }
6872 
6873     // Visit the fields.
6874     unsigned FieldIdx = 0;
6875     for (FieldDecl *FD : RD->fields()) {
6876       if (FD->isBitField()) {
6877         Info.FFDiag(BCE->getBeginLoc(),
6878                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6879         return false;
6880       }
6881 
6882       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6883 
6884       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6885              "only bit-fields can have sub-char alignment");
6886       CharUnits FieldOffset =
6887           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6888       QualType FieldTy = FD->getType();
6889       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6890         return false;
6891       ++FieldIdx;
6892     }
6893 
6894     return true;
6895   }
6896 
6897   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6898     const auto *CAT =
6899         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6900     if (!CAT)
6901       return false;
6902 
6903     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6904     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6905     unsigned ArraySize = Val.getArraySize();
6906     // First, initialize the initialized elements.
6907     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6908       const APValue &SubObj = Val.getArrayInitializedElt(I);
6909       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6910         return false;
6911     }
6912 
6913     // Next, initialize the rest of the array using the filler.
6914     if (Val.hasArrayFiller()) {
6915       const APValue &Filler = Val.getArrayFiller();
6916       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6917         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6918           return false;
6919       }
6920     }
6921 
6922     return true;
6923   }
6924 
6925   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6926     APSInt AdjustedVal = Val;
6927     unsigned Width = AdjustedVal.getBitWidth();
6928     if (Ty->isBooleanType()) {
6929       Width = Info.Ctx.getTypeSize(Ty);
6930       AdjustedVal = AdjustedVal.extend(Width);
6931     }
6932 
6933     SmallVector<unsigned char, 8> Bytes(Width / 8);
6934     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6935     Buffer.writeObject(Offset, Bytes);
6936     return true;
6937   }
6938 
6939   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6940     APSInt AsInt(Val.bitcastToAPInt());
6941     return visitInt(AsInt, Ty, Offset);
6942   }
6943 
6944 public:
6945   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6946                                          const CastExpr *BCE) {
6947     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6948     APValueToBufferConverter Converter(Info, DstSize, BCE);
6949     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6950       return None;
6951     return Converter.Buffer;
6952   }
6953 };
6954 
6955 /// Write an BitCastBuffer into an APValue.
6956 class BufferToAPValueConverter {
6957   EvalInfo &Info;
6958   const BitCastBuffer &Buffer;
6959   const CastExpr *BCE;
6960 
6961   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6962                            const CastExpr *BCE)
6963       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6964 
6965   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6966   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6967   // Ideally this will be unreachable.
6968   llvm::NoneType unsupportedType(QualType Ty) {
6969     Info.FFDiag(BCE->getBeginLoc(),
6970                 diag::note_constexpr_bit_cast_unsupported_type)
6971         << Ty;
6972     return None;
6973   }
6974 
6975   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6976     Info.FFDiag(BCE->getBeginLoc(),
6977                 diag::note_constexpr_bit_cast_unrepresentable_value)
6978         << Ty << toString(Val, /*Radix=*/10);
6979     return None;
6980   }
6981 
6982   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6983                           const EnumType *EnumSugar = nullptr) {
6984     if (T->isNullPtrType()) {
6985       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6986       return APValue((Expr *)nullptr,
6987                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6988                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6989     }
6990 
6991     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6992 
6993     // Work around floating point types that contain unused padding bytes. This
6994     // is really just `long double` on x86, which is the only fundamental type
6995     // with padding bytes.
6996     if (T->isRealFloatingType()) {
6997       const llvm::fltSemantics &Semantics =
6998           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6999       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7000       assert(NumBits % 8 == 0);
7001       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7002       if (NumBytes != SizeOf)
7003         SizeOf = NumBytes;
7004     }
7005 
7006     SmallVector<uint8_t, 8> Bytes;
7007     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7008       // If this is std::byte or unsigned char, then its okay to store an
7009       // indeterminate value.
7010       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7011       bool IsUChar =
7012           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7013                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7014       if (!IsStdByte && !IsUChar) {
7015         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7016         Info.FFDiag(BCE->getExprLoc(),
7017                     diag::note_constexpr_bit_cast_indet_dest)
7018             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7019         return None;
7020       }
7021 
7022       return APValue::IndeterminateValue();
7023     }
7024 
7025     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7026     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7027 
7028     if (T->isIntegralOrEnumerationType()) {
7029       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7030 
7031       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7032       if (IntWidth != Val.getBitWidth()) {
7033         APSInt Truncated = Val.trunc(IntWidth);
7034         if (Truncated.extend(Val.getBitWidth()) != Val)
7035           return unrepresentableValue(QualType(T, 0), Val);
7036         Val = Truncated;
7037       }
7038 
7039       return APValue(Val);
7040     }
7041 
7042     if (T->isRealFloatingType()) {
7043       const llvm::fltSemantics &Semantics =
7044           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7045       return APValue(APFloat(Semantics, Val));
7046     }
7047 
7048     return unsupportedType(QualType(T, 0));
7049   }
7050 
7051   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7052     const RecordDecl *RD = RTy->getAsRecordDecl();
7053     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7054 
7055     unsigned NumBases = 0;
7056     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7057       NumBases = CXXRD->getNumBases();
7058 
7059     APValue ResultVal(APValue::UninitStruct(), NumBases,
7060                       std::distance(RD->field_begin(), RD->field_end()));
7061 
7062     // Visit the base classes.
7063     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7064       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7065         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7066         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7067         if (BaseDecl->isEmpty() ||
7068             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7069           continue;
7070 
7071         Optional<APValue> SubObj = visitType(
7072             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7073         if (!SubObj)
7074           return None;
7075         ResultVal.getStructBase(I) = *SubObj;
7076       }
7077     }
7078 
7079     // Visit the fields.
7080     unsigned FieldIdx = 0;
7081     for (FieldDecl *FD : RD->fields()) {
7082       // FIXME: We don't currently support bit-fields. A lot of the logic for
7083       // this is in CodeGen, so we need to factor it around.
7084       if (FD->isBitField()) {
7085         Info.FFDiag(BCE->getBeginLoc(),
7086                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7087         return None;
7088       }
7089 
7090       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7091       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7092 
7093       CharUnits FieldOffset =
7094           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7095           Offset;
7096       QualType FieldTy = FD->getType();
7097       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7098       if (!SubObj)
7099         return None;
7100       ResultVal.getStructField(FieldIdx) = *SubObj;
7101       ++FieldIdx;
7102     }
7103 
7104     return ResultVal;
7105   }
7106 
7107   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7108     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7109     assert(!RepresentationType.isNull() &&
7110            "enum forward decl should be caught by Sema");
7111     const auto *AsBuiltin =
7112         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7113     // Recurse into the underlying type. Treat std::byte transparently as
7114     // unsigned char.
7115     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7116   }
7117 
7118   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7119     size_t Size = Ty->getSize().getLimitedValue();
7120     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7121 
7122     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7123     for (size_t I = 0; I != Size; ++I) {
7124       Optional<APValue> ElementValue =
7125           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7126       if (!ElementValue)
7127         return None;
7128       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7129     }
7130 
7131     return ArrayValue;
7132   }
7133 
7134   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7135     return unsupportedType(QualType(Ty, 0));
7136   }
7137 
7138   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7139     QualType Can = Ty.getCanonicalType();
7140 
7141     switch (Can->getTypeClass()) {
7142 #define TYPE(Class, Base)                                                      \
7143   case Type::Class:                                                            \
7144     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7145 #define ABSTRACT_TYPE(Class, Base)
7146 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7147   case Type::Class:                                                            \
7148     llvm_unreachable("non-canonical type should be impossible!");
7149 #define DEPENDENT_TYPE(Class, Base)                                            \
7150   case Type::Class:                                                            \
7151     llvm_unreachable(                                                          \
7152         "dependent types aren't supported in the constant evaluator!");
7153 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7154   case Type::Class:                                                            \
7155     llvm_unreachable("either dependent or not canonical!");
7156 #include "clang/AST/TypeNodes.inc"
7157     }
7158     llvm_unreachable("Unhandled Type::TypeClass");
7159   }
7160 
7161 public:
7162   // Pull out a full value of type DstType.
7163   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7164                                    const CastExpr *BCE) {
7165     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7166     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7167   }
7168 };
7169 
7170 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7171                                                  QualType Ty, EvalInfo *Info,
7172                                                  const ASTContext &Ctx,
7173                                                  bool CheckingDest) {
7174   Ty = Ty.getCanonicalType();
7175 
7176   auto diag = [&](int Reason) {
7177     if (Info)
7178       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7179           << CheckingDest << (Reason == 4) << Reason;
7180     return false;
7181   };
7182   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7183     if (Info)
7184       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7185           << NoteTy << Construct << Ty;
7186     return false;
7187   };
7188 
7189   if (Ty->isUnionType())
7190     return diag(0);
7191   if (Ty->isPointerType())
7192     return diag(1);
7193   if (Ty->isMemberPointerType())
7194     return diag(2);
7195   if (Ty.isVolatileQualified())
7196     return diag(3);
7197 
7198   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7199     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7200       for (CXXBaseSpecifier &BS : CXXRD->bases())
7201         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7202                                                   CheckingDest))
7203           return note(1, BS.getType(), BS.getBeginLoc());
7204     }
7205     for (FieldDecl *FD : Record->fields()) {
7206       if (FD->getType()->isReferenceType())
7207         return diag(4);
7208       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7209                                                 CheckingDest))
7210         return note(0, FD->getType(), FD->getBeginLoc());
7211     }
7212   }
7213 
7214   if (Ty->isArrayType() &&
7215       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7216                                             Info, Ctx, CheckingDest))
7217     return false;
7218 
7219   return true;
7220 }
7221 
7222 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7223                                              const ASTContext &Ctx,
7224                                              const CastExpr *BCE) {
7225   bool DestOK = checkBitCastConstexprEligibilityType(
7226       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7227   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7228                                 BCE->getBeginLoc(),
7229                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7230   return SourceOK;
7231 }
7232 
7233 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7234                                         APValue &SourceValue,
7235                                         const CastExpr *BCE) {
7236   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7237          "no host or target supports non 8-bit chars");
7238   assert(SourceValue.isLValue() &&
7239          "LValueToRValueBitcast requires an lvalue operand!");
7240 
7241   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7242     return false;
7243 
7244   LValue SourceLValue;
7245   APValue SourceRValue;
7246   SourceLValue.setFrom(Info.Ctx, SourceValue);
7247   if (!handleLValueToRValueConversion(
7248           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7249           SourceRValue, /*WantObjectRepresentation=*/true))
7250     return false;
7251 
7252   // Read out SourceValue into a char buffer.
7253   Optional<BitCastBuffer> Buffer =
7254       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7255   if (!Buffer)
7256     return false;
7257 
7258   // Write out the buffer into a new APValue.
7259   Optional<APValue> MaybeDestValue =
7260       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7261   if (!MaybeDestValue)
7262     return false;
7263 
7264   DestValue = std::move(*MaybeDestValue);
7265   return true;
7266 }
7267 
7268 template <class Derived>
7269 class ExprEvaluatorBase
7270   : public ConstStmtVisitor<Derived, bool> {
7271 private:
7272   Derived &getDerived() { return static_cast<Derived&>(*this); }
7273   bool DerivedSuccess(const APValue &V, const Expr *E) {
7274     return getDerived().Success(V, E);
7275   }
7276   bool DerivedZeroInitialization(const Expr *E) {
7277     return getDerived().ZeroInitialization(E);
7278   }
7279 
7280   // Check whether a conditional operator with a non-constant condition is a
7281   // potential constant expression. If neither arm is a potential constant
7282   // expression, then the conditional operator is not either.
7283   template<typename ConditionalOperator>
7284   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7285     assert(Info.checkingPotentialConstantExpression());
7286 
7287     // Speculatively evaluate both arms.
7288     SmallVector<PartialDiagnosticAt, 8> Diag;
7289     {
7290       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7291       StmtVisitorTy::Visit(E->getFalseExpr());
7292       if (Diag.empty())
7293         return;
7294     }
7295 
7296     {
7297       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7298       Diag.clear();
7299       StmtVisitorTy::Visit(E->getTrueExpr());
7300       if (Diag.empty())
7301         return;
7302     }
7303 
7304     Error(E, diag::note_constexpr_conditional_never_const);
7305   }
7306 
7307 
7308   template<typename ConditionalOperator>
7309   bool HandleConditionalOperator(const ConditionalOperator *E) {
7310     bool BoolResult;
7311     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7312       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7313         CheckPotentialConstantConditional(E);
7314         return false;
7315       }
7316       if (Info.noteFailure()) {
7317         StmtVisitorTy::Visit(E->getTrueExpr());
7318         StmtVisitorTy::Visit(E->getFalseExpr());
7319       }
7320       return false;
7321     }
7322 
7323     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7324     return StmtVisitorTy::Visit(EvalExpr);
7325   }
7326 
7327 protected:
7328   EvalInfo &Info;
7329   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7330   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7331 
7332   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7333     return Info.CCEDiag(E, D);
7334   }
7335 
7336   bool ZeroInitialization(const Expr *E) { return Error(E); }
7337 
7338 public:
7339   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7340 
7341   EvalInfo &getEvalInfo() { return Info; }
7342 
7343   /// Report an evaluation error. This should only be called when an error is
7344   /// first discovered. When propagating an error, just return false.
7345   bool Error(const Expr *E, diag::kind D) {
7346     Info.FFDiag(E, D);
7347     return false;
7348   }
7349   bool Error(const Expr *E) {
7350     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7351   }
7352 
7353   bool VisitStmt(const Stmt *) {
7354     llvm_unreachable("Expression evaluator should not be called on stmts");
7355   }
7356   bool VisitExpr(const Expr *E) {
7357     return Error(E);
7358   }
7359 
7360   bool VisitConstantExpr(const ConstantExpr *E) {
7361     if (E->hasAPValueResult())
7362       return DerivedSuccess(E->getAPValueResult(), E);
7363 
7364     return StmtVisitorTy::Visit(E->getSubExpr());
7365   }
7366 
7367   bool VisitParenExpr(const ParenExpr *E)
7368     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7369   bool VisitUnaryExtension(const UnaryOperator *E)
7370     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7371   bool VisitUnaryPlus(const UnaryOperator *E)
7372     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7373   bool VisitChooseExpr(const ChooseExpr *E)
7374     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7375   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7376     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7377   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7378     { return StmtVisitorTy::Visit(E->getReplacement()); }
7379   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7380     TempVersionRAII RAII(*Info.CurrentCall);
7381     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7382     return StmtVisitorTy::Visit(E->getExpr());
7383   }
7384   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7385     TempVersionRAII RAII(*Info.CurrentCall);
7386     // The initializer may not have been parsed yet, or might be erroneous.
7387     if (!E->getExpr())
7388       return Error(E);
7389     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7390     return StmtVisitorTy::Visit(E->getExpr());
7391   }
7392 
7393   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7394     FullExpressionRAII Scope(Info);
7395     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7396   }
7397 
7398   // Temporaries are registered when created, so we don't care about
7399   // CXXBindTemporaryExpr.
7400   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7401     return StmtVisitorTy::Visit(E->getSubExpr());
7402   }
7403 
7404   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7405     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7406     return static_cast<Derived*>(this)->VisitCastExpr(E);
7407   }
7408   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7409     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7410       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7411     return static_cast<Derived*>(this)->VisitCastExpr(E);
7412   }
7413   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7414     return static_cast<Derived*>(this)->VisitCastExpr(E);
7415   }
7416 
7417   bool VisitBinaryOperator(const BinaryOperator *E) {
7418     switch (E->getOpcode()) {
7419     default:
7420       return Error(E);
7421 
7422     case BO_Comma:
7423       VisitIgnoredValue(E->getLHS());
7424       return StmtVisitorTy::Visit(E->getRHS());
7425 
7426     case BO_PtrMemD:
7427     case BO_PtrMemI: {
7428       LValue Obj;
7429       if (!HandleMemberPointerAccess(Info, E, Obj))
7430         return false;
7431       APValue Result;
7432       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7433         return false;
7434       return DerivedSuccess(Result, E);
7435     }
7436     }
7437   }
7438 
7439   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7440     return StmtVisitorTy::Visit(E->getSemanticForm());
7441   }
7442 
7443   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7444     // Evaluate and cache the common expression. We treat it as a temporary,
7445     // even though it's not quite the same thing.
7446     LValue CommonLV;
7447     if (!Evaluate(Info.CurrentCall->createTemporary(
7448                       E->getOpaqueValue(),
7449                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7450                       ScopeKind::FullExpression, CommonLV),
7451                   Info, E->getCommon()))
7452       return false;
7453 
7454     return HandleConditionalOperator(E);
7455   }
7456 
7457   bool VisitConditionalOperator(const ConditionalOperator *E) {
7458     bool IsBcpCall = false;
7459     // If the condition (ignoring parens) is a __builtin_constant_p call,
7460     // the result is a constant expression if it can be folded without
7461     // side-effects. This is an important GNU extension. See GCC PR38377
7462     // for discussion.
7463     if (const CallExpr *CallCE =
7464           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7465       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7466         IsBcpCall = true;
7467 
7468     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7469     // constant expression; we can't check whether it's potentially foldable.
7470     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7471     // it would return 'false' in this mode.
7472     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7473       return false;
7474 
7475     FoldConstant Fold(Info, IsBcpCall);
7476     if (!HandleConditionalOperator(E)) {
7477       Fold.keepDiagnostics();
7478       return false;
7479     }
7480 
7481     return true;
7482   }
7483 
7484   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7485     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7486       return DerivedSuccess(*Value, E);
7487 
7488     const Expr *Source = E->getSourceExpr();
7489     if (!Source)
7490       return Error(E);
7491     if (Source == E) {
7492       assert(0 && "OpaqueValueExpr recursively refers to itself");
7493       return Error(E);
7494     }
7495     return StmtVisitorTy::Visit(Source);
7496   }
7497 
7498   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7499     for (const Expr *SemE : E->semantics()) {
7500       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7501         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7502         // result expression: there could be two different LValues that would
7503         // refer to the same object in that case, and we can't model that.
7504         if (SemE == E->getResultExpr())
7505           return Error(E);
7506 
7507         // Unique OVEs get evaluated if and when we encounter them when
7508         // emitting the rest of the semantic form, rather than eagerly.
7509         if (OVE->isUnique())
7510           continue;
7511 
7512         LValue LV;
7513         if (!Evaluate(Info.CurrentCall->createTemporary(
7514                           OVE, getStorageType(Info.Ctx, OVE),
7515                           ScopeKind::FullExpression, LV),
7516                       Info, OVE->getSourceExpr()))
7517           return false;
7518       } else if (SemE == E->getResultExpr()) {
7519         if (!StmtVisitorTy::Visit(SemE))
7520           return false;
7521       } else {
7522         if (!EvaluateIgnoredValue(Info, SemE))
7523           return false;
7524       }
7525     }
7526     return true;
7527   }
7528 
7529   bool VisitCallExpr(const CallExpr *E) {
7530     APValue Result;
7531     if (!handleCallExpr(E, Result, nullptr))
7532       return false;
7533     return DerivedSuccess(Result, E);
7534   }
7535 
7536   bool handleCallExpr(const CallExpr *E, APValue &Result,
7537                      const LValue *ResultSlot) {
7538     CallScopeRAII CallScope(Info);
7539 
7540     const Expr *Callee = E->getCallee()->IgnoreParens();
7541     QualType CalleeType = Callee->getType();
7542 
7543     const FunctionDecl *FD = nullptr;
7544     LValue *This = nullptr, ThisVal;
7545     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7546     bool HasQualifier = false;
7547 
7548     CallRef Call;
7549 
7550     // Extract function decl and 'this' pointer from the callee.
7551     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7552       const CXXMethodDecl *Member = nullptr;
7553       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7554         // Explicit bound member calls, such as x.f() or p->g();
7555         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7556           return false;
7557         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7558         if (!Member)
7559           return Error(Callee);
7560         This = &ThisVal;
7561         HasQualifier = ME->hasQualifier();
7562       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7563         // Indirect bound member calls ('.*' or '->*').
7564         const ValueDecl *D =
7565             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7566         if (!D)
7567           return false;
7568         Member = dyn_cast<CXXMethodDecl>(D);
7569         if (!Member)
7570           return Error(Callee);
7571         This = &ThisVal;
7572       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7573         if (!Info.getLangOpts().CPlusPlus20)
7574           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7575         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7576                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7577       } else
7578         return Error(Callee);
7579       FD = Member;
7580     } else if (CalleeType->isFunctionPointerType()) {
7581       LValue CalleeLV;
7582       if (!EvaluatePointer(Callee, CalleeLV, Info))
7583         return false;
7584 
7585       if (!CalleeLV.getLValueOffset().isZero())
7586         return Error(Callee);
7587       FD = dyn_cast_or_null<FunctionDecl>(
7588           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7589       if (!FD)
7590         return Error(Callee);
7591       // Don't call function pointers which have been cast to some other type.
7592       // Per DR (no number yet), the caller and callee can differ in noexcept.
7593       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7594         CalleeType->getPointeeType(), FD->getType())) {
7595         return Error(E);
7596       }
7597 
7598       // For an (overloaded) assignment expression, evaluate the RHS before the
7599       // LHS.
7600       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7601       if (OCE && OCE->isAssignmentOp()) {
7602         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7603         Call = Info.CurrentCall->createCall(FD);
7604         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7605                           Info, FD, /*RightToLeft=*/true))
7606           return false;
7607       }
7608 
7609       // Overloaded operator calls to member functions are represented as normal
7610       // calls with '*this' as the first argument.
7611       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7612       if (MD && !MD->isStatic()) {
7613         // FIXME: When selecting an implicit conversion for an overloaded
7614         // operator delete, we sometimes try to evaluate calls to conversion
7615         // operators without a 'this' parameter!
7616         if (Args.empty())
7617           return Error(E);
7618 
7619         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7620           return false;
7621         This = &ThisVal;
7622         Args = Args.slice(1);
7623       } else if (MD && MD->isLambdaStaticInvoker()) {
7624         // Map the static invoker for the lambda back to the call operator.
7625         // Conveniently, we don't have to slice out the 'this' argument (as is
7626         // being done for the non-static case), since a static member function
7627         // doesn't have an implicit argument passed in.
7628         const CXXRecordDecl *ClosureClass = MD->getParent();
7629         assert(
7630             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7631             "Number of captures must be zero for conversion to function-ptr");
7632 
7633         const CXXMethodDecl *LambdaCallOp =
7634             ClosureClass->getLambdaCallOperator();
7635 
7636         // Set 'FD', the function that will be called below, to the call
7637         // operator.  If the closure object represents a generic lambda, find
7638         // the corresponding specialization of the call operator.
7639 
7640         if (ClosureClass->isGenericLambda()) {
7641           assert(MD->isFunctionTemplateSpecialization() &&
7642                  "A generic lambda's static-invoker function must be a "
7643                  "template specialization");
7644           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7645           FunctionTemplateDecl *CallOpTemplate =
7646               LambdaCallOp->getDescribedFunctionTemplate();
7647           void *InsertPos = nullptr;
7648           FunctionDecl *CorrespondingCallOpSpecialization =
7649               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7650           assert(CorrespondingCallOpSpecialization &&
7651                  "We must always have a function call operator specialization "
7652                  "that corresponds to our static invoker specialization");
7653           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7654         } else
7655           FD = LambdaCallOp;
7656       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7657         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7658             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7659           LValue Ptr;
7660           if (!HandleOperatorNewCall(Info, E, Ptr))
7661             return false;
7662           Ptr.moveInto(Result);
7663           return CallScope.destroy();
7664         } else {
7665           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7666         }
7667       }
7668     } else
7669       return Error(E);
7670 
7671     // Evaluate the arguments now if we've not already done so.
7672     if (!Call) {
7673       Call = Info.CurrentCall->createCall(FD);
7674       if (!EvaluateArgs(Args, Call, Info, FD))
7675         return false;
7676     }
7677 
7678     SmallVector<QualType, 4> CovariantAdjustmentPath;
7679     if (This) {
7680       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7681       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7682         // Perform virtual dispatch, if necessary.
7683         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7684                                    CovariantAdjustmentPath);
7685         if (!FD)
7686           return false;
7687       } else {
7688         // Check that the 'this' pointer points to an object of the right type.
7689         // FIXME: If this is an assignment operator call, we may need to change
7690         // the active union member before we check this.
7691         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7692           return false;
7693       }
7694     }
7695 
7696     // Destructor calls are different enough that they have their own codepath.
7697     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7698       assert(This && "no 'this' pointer for destructor call");
7699       return HandleDestruction(Info, E, *This,
7700                                Info.Ctx.getRecordType(DD->getParent())) &&
7701              CallScope.destroy();
7702     }
7703 
7704     const FunctionDecl *Definition = nullptr;
7705     Stmt *Body = FD->getBody(Definition);
7706 
7707     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7708         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7709                             Body, Info, Result, ResultSlot))
7710       return false;
7711 
7712     if (!CovariantAdjustmentPath.empty() &&
7713         !HandleCovariantReturnAdjustment(Info, E, Result,
7714                                          CovariantAdjustmentPath))
7715       return false;
7716 
7717     return CallScope.destroy();
7718   }
7719 
7720   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7721     return StmtVisitorTy::Visit(E->getInitializer());
7722   }
7723   bool VisitInitListExpr(const InitListExpr *E) {
7724     if (E->getNumInits() == 0)
7725       return DerivedZeroInitialization(E);
7726     if (E->getNumInits() == 1)
7727       return StmtVisitorTy::Visit(E->getInit(0));
7728     return Error(E);
7729   }
7730   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7731     return DerivedZeroInitialization(E);
7732   }
7733   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7734     return DerivedZeroInitialization(E);
7735   }
7736   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7737     return DerivedZeroInitialization(E);
7738   }
7739 
7740   /// A member expression where the object is a prvalue is itself a prvalue.
7741   bool VisitMemberExpr(const MemberExpr *E) {
7742     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7743            "missing temporary materialization conversion");
7744     assert(!E->isArrow() && "missing call to bound member function?");
7745 
7746     APValue Val;
7747     if (!Evaluate(Val, Info, E->getBase()))
7748       return false;
7749 
7750     QualType BaseTy = E->getBase()->getType();
7751 
7752     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7753     if (!FD) return Error(E);
7754     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7755     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7756            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7757 
7758     // Note: there is no lvalue base here. But this case should only ever
7759     // happen in C or in C++98, where we cannot be evaluating a constexpr
7760     // constructor, which is the only case the base matters.
7761     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7762     SubobjectDesignator Designator(BaseTy);
7763     Designator.addDeclUnchecked(FD);
7764 
7765     APValue Result;
7766     return extractSubobject(Info, E, Obj, Designator, Result) &&
7767            DerivedSuccess(Result, E);
7768   }
7769 
7770   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7771     APValue Val;
7772     if (!Evaluate(Val, Info, E->getBase()))
7773       return false;
7774 
7775     if (Val.isVector()) {
7776       SmallVector<uint32_t, 4> Indices;
7777       E->getEncodedElementAccess(Indices);
7778       if (Indices.size() == 1) {
7779         // Return scalar.
7780         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7781       } else {
7782         // Construct new APValue vector.
7783         SmallVector<APValue, 4> Elts;
7784         for (unsigned I = 0; I < Indices.size(); ++I) {
7785           Elts.push_back(Val.getVectorElt(Indices[I]));
7786         }
7787         APValue VecResult(Elts.data(), Indices.size());
7788         return DerivedSuccess(VecResult, E);
7789       }
7790     }
7791 
7792     return false;
7793   }
7794 
7795   bool VisitCastExpr(const CastExpr *E) {
7796     switch (E->getCastKind()) {
7797     default:
7798       break;
7799 
7800     case CK_AtomicToNonAtomic: {
7801       APValue AtomicVal;
7802       // This does not need to be done in place even for class/array types:
7803       // atomic-to-non-atomic conversion implies copying the object
7804       // representation.
7805       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7806         return false;
7807       return DerivedSuccess(AtomicVal, E);
7808     }
7809 
7810     case CK_NoOp:
7811     case CK_UserDefinedConversion:
7812       return StmtVisitorTy::Visit(E->getSubExpr());
7813 
7814     case CK_LValueToRValue: {
7815       LValue LVal;
7816       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7817         return false;
7818       APValue RVal;
7819       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7820       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7821                                           LVal, RVal))
7822         return false;
7823       return DerivedSuccess(RVal, E);
7824     }
7825     case CK_LValueToRValueBitCast: {
7826       APValue DestValue, SourceValue;
7827       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7828         return false;
7829       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7830         return false;
7831       return DerivedSuccess(DestValue, E);
7832     }
7833 
7834     case CK_AddressSpaceConversion: {
7835       APValue Value;
7836       if (!Evaluate(Value, Info, E->getSubExpr()))
7837         return false;
7838       return DerivedSuccess(Value, E);
7839     }
7840     }
7841 
7842     return Error(E);
7843   }
7844 
7845   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7846     return VisitUnaryPostIncDec(UO);
7847   }
7848   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7849     return VisitUnaryPostIncDec(UO);
7850   }
7851   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7852     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7853       return Error(UO);
7854 
7855     LValue LVal;
7856     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7857       return false;
7858     APValue RVal;
7859     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7860                       UO->isIncrementOp(), &RVal))
7861       return false;
7862     return DerivedSuccess(RVal, UO);
7863   }
7864 
7865   bool VisitStmtExpr(const StmtExpr *E) {
7866     // We will have checked the full-expressions inside the statement expression
7867     // when they were completed, and don't need to check them again now.
7868     llvm::SaveAndRestore<bool> NotCheckingForUB(
7869         Info.CheckingForUndefinedBehavior, false);
7870 
7871     const CompoundStmt *CS = E->getSubStmt();
7872     if (CS->body_empty())
7873       return true;
7874 
7875     BlockScopeRAII Scope(Info);
7876     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7877                                            BE = CS->body_end();
7878          /**/; ++BI) {
7879       if (BI + 1 == BE) {
7880         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7881         if (!FinalExpr) {
7882           Info.FFDiag((*BI)->getBeginLoc(),
7883                       diag::note_constexpr_stmt_expr_unsupported);
7884           return false;
7885         }
7886         return this->Visit(FinalExpr) && Scope.destroy();
7887       }
7888 
7889       APValue ReturnValue;
7890       StmtResult Result = { ReturnValue, nullptr };
7891       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7892       if (ESR != ESR_Succeeded) {
7893         // FIXME: If the statement-expression terminated due to 'return',
7894         // 'break', or 'continue', it would be nice to propagate that to
7895         // the outer statement evaluation rather than bailing out.
7896         if (ESR != ESR_Failed)
7897           Info.FFDiag((*BI)->getBeginLoc(),
7898                       diag::note_constexpr_stmt_expr_unsupported);
7899         return false;
7900       }
7901     }
7902 
7903     llvm_unreachable("Return from function from the loop above.");
7904   }
7905 
7906   /// Visit a value which is evaluated, but whose value is ignored.
7907   void VisitIgnoredValue(const Expr *E) {
7908     EvaluateIgnoredValue(Info, E);
7909   }
7910 
7911   /// Potentially visit a MemberExpr's base expression.
7912   void VisitIgnoredBaseExpression(const Expr *E) {
7913     // While MSVC doesn't evaluate the base expression, it does diagnose the
7914     // presence of side-effecting behavior.
7915     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7916       return;
7917     VisitIgnoredValue(E);
7918   }
7919 };
7920 
7921 } // namespace
7922 
7923 //===----------------------------------------------------------------------===//
7924 // Common base class for lvalue and temporary evaluation.
7925 //===----------------------------------------------------------------------===//
7926 namespace {
7927 template<class Derived>
7928 class LValueExprEvaluatorBase
7929   : public ExprEvaluatorBase<Derived> {
7930 protected:
7931   LValue &Result;
7932   bool InvalidBaseOK;
7933   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7934   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7935 
7936   bool Success(APValue::LValueBase B) {
7937     Result.set(B);
7938     return true;
7939   }
7940 
7941   bool evaluatePointer(const Expr *E, LValue &Result) {
7942     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7943   }
7944 
7945 public:
7946   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7947       : ExprEvaluatorBaseTy(Info), Result(Result),
7948         InvalidBaseOK(InvalidBaseOK) {}
7949 
7950   bool Success(const APValue &V, const Expr *E) {
7951     Result.setFrom(this->Info.Ctx, V);
7952     return true;
7953   }
7954 
7955   bool VisitMemberExpr(const MemberExpr *E) {
7956     // Handle non-static data members.
7957     QualType BaseTy;
7958     bool EvalOK;
7959     if (E->isArrow()) {
7960       EvalOK = evaluatePointer(E->getBase(), Result);
7961       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7962     } else if (E->getBase()->isPRValue()) {
7963       assert(E->getBase()->getType()->isRecordType());
7964       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7965       BaseTy = E->getBase()->getType();
7966     } else {
7967       EvalOK = this->Visit(E->getBase());
7968       BaseTy = E->getBase()->getType();
7969     }
7970     if (!EvalOK) {
7971       if (!InvalidBaseOK)
7972         return false;
7973       Result.setInvalid(E);
7974       return true;
7975     }
7976 
7977     const ValueDecl *MD = E->getMemberDecl();
7978     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7979       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7980              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7981       (void)BaseTy;
7982       if (!HandleLValueMember(this->Info, E, Result, FD))
7983         return false;
7984     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7985       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7986         return false;
7987     } else
7988       return this->Error(E);
7989 
7990     if (MD->getType()->isReferenceType()) {
7991       APValue RefValue;
7992       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7993                                           RefValue))
7994         return false;
7995       return Success(RefValue, E);
7996     }
7997     return true;
7998   }
7999 
8000   bool VisitBinaryOperator(const BinaryOperator *E) {
8001     switch (E->getOpcode()) {
8002     default:
8003       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8004 
8005     case BO_PtrMemD:
8006     case BO_PtrMemI:
8007       return HandleMemberPointerAccess(this->Info, E, Result);
8008     }
8009   }
8010 
8011   bool VisitCastExpr(const CastExpr *E) {
8012     switch (E->getCastKind()) {
8013     default:
8014       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8015 
8016     case CK_DerivedToBase:
8017     case CK_UncheckedDerivedToBase:
8018       if (!this->Visit(E->getSubExpr()))
8019         return false;
8020 
8021       // Now figure out the necessary offset to add to the base LV to get from
8022       // the derived class to the base class.
8023       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8024                                   Result);
8025     }
8026   }
8027 };
8028 }
8029 
8030 //===----------------------------------------------------------------------===//
8031 // LValue Evaluation
8032 //
8033 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8034 // function designators (in C), decl references to void objects (in C), and
8035 // temporaries (if building with -Wno-address-of-temporary).
8036 //
8037 // LValue evaluation produces values comprising a base expression of one of the
8038 // following types:
8039 // - Declarations
8040 //  * VarDecl
8041 //  * FunctionDecl
8042 // - Literals
8043 //  * CompoundLiteralExpr in C (and in global scope in C++)
8044 //  * StringLiteral
8045 //  * PredefinedExpr
8046 //  * ObjCStringLiteralExpr
8047 //  * ObjCEncodeExpr
8048 //  * AddrLabelExpr
8049 //  * BlockExpr
8050 //  * CallExpr for a MakeStringConstant builtin
8051 // - typeid(T) expressions, as TypeInfoLValues
8052 // - Locals and temporaries
8053 //  * MaterializeTemporaryExpr
8054 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8055 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8056 //    from the AST (FIXME).
8057 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8058 //    CallIndex, for a lifetime-extended temporary.
8059 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8060 //    immediate invocation.
8061 // plus an offset in bytes.
8062 //===----------------------------------------------------------------------===//
8063 namespace {
8064 class LValueExprEvaluator
8065   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8066 public:
8067   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8068     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8069 
8070   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8071   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8072 
8073   bool VisitDeclRefExpr(const DeclRefExpr *E);
8074   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8075   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8076   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8077   bool VisitMemberExpr(const MemberExpr *E);
8078   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8079   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8080   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8081   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8082   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8083   bool VisitUnaryDeref(const UnaryOperator *E);
8084   bool VisitUnaryReal(const UnaryOperator *E);
8085   bool VisitUnaryImag(const UnaryOperator *E);
8086   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8087     return VisitUnaryPreIncDec(UO);
8088   }
8089   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8090     return VisitUnaryPreIncDec(UO);
8091   }
8092   bool VisitBinAssign(const BinaryOperator *BO);
8093   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8094 
8095   bool VisitCastExpr(const CastExpr *E) {
8096     switch (E->getCastKind()) {
8097     default:
8098       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8099 
8100     case CK_LValueBitCast:
8101       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8102       if (!Visit(E->getSubExpr()))
8103         return false;
8104       Result.Designator.setInvalid();
8105       return true;
8106 
8107     case CK_BaseToDerived:
8108       if (!Visit(E->getSubExpr()))
8109         return false;
8110       return HandleBaseToDerivedCast(Info, E, Result);
8111 
8112     case CK_Dynamic:
8113       if (!Visit(E->getSubExpr()))
8114         return false;
8115       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8116     }
8117   }
8118 };
8119 } // end anonymous namespace
8120 
8121 /// Evaluate an expression as an lvalue. This can be legitimately called on
8122 /// expressions which are not glvalues, in three cases:
8123 ///  * function designators in C, and
8124 ///  * "extern void" objects
8125 ///  * @selector() expressions in Objective-C
8126 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8127                            bool InvalidBaseOK) {
8128   assert(!E->isValueDependent());
8129   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8130          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8131   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8132 }
8133 
8134 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8135   const NamedDecl *D = E->getDecl();
8136   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8137     return Success(cast<ValueDecl>(D));
8138   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8139     return VisitVarDecl(E, VD);
8140   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8141     return Visit(BD->getBinding());
8142   return Error(E);
8143 }
8144 
8145 
8146 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8147 
8148   // If we are within a lambda's call operator, check whether the 'VD' referred
8149   // to within 'E' actually represents a lambda-capture that maps to a
8150   // data-member/field within the closure object, and if so, evaluate to the
8151   // field or what the field refers to.
8152   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8153       isa<DeclRefExpr>(E) &&
8154       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8155     // We don't always have a complete capture-map when checking or inferring if
8156     // the function call operator meets the requirements of a constexpr function
8157     // - but we don't need to evaluate the captures to determine constexprness
8158     // (dcl.constexpr C++17).
8159     if (Info.checkingPotentialConstantExpression())
8160       return false;
8161 
8162     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8163       // Start with 'Result' referring to the complete closure object...
8164       Result = *Info.CurrentCall->This;
8165       // ... then update it to refer to the field of the closure object
8166       // that represents the capture.
8167       if (!HandleLValueMember(Info, E, Result, FD))
8168         return false;
8169       // And if the field is of reference type, update 'Result' to refer to what
8170       // the field refers to.
8171       if (FD->getType()->isReferenceType()) {
8172         APValue RVal;
8173         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8174                                             RVal))
8175           return false;
8176         Result.setFrom(Info.Ctx, RVal);
8177       }
8178       return true;
8179     }
8180   }
8181 
8182   CallStackFrame *Frame = nullptr;
8183   unsigned Version = 0;
8184   if (VD->hasLocalStorage()) {
8185     // Only if a local variable was declared in the function currently being
8186     // evaluated, do we expect to be able to find its value in the current
8187     // frame. (Otherwise it was likely declared in an enclosing context and
8188     // could either have a valid evaluatable value (for e.g. a constexpr
8189     // variable) or be ill-formed (and trigger an appropriate evaluation
8190     // diagnostic)).
8191     CallStackFrame *CurrFrame = Info.CurrentCall;
8192     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8193       // Function parameters are stored in some caller's frame. (Usually the
8194       // immediate caller, but for an inherited constructor they may be more
8195       // distant.)
8196       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8197         if (CurrFrame->Arguments) {
8198           VD = CurrFrame->Arguments.getOrigParam(PVD);
8199           Frame =
8200               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8201           Version = CurrFrame->Arguments.Version;
8202         }
8203       } else {
8204         Frame = CurrFrame;
8205         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8206       }
8207     }
8208   }
8209 
8210   if (!VD->getType()->isReferenceType()) {
8211     if (Frame) {
8212       Result.set({VD, Frame->Index, Version});
8213       return true;
8214     }
8215     return Success(VD);
8216   }
8217 
8218   if (!Info.getLangOpts().CPlusPlus11) {
8219     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8220         << VD << VD->getType();
8221     Info.Note(VD->getLocation(), diag::note_declared_at);
8222   }
8223 
8224   APValue *V;
8225   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8226     return false;
8227   if (!V->hasValue()) {
8228     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8229     // adjust the diagnostic to say that.
8230     if (!Info.checkingPotentialConstantExpression())
8231       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8232     return false;
8233   }
8234   return Success(*V, E);
8235 }
8236 
8237 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8238     const MaterializeTemporaryExpr *E) {
8239   // Walk through the expression to find the materialized temporary itself.
8240   SmallVector<const Expr *, 2> CommaLHSs;
8241   SmallVector<SubobjectAdjustment, 2> Adjustments;
8242   const Expr *Inner =
8243       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8244 
8245   // If we passed any comma operators, evaluate their LHSs.
8246   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8247     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8248       return false;
8249 
8250   // A materialized temporary with static storage duration can appear within the
8251   // result of a constant expression evaluation, so we need to preserve its
8252   // value for use outside this evaluation.
8253   APValue *Value;
8254   if (E->getStorageDuration() == SD_Static) {
8255     // FIXME: What about SD_Thread?
8256     Value = E->getOrCreateValue(true);
8257     *Value = APValue();
8258     Result.set(E);
8259   } else {
8260     Value = &Info.CurrentCall->createTemporary(
8261         E, E->getType(),
8262         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8263                                                      : ScopeKind::Block,
8264         Result);
8265   }
8266 
8267   QualType Type = Inner->getType();
8268 
8269   // Materialize the temporary itself.
8270   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8271     *Value = APValue();
8272     return false;
8273   }
8274 
8275   // Adjust our lvalue to refer to the desired subobject.
8276   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8277     --I;
8278     switch (Adjustments[I].Kind) {
8279     case SubobjectAdjustment::DerivedToBaseAdjustment:
8280       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8281                                 Type, Result))
8282         return false;
8283       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8284       break;
8285 
8286     case SubobjectAdjustment::FieldAdjustment:
8287       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8288         return false;
8289       Type = Adjustments[I].Field->getType();
8290       break;
8291 
8292     case SubobjectAdjustment::MemberPointerAdjustment:
8293       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8294                                      Adjustments[I].Ptr.RHS))
8295         return false;
8296       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8297       break;
8298     }
8299   }
8300 
8301   return true;
8302 }
8303 
8304 bool
8305 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8306   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8307          "lvalue compound literal in c++?");
8308   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8309   // only see this when folding in C, so there's no standard to follow here.
8310   return Success(E);
8311 }
8312 
8313 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8314   TypeInfoLValue TypeInfo;
8315 
8316   if (!E->isPotentiallyEvaluated()) {
8317     if (E->isTypeOperand())
8318       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8319     else
8320       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8321   } else {
8322     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8323       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8324         << E->getExprOperand()->getType()
8325         << E->getExprOperand()->getSourceRange();
8326     }
8327 
8328     if (!Visit(E->getExprOperand()))
8329       return false;
8330 
8331     Optional<DynamicType> DynType =
8332         ComputeDynamicType(Info, E, Result, AK_TypeId);
8333     if (!DynType)
8334       return false;
8335 
8336     TypeInfo =
8337         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8338   }
8339 
8340   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8341 }
8342 
8343 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8344   return Success(E->getGuidDecl());
8345 }
8346 
8347 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8348   // Handle static data members.
8349   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8350     VisitIgnoredBaseExpression(E->getBase());
8351     return VisitVarDecl(E, VD);
8352   }
8353 
8354   // Handle static member functions.
8355   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8356     if (MD->isStatic()) {
8357       VisitIgnoredBaseExpression(E->getBase());
8358       return Success(MD);
8359     }
8360   }
8361 
8362   // Handle non-static data members.
8363   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8364 }
8365 
8366 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8367   // FIXME: Deal with vectors as array subscript bases.
8368   if (E->getBase()->getType()->isVectorType())
8369     return Error(E);
8370 
8371   APSInt Index;
8372   bool Success = true;
8373 
8374   // C++17's rules require us to evaluate the LHS first, regardless of which
8375   // side is the base.
8376   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8377     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8378                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8379       if (!Info.noteFailure())
8380         return false;
8381       Success = false;
8382     }
8383   }
8384 
8385   return Success &&
8386          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8387 }
8388 
8389 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8390   return evaluatePointer(E->getSubExpr(), Result);
8391 }
8392 
8393 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8394   if (!Visit(E->getSubExpr()))
8395     return false;
8396   // __real is a no-op on scalar lvalues.
8397   if (E->getSubExpr()->getType()->isAnyComplexType())
8398     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8399   return true;
8400 }
8401 
8402 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8403   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8404          "lvalue __imag__ on scalar?");
8405   if (!Visit(E->getSubExpr()))
8406     return false;
8407   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8408   return true;
8409 }
8410 
8411 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8412   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8413     return Error(UO);
8414 
8415   if (!this->Visit(UO->getSubExpr()))
8416     return false;
8417 
8418   return handleIncDec(
8419       this->Info, UO, Result, UO->getSubExpr()->getType(),
8420       UO->isIncrementOp(), nullptr);
8421 }
8422 
8423 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8424     const CompoundAssignOperator *CAO) {
8425   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8426     return Error(CAO);
8427 
8428   bool Success = true;
8429 
8430   // C++17 onwards require that we evaluate the RHS first.
8431   APValue RHS;
8432   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8433     if (!Info.noteFailure())
8434       return false;
8435     Success = false;
8436   }
8437 
8438   // The overall lvalue result is the result of evaluating the LHS.
8439   if (!this->Visit(CAO->getLHS()) || !Success)
8440     return false;
8441 
8442   return handleCompoundAssignment(
8443       this->Info, CAO,
8444       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8445       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8446 }
8447 
8448 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8449   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8450     return Error(E);
8451 
8452   bool Success = true;
8453 
8454   // C++17 onwards require that we evaluate the RHS first.
8455   APValue NewVal;
8456   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8457     if (!Info.noteFailure())
8458       return false;
8459     Success = false;
8460   }
8461 
8462   if (!this->Visit(E->getLHS()) || !Success)
8463     return false;
8464 
8465   if (Info.getLangOpts().CPlusPlus20 &&
8466       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8467     return false;
8468 
8469   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8470                           NewVal);
8471 }
8472 
8473 //===----------------------------------------------------------------------===//
8474 // Pointer Evaluation
8475 //===----------------------------------------------------------------------===//
8476 
8477 /// Attempts to compute the number of bytes available at the pointer
8478 /// returned by a function with the alloc_size attribute. Returns true if we
8479 /// were successful. Places an unsigned number into `Result`.
8480 ///
8481 /// This expects the given CallExpr to be a call to a function with an
8482 /// alloc_size attribute.
8483 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8484                                             const CallExpr *Call,
8485                                             llvm::APInt &Result) {
8486   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8487 
8488   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8489   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8490   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8491   if (Call->getNumArgs() <= SizeArgNo)
8492     return false;
8493 
8494   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8495     Expr::EvalResult ExprResult;
8496     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8497       return false;
8498     Into = ExprResult.Val.getInt();
8499     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8500       return false;
8501     Into = Into.zextOrSelf(BitsInSizeT);
8502     return true;
8503   };
8504 
8505   APSInt SizeOfElem;
8506   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8507     return false;
8508 
8509   if (!AllocSize->getNumElemsParam().isValid()) {
8510     Result = std::move(SizeOfElem);
8511     return true;
8512   }
8513 
8514   APSInt NumberOfElems;
8515   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8516   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8517     return false;
8518 
8519   bool Overflow;
8520   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8521   if (Overflow)
8522     return false;
8523 
8524   Result = std::move(BytesAvailable);
8525   return true;
8526 }
8527 
8528 /// Convenience function. LVal's base must be a call to an alloc_size
8529 /// function.
8530 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8531                                             const LValue &LVal,
8532                                             llvm::APInt &Result) {
8533   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8534          "Can't get the size of a non alloc_size function");
8535   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8536   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8537   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8538 }
8539 
8540 /// Attempts to evaluate the given LValueBase as the result of a call to
8541 /// a function with the alloc_size attribute. If it was possible to do so, this
8542 /// function will return true, make Result's Base point to said function call,
8543 /// and mark Result's Base as invalid.
8544 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8545                                       LValue &Result) {
8546   if (Base.isNull())
8547     return false;
8548 
8549   // Because we do no form of static analysis, we only support const variables.
8550   //
8551   // Additionally, we can't support parameters, nor can we support static
8552   // variables (in the latter case, use-before-assign isn't UB; in the former,
8553   // we have no clue what they'll be assigned to).
8554   const auto *VD =
8555       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8556   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8557     return false;
8558 
8559   const Expr *Init = VD->getAnyInitializer();
8560   if (!Init)
8561     return false;
8562 
8563   const Expr *E = Init->IgnoreParens();
8564   if (!tryUnwrapAllocSizeCall(E))
8565     return false;
8566 
8567   // Store E instead of E unwrapped so that the type of the LValue's base is
8568   // what the user wanted.
8569   Result.setInvalid(E);
8570 
8571   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8572   Result.addUnsizedArray(Info, E, Pointee);
8573   return true;
8574 }
8575 
8576 namespace {
8577 class PointerExprEvaluator
8578   : public ExprEvaluatorBase<PointerExprEvaluator> {
8579   LValue &Result;
8580   bool InvalidBaseOK;
8581 
8582   bool Success(const Expr *E) {
8583     Result.set(E);
8584     return true;
8585   }
8586 
8587   bool evaluateLValue(const Expr *E, LValue &Result) {
8588     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8589   }
8590 
8591   bool evaluatePointer(const Expr *E, LValue &Result) {
8592     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8593   }
8594 
8595   bool visitNonBuiltinCallExpr(const CallExpr *E);
8596 public:
8597 
8598   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8599       : ExprEvaluatorBaseTy(info), Result(Result),
8600         InvalidBaseOK(InvalidBaseOK) {}
8601 
8602   bool Success(const APValue &V, const Expr *E) {
8603     Result.setFrom(Info.Ctx, V);
8604     return true;
8605   }
8606   bool ZeroInitialization(const Expr *E) {
8607     Result.setNull(Info.Ctx, E->getType());
8608     return true;
8609   }
8610 
8611   bool VisitBinaryOperator(const BinaryOperator *E);
8612   bool VisitCastExpr(const CastExpr* E);
8613   bool VisitUnaryAddrOf(const UnaryOperator *E);
8614   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8615       { return Success(E); }
8616   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8617     if (E->isExpressibleAsConstantInitializer())
8618       return Success(E);
8619     if (Info.noteFailure())
8620       EvaluateIgnoredValue(Info, E->getSubExpr());
8621     return Error(E);
8622   }
8623   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8624       { return Success(E); }
8625   bool VisitCallExpr(const CallExpr *E);
8626   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8627   bool VisitBlockExpr(const BlockExpr *E) {
8628     if (!E->getBlockDecl()->hasCaptures())
8629       return Success(E);
8630     return Error(E);
8631   }
8632   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8633     // Can't look at 'this' when checking a potential constant expression.
8634     if (Info.checkingPotentialConstantExpression())
8635       return false;
8636     if (!Info.CurrentCall->This) {
8637       if (Info.getLangOpts().CPlusPlus11)
8638         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8639       else
8640         Info.FFDiag(E);
8641       return false;
8642     }
8643     Result = *Info.CurrentCall->This;
8644     // If we are inside a lambda's call operator, the 'this' expression refers
8645     // to the enclosing '*this' object (either by value or reference) which is
8646     // either copied into the closure object's field that represents the '*this'
8647     // or refers to '*this'.
8648     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8649       // Ensure we actually have captured 'this'. (an error will have
8650       // been previously reported if not).
8651       if (!Info.CurrentCall->LambdaThisCaptureField)
8652         return false;
8653 
8654       // Update 'Result' to refer to the data member/field of the closure object
8655       // that represents the '*this' capture.
8656       if (!HandleLValueMember(Info, E, Result,
8657                              Info.CurrentCall->LambdaThisCaptureField))
8658         return false;
8659       // If we captured '*this' by reference, replace the field with its referent.
8660       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8661               ->isPointerType()) {
8662         APValue RVal;
8663         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8664                                             RVal))
8665           return false;
8666 
8667         Result.setFrom(Info.Ctx, RVal);
8668       }
8669     }
8670     return true;
8671   }
8672 
8673   bool VisitCXXNewExpr(const CXXNewExpr *E);
8674 
8675   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8676     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8677     APValue LValResult = E->EvaluateInContext(
8678         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8679     Result.setFrom(Info.Ctx, LValResult);
8680     return true;
8681   }
8682 
8683   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8684     std::string ResultStr = E->ComputeName(Info.Ctx);
8685 
8686     QualType CharTy = Info.Ctx.CharTy.withConst();
8687     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8688                ResultStr.size() + 1);
8689     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8690                                                      ArrayType::Normal, 0);
8691 
8692     StringLiteral *SL =
8693         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8694                               /*Pascal*/ false, ArrayTy, E->getLocation());
8695 
8696     evaluateLValue(SL, Result);
8697     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8698     return true;
8699   }
8700 
8701   // FIXME: Missing: @protocol, @selector
8702 };
8703 } // end anonymous namespace
8704 
8705 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8706                             bool InvalidBaseOK) {
8707   assert(!E->isValueDependent());
8708   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8709   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8710 }
8711 
8712 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8713   if (E->getOpcode() != BO_Add &&
8714       E->getOpcode() != BO_Sub)
8715     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8716 
8717   const Expr *PExp = E->getLHS();
8718   const Expr *IExp = E->getRHS();
8719   if (IExp->getType()->isPointerType())
8720     std::swap(PExp, IExp);
8721 
8722   bool EvalPtrOK = evaluatePointer(PExp, Result);
8723   if (!EvalPtrOK && !Info.noteFailure())
8724     return false;
8725 
8726   llvm::APSInt Offset;
8727   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8728     return false;
8729 
8730   if (E->getOpcode() == BO_Sub)
8731     negateAsSigned(Offset);
8732 
8733   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8734   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8735 }
8736 
8737 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8738   return evaluateLValue(E->getSubExpr(), Result);
8739 }
8740 
8741 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8742   const Expr *SubExpr = E->getSubExpr();
8743 
8744   switch (E->getCastKind()) {
8745   default:
8746     break;
8747   case CK_BitCast:
8748   case CK_CPointerToObjCPointerCast:
8749   case CK_BlockPointerToObjCPointerCast:
8750   case CK_AnyPointerToBlockPointerCast:
8751   case CK_AddressSpaceConversion:
8752     if (!Visit(SubExpr))
8753       return false;
8754     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8755     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8756     // also static_casts, but we disallow them as a resolution to DR1312.
8757     if (!E->getType()->isVoidPointerType()) {
8758       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8759           !Result.IsNullPtr &&
8760           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8761                                           E->getType()->getPointeeType()) &&
8762           Info.getStdAllocatorCaller("allocate")) {
8763         // Inside a call to std::allocator::allocate and friends, we permit
8764         // casting from void* back to cv1 T* for a pointer that points to a
8765         // cv2 T.
8766       } else {
8767         Result.Designator.setInvalid();
8768         if (SubExpr->getType()->isVoidPointerType())
8769           CCEDiag(E, diag::note_constexpr_invalid_cast)
8770             << 3 << SubExpr->getType();
8771         else
8772           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8773       }
8774     }
8775     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8776       ZeroInitialization(E);
8777     return true;
8778 
8779   case CK_DerivedToBase:
8780   case CK_UncheckedDerivedToBase:
8781     if (!evaluatePointer(E->getSubExpr(), Result))
8782       return false;
8783     if (!Result.Base && Result.Offset.isZero())
8784       return true;
8785 
8786     // Now figure out the necessary offset to add to the base LV to get from
8787     // the derived class to the base class.
8788     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8789                                   castAs<PointerType>()->getPointeeType(),
8790                                 Result);
8791 
8792   case CK_BaseToDerived:
8793     if (!Visit(E->getSubExpr()))
8794       return false;
8795     if (!Result.Base && Result.Offset.isZero())
8796       return true;
8797     return HandleBaseToDerivedCast(Info, E, Result);
8798 
8799   case CK_Dynamic:
8800     if (!Visit(E->getSubExpr()))
8801       return false;
8802     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8803 
8804   case CK_NullToPointer:
8805     VisitIgnoredValue(E->getSubExpr());
8806     return ZeroInitialization(E);
8807 
8808   case CK_IntegralToPointer: {
8809     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8810 
8811     APValue Value;
8812     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8813       break;
8814 
8815     if (Value.isInt()) {
8816       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8817       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8818       Result.Base = (Expr*)nullptr;
8819       Result.InvalidBase = false;
8820       Result.Offset = CharUnits::fromQuantity(N);
8821       Result.Designator.setInvalid();
8822       Result.IsNullPtr = false;
8823       return true;
8824     } else {
8825       // Cast is of an lvalue, no need to change value.
8826       Result.setFrom(Info.Ctx, Value);
8827       return true;
8828     }
8829   }
8830 
8831   case CK_ArrayToPointerDecay: {
8832     if (SubExpr->isGLValue()) {
8833       if (!evaluateLValue(SubExpr, Result))
8834         return false;
8835     } else {
8836       APValue &Value = Info.CurrentCall->createTemporary(
8837           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8838       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8839         return false;
8840     }
8841     // The result is a pointer to the first element of the array.
8842     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8843     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8844       Result.addArray(Info, E, CAT);
8845     else
8846       Result.addUnsizedArray(Info, E, AT->getElementType());
8847     return true;
8848   }
8849 
8850   case CK_FunctionToPointerDecay:
8851     return evaluateLValue(SubExpr, Result);
8852 
8853   case CK_LValueToRValue: {
8854     LValue LVal;
8855     if (!evaluateLValue(E->getSubExpr(), LVal))
8856       return false;
8857 
8858     APValue RVal;
8859     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8860     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8861                                         LVal, RVal))
8862       return InvalidBaseOK &&
8863              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8864     return Success(RVal, E);
8865   }
8866   }
8867 
8868   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8869 }
8870 
8871 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8872                                 UnaryExprOrTypeTrait ExprKind) {
8873   // C++ [expr.alignof]p3:
8874   //     When alignof is applied to a reference type, the result is the
8875   //     alignment of the referenced type.
8876   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8877     T = Ref->getPointeeType();
8878 
8879   if (T.getQualifiers().hasUnaligned())
8880     return CharUnits::One();
8881 
8882   const bool AlignOfReturnsPreferred =
8883       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8884 
8885   // __alignof is defined to return the preferred alignment.
8886   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8887   // as well.
8888   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8889     return Info.Ctx.toCharUnitsFromBits(
8890       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8891   // alignof and _Alignof are defined to return the ABI alignment.
8892   else if (ExprKind == UETT_AlignOf)
8893     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8894   else
8895     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8896 }
8897 
8898 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8899                                 UnaryExprOrTypeTrait ExprKind) {
8900   E = E->IgnoreParens();
8901 
8902   // The kinds of expressions that we have special-case logic here for
8903   // should be kept up to date with the special checks for those
8904   // expressions in Sema.
8905 
8906   // alignof decl is always accepted, even if it doesn't make sense: we default
8907   // to 1 in those cases.
8908   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8909     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8910                                  /*RefAsPointee*/true);
8911 
8912   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8913     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8914                                  /*RefAsPointee*/true);
8915 
8916   return GetAlignOfType(Info, E->getType(), ExprKind);
8917 }
8918 
8919 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8920   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8921     return Info.Ctx.getDeclAlign(VD);
8922   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8923     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8924   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8925 }
8926 
8927 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8928 /// __builtin_is_aligned and __builtin_assume_aligned.
8929 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8930                                  EvalInfo &Info, APSInt &Alignment) {
8931   if (!EvaluateInteger(E, Alignment, Info))
8932     return false;
8933   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8934     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8935     return false;
8936   }
8937   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8938   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8939   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8940     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8941         << MaxValue << ForType << Alignment;
8942     return false;
8943   }
8944   // Ensure both alignment and source value have the same bit width so that we
8945   // don't assert when computing the resulting value.
8946   APSInt ExtAlignment =
8947       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8948   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8949          "Alignment should not be changed by ext/trunc");
8950   Alignment = ExtAlignment;
8951   assert(Alignment.getBitWidth() == SrcWidth);
8952   return true;
8953 }
8954 
8955 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8956 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8957   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8958     return true;
8959 
8960   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8961     return false;
8962 
8963   Result.setInvalid(E);
8964   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8965   Result.addUnsizedArray(Info, E, PointeeTy);
8966   return true;
8967 }
8968 
8969 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8970   if (IsStringLiteralCall(E))
8971     return Success(E);
8972 
8973   if (unsigned BuiltinOp = E->getBuiltinCallee())
8974     return VisitBuiltinCallExpr(E, BuiltinOp);
8975 
8976   return visitNonBuiltinCallExpr(E);
8977 }
8978 
8979 // Determine if T is a character type for which we guarantee that
8980 // sizeof(T) == 1.
8981 static bool isOneByteCharacterType(QualType T) {
8982   return T->isCharType() || T->isChar8Type();
8983 }
8984 
8985 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8986                                                 unsigned BuiltinOp) {
8987   switch (BuiltinOp) {
8988   case Builtin::BI__builtin_addressof:
8989     return evaluateLValue(E->getArg(0), Result);
8990   case Builtin::BI__builtin_assume_aligned: {
8991     // We need to be very careful here because: if the pointer does not have the
8992     // asserted alignment, then the behavior is undefined, and undefined
8993     // behavior is non-constant.
8994     if (!evaluatePointer(E->getArg(0), Result))
8995       return false;
8996 
8997     LValue OffsetResult(Result);
8998     APSInt Alignment;
8999     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9000                               Alignment))
9001       return false;
9002     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9003 
9004     if (E->getNumArgs() > 2) {
9005       APSInt Offset;
9006       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9007         return false;
9008 
9009       int64_t AdditionalOffset = -Offset.getZExtValue();
9010       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9011     }
9012 
9013     // If there is a base object, then it must have the correct alignment.
9014     if (OffsetResult.Base) {
9015       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9016 
9017       if (BaseAlignment < Align) {
9018         Result.Designator.setInvalid();
9019         // FIXME: Add support to Diagnostic for long / long long.
9020         CCEDiag(E->getArg(0),
9021                 diag::note_constexpr_baa_insufficient_alignment) << 0
9022           << (unsigned)BaseAlignment.getQuantity()
9023           << (unsigned)Align.getQuantity();
9024         return false;
9025       }
9026     }
9027 
9028     // The offset must also have the correct alignment.
9029     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9030       Result.Designator.setInvalid();
9031 
9032       (OffsetResult.Base
9033            ? CCEDiag(E->getArg(0),
9034                      diag::note_constexpr_baa_insufficient_alignment) << 1
9035            : CCEDiag(E->getArg(0),
9036                      diag::note_constexpr_baa_value_insufficient_alignment))
9037         << (int)OffsetResult.Offset.getQuantity()
9038         << (unsigned)Align.getQuantity();
9039       return false;
9040     }
9041 
9042     return true;
9043   }
9044   case Builtin::BI__builtin_align_up:
9045   case Builtin::BI__builtin_align_down: {
9046     if (!evaluatePointer(E->getArg(0), Result))
9047       return false;
9048     APSInt Alignment;
9049     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9050                               Alignment))
9051       return false;
9052     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9053     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9054     // For align_up/align_down, we can return the same value if the alignment
9055     // is known to be greater or equal to the requested value.
9056     if (PtrAlign.getQuantity() >= Alignment)
9057       return true;
9058 
9059     // The alignment could be greater than the minimum at run-time, so we cannot
9060     // infer much about the resulting pointer value. One case is possible:
9061     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9062     // can infer the correct index if the requested alignment is smaller than
9063     // the base alignment so we can perform the computation on the offset.
9064     if (BaseAlignment.getQuantity() >= Alignment) {
9065       assert(Alignment.getBitWidth() <= 64 &&
9066              "Cannot handle > 64-bit address-space");
9067       uint64_t Alignment64 = Alignment.getZExtValue();
9068       CharUnits NewOffset = CharUnits::fromQuantity(
9069           BuiltinOp == Builtin::BI__builtin_align_down
9070               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9071               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9072       Result.adjustOffset(NewOffset - Result.Offset);
9073       // TODO: diagnose out-of-bounds values/only allow for arrays?
9074       return true;
9075     }
9076     // Otherwise, we cannot constant-evaluate the result.
9077     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9078         << Alignment;
9079     return false;
9080   }
9081   case Builtin::BI__builtin_operator_new:
9082     return HandleOperatorNewCall(Info, E, Result);
9083   case Builtin::BI__builtin_launder:
9084     return evaluatePointer(E->getArg(0), Result);
9085   case Builtin::BIstrchr:
9086   case Builtin::BIwcschr:
9087   case Builtin::BImemchr:
9088   case Builtin::BIwmemchr:
9089     if (Info.getLangOpts().CPlusPlus11)
9090       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9091         << /*isConstexpr*/0 << /*isConstructor*/0
9092         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9093     else
9094       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9095     LLVM_FALLTHROUGH;
9096   case Builtin::BI__builtin_strchr:
9097   case Builtin::BI__builtin_wcschr:
9098   case Builtin::BI__builtin_memchr:
9099   case Builtin::BI__builtin_char_memchr:
9100   case Builtin::BI__builtin_wmemchr: {
9101     if (!Visit(E->getArg(0)))
9102       return false;
9103     APSInt Desired;
9104     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9105       return false;
9106     uint64_t MaxLength = uint64_t(-1);
9107     if (BuiltinOp != Builtin::BIstrchr &&
9108         BuiltinOp != Builtin::BIwcschr &&
9109         BuiltinOp != Builtin::BI__builtin_strchr &&
9110         BuiltinOp != Builtin::BI__builtin_wcschr) {
9111       APSInt N;
9112       if (!EvaluateInteger(E->getArg(2), N, Info))
9113         return false;
9114       MaxLength = N.getExtValue();
9115     }
9116     // We cannot find the value if there are no candidates to match against.
9117     if (MaxLength == 0u)
9118       return ZeroInitialization(E);
9119     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9120         Result.Designator.Invalid)
9121       return false;
9122     QualType CharTy = Result.Designator.getType(Info.Ctx);
9123     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9124                      BuiltinOp == Builtin::BI__builtin_memchr;
9125     assert(IsRawByte ||
9126            Info.Ctx.hasSameUnqualifiedType(
9127                CharTy, E->getArg(0)->getType()->getPointeeType()));
9128     // Pointers to const void may point to objects of incomplete type.
9129     if (IsRawByte && CharTy->isIncompleteType()) {
9130       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9131       return false;
9132     }
9133     // Give up on byte-oriented matching against multibyte elements.
9134     // FIXME: We can compare the bytes in the correct order.
9135     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9136       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9137           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9138           << CharTy;
9139       return false;
9140     }
9141     // Figure out what value we're actually looking for (after converting to
9142     // the corresponding unsigned type if necessary).
9143     uint64_t DesiredVal;
9144     bool StopAtNull = false;
9145     switch (BuiltinOp) {
9146     case Builtin::BIstrchr:
9147     case Builtin::BI__builtin_strchr:
9148       // strchr compares directly to the passed integer, and therefore
9149       // always fails if given an int that is not a char.
9150       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9151                                                   E->getArg(1)->getType(),
9152                                                   Desired),
9153                                Desired))
9154         return ZeroInitialization(E);
9155       StopAtNull = true;
9156       LLVM_FALLTHROUGH;
9157     case Builtin::BImemchr:
9158     case Builtin::BI__builtin_memchr:
9159     case Builtin::BI__builtin_char_memchr:
9160       // memchr compares by converting both sides to unsigned char. That's also
9161       // correct for strchr if we get this far (to cope with plain char being
9162       // unsigned in the strchr case).
9163       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9164       break;
9165 
9166     case Builtin::BIwcschr:
9167     case Builtin::BI__builtin_wcschr:
9168       StopAtNull = true;
9169       LLVM_FALLTHROUGH;
9170     case Builtin::BIwmemchr:
9171     case Builtin::BI__builtin_wmemchr:
9172       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9173       DesiredVal = Desired.getZExtValue();
9174       break;
9175     }
9176 
9177     for (; MaxLength; --MaxLength) {
9178       APValue Char;
9179       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9180           !Char.isInt())
9181         return false;
9182       if (Char.getInt().getZExtValue() == DesiredVal)
9183         return true;
9184       if (StopAtNull && !Char.getInt())
9185         break;
9186       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9187         return false;
9188     }
9189     // Not found: return nullptr.
9190     return ZeroInitialization(E);
9191   }
9192 
9193   case Builtin::BImemcpy:
9194   case Builtin::BImemmove:
9195   case Builtin::BIwmemcpy:
9196   case Builtin::BIwmemmove:
9197     if (Info.getLangOpts().CPlusPlus11)
9198       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9199         << /*isConstexpr*/0 << /*isConstructor*/0
9200         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9201     else
9202       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9203     LLVM_FALLTHROUGH;
9204   case Builtin::BI__builtin_memcpy:
9205   case Builtin::BI__builtin_memmove:
9206   case Builtin::BI__builtin_wmemcpy:
9207   case Builtin::BI__builtin_wmemmove: {
9208     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9209                  BuiltinOp == Builtin::BIwmemmove ||
9210                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9211                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9212     bool Move = BuiltinOp == Builtin::BImemmove ||
9213                 BuiltinOp == Builtin::BIwmemmove ||
9214                 BuiltinOp == Builtin::BI__builtin_memmove ||
9215                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9216 
9217     // The result of mem* is the first argument.
9218     if (!Visit(E->getArg(0)))
9219       return false;
9220     LValue Dest = Result;
9221 
9222     LValue Src;
9223     if (!EvaluatePointer(E->getArg(1), Src, Info))
9224       return false;
9225 
9226     APSInt N;
9227     if (!EvaluateInteger(E->getArg(2), N, Info))
9228       return false;
9229     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9230 
9231     // If the size is zero, we treat this as always being a valid no-op.
9232     // (Even if one of the src and dest pointers is null.)
9233     if (!N)
9234       return true;
9235 
9236     // Otherwise, if either of the operands is null, we can't proceed. Don't
9237     // try to determine the type of the copied objects, because there aren't
9238     // any.
9239     if (!Src.Base || !Dest.Base) {
9240       APValue Val;
9241       (!Src.Base ? Src : Dest).moveInto(Val);
9242       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9243           << Move << WChar << !!Src.Base
9244           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9245       return false;
9246     }
9247     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9248       return false;
9249 
9250     // We require that Src and Dest are both pointers to arrays of
9251     // trivially-copyable type. (For the wide version, the designator will be
9252     // invalid if the designated object is not a wchar_t.)
9253     QualType T = Dest.Designator.getType(Info.Ctx);
9254     QualType SrcT = Src.Designator.getType(Info.Ctx);
9255     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9256       // FIXME: Consider using our bit_cast implementation to support this.
9257       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9258       return false;
9259     }
9260     if (T->isIncompleteType()) {
9261       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9262       return false;
9263     }
9264     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9265       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9266       return false;
9267     }
9268 
9269     // Figure out how many T's we're copying.
9270     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9271     if (!WChar) {
9272       uint64_t Remainder;
9273       llvm::APInt OrigN = N;
9274       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9275       if (Remainder) {
9276         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9277             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9278             << (unsigned)TSize;
9279         return false;
9280       }
9281     }
9282 
9283     // Check that the copying will remain within the arrays, just so that we
9284     // can give a more meaningful diagnostic. This implicitly also checks that
9285     // N fits into 64 bits.
9286     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9287     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9288     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9289       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9290           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9291           << toString(N, 10, /*Signed*/false);
9292       return false;
9293     }
9294     uint64_t NElems = N.getZExtValue();
9295     uint64_t NBytes = NElems * TSize;
9296 
9297     // Check for overlap.
9298     int Direction = 1;
9299     if (HasSameBase(Src, Dest)) {
9300       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9301       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9302       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9303         // Dest is inside the source region.
9304         if (!Move) {
9305           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9306           return false;
9307         }
9308         // For memmove and friends, copy backwards.
9309         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9310             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9311           return false;
9312         Direction = -1;
9313       } else if (!Move && SrcOffset >= DestOffset &&
9314                  SrcOffset - DestOffset < NBytes) {
9315         // Src is inside the destination region for memcpy: invalid.
9316         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9317         return false;
9318       }
9319     }
9320 
9321     while (true) {
9322       APValue Val;
9323       // FIXME: Set WantObjectRepresentation to true if we're copying a
9324       // char-like type?
9325       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9326           !handleAssignment(Info, E, Dest, T, Val))
9327         return false;
9328       // Do not iterate past the last element; if we're copying backwards, that
9329       // might take us off the start of the array.
9330       if (--NElems == 0)
9331         return true;
9332       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9333           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9334         return false;
9335     }
9336   }
9337 
9338   default:
9339     break;
9340   }
9341 
9342   return visitNonBuiltinCallExpr(E);
9343 }
9344 
9345 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9346                                      APValue &Result, const InitListExpr *ILE,
9347                                      QualType AllocType);
9348 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9349                                           APValue &Result,
9350                                           const CXXConstructExpr *CCE,
9351                                           QualType AllocType);
9352 
9353 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9354   if (!Info.getLangOpts().CPlusPlus20)
9355     Info.CCEDiag(E, diag::note_constexpr_new);
9356 
9357   // We cannot speculatively evaluate a delete expression.
9358   if (Info.SpeculativeEvaluationDepth)
9359     return false;
9360 
9361   FunctionDecl *OperatorNew = E->getOperatorNew();
9362 
9363   bool IsNothrow = false;
9364   bool IsPlacement = false;
9365   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9366       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9367     // FIXME Support array placement new.
9368     assert(E->getNumPlacementArgs() == 1);
9369     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9370       return false;
9371     if (Result.Designator.Invalid)
9372       return false;
9373     IsPlacement = true;
9374   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9375     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9376         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9377     return false;
9378   } else if (E->getNumPlacementArgs()) {
9379     // The only new-placement list we support is of the form (std::nothrow).
9380     //
9381     // FIXME: There is no restriction on this, but it's not clear that any
9382     // other form makes any sense. We get here for cases such as:
9383     //
9384     //   new (std::align_val_t{N}) X(int)
9385     //
9386     // (which should presumably be valid only if N is a multiple of
9387     // alignof(int), and in any case can't be deallocated unless N is
9388     // alignof(X) and X has new-extended alignment).
9389     if (E->getNumPlacementArgs() != 1 ||
9390         !E->getPlacementArg(0)->getType()->isNothrowT())
9391       return Error(E, diag::note_constexpr_new_placement);
9392 
9393     LValue Nothrow;
9394     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9395       return false;
9396     IsNothrow = true;
9397   }
9398 
9399   const Expr *Init = E->getInitializer();
9400   const InitListExpr *ResizedArrayILE = nullptr;
9401   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9402   bool ValueInit = false;
9403 
9404   QualType AllocType = E->getAllocatedType();
9405   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9406     const Expr *Stripped = *ArraySize;
9407     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9408          Stripped = ICE->getSubExpr())
9409       if (ICE->getCastKind() != CK_NoOp &&
9410           ICE->getCastKind() != CK_IntegralCast)
9411         break;
9412 
9413     llvm::APSInt ArrayBound;
9414     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9415       return false;
9416 
9417     // C++ [expr.new]p9:
9418     //   The expression is erroneous if:
9419     //   -- [...] its value before converting to size_t [or] applying the
9420     //      second standard conversion sequence is less than zero
9421     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9422       if (IsNothrow)
9423         return ZeroInitialization(E);
9424 
9425       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9426           << ArrayBound << (*ArraySize)->getSourceRange();
9427       return false;
9428     }
9429 
9430     //   -- its value is such that the size of the allocated object would
9431     //      exceed the implementation-defined limit
9432     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9433                                                 ArrayBound) >
9434         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9435       if (IsNothrow)
9436         return ZeroInitialization(E);
9437 
9438       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9439         << ArrayBound << (*ArraySize)->getSourceRange();
9440       return false;
9441     }
9442 
9443     //   -- the new-initializer is a braced-init-list and the number of
9444     //      array elements for which initializers are provided [...]
9445     //      exceeds the number of elements to initialize
9446     if (!Init) {
9447       // No initialization is performed.
9448     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9449                isa<ImplicitValueInitExpr>(Init)) {
9450       ValueInit = true;
9451     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9452       ResizedArrayCCE = CCE;
9453     } else {
9454       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9455       assert(CAT && "unexpected type for array initializer");
9456 
9457       unsigned Bits =
9458           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9459       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9460       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9461       if (InitBound.ugt(AllocBound)) {
9462         if (IsNothrow)
9463           return ZeroInitialization(E);
9464 
9465         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9466             << toString(AllocBound, 10, /*Signed=*/false)
9467             << toString(InitBound, 10, /*Signed=*/false)
9468             << (*ArraySize)->getSourceRange();
9469         return false;
9470       }
9471 
9472       // If the sizes differ, we must have an initializer list, and we need
9473       // special handling for this case when we initialize.
9474       if (InitBound != AllocBound)
9475         ResizedArrayILE = cast<InitListExpr>(Init);
9476     }
9477 
9478     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9479                                               ArrayType::Normal, 0);
9480   } else {
9481     assert(!AllocType->isArrayType() &&
9482            "array allocation with non-array new");
9483   }
9484 
9485   APValue *Val;
9486   if (IsPlacement) {
9487     AccessKinds AK = AK_Construct;
9488     struct FindObjectHandler {
9489       EvalInfo &Info;
9490       const Expr *E;
9491       QualType AllocType;
9492       const AccessKinds AccessKind;
9493       APValue *Value;
9494 
9495       typedef bool result_type;
9496       bool failed() { return false; }
9497       bool found(APValue &Subobj, QualType SubobjType) {
9498         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9499         // old name of the object to be used to name the new object.
9500         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9501           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9502             SubobjType << AllocType;
9503           return false;
9504         }
9505         Value = &Subobj;
9506         return true;
9507       }
9508       bool found(APSInt &Value, QualType SubobjType) {
9509         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9510         return false;
9511       }
9512       bool found(APFloat &Value, QualType SubobjType) {
9513         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9514         return false;
9515       }
9516     } Handler = {Info, E, AllocType, AK, nullptr};
9517 
9518     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9519     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9520       return false;
9521 
9522     Val = Handler.Value;
9523 
9524     // [basic.life]p1:
9525     //   The lifetime of an object o of type T ends when [...] the storage
9526     //   which the object occupies is [...] reused by an object that is not
9527     //   nested within o (6.6.2).
9528     *Val = APValue();
9529   } else {
9530     // Perform the allocation and obtain a pointer to the resulting object.
9531     Val = Info.createHeapAlloc(E, AllocType, Result);
9532     if (!Val)
9533       return false;
9534   }
9535 
9536   if (ValueInit) {
9537     ImplicitValueInitExpr VIE(AllocType);
9538     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9539       return false;
9540   } else if (ResizedArrayILE) {
9541     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9542                                   AllocType))
9543       return false;
9544   } else if (ResizedArrayCCE) {
9545     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9546                                        AllocType))
9547       return false;
9548   } else if (Init) {
9549     if (!EvaluateInPlace(*Val, Info, Result, Init))
9550       return false;
9551   } else if (!getDefaultInitValue(AllocType, *Val)) {
9552     return false;
9553   }
9554 
9555   // Array new returns a pointer to the first element, not a pointer to the
9556   // array.
9557   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9558     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9559 
9560   return true;
9561 }
9562 //===----------------------------------------------------------------------===//
9563 // Member Pointer Evaluation
9564 //===----------------------------------------------------------------------===//
9565 
9566 namespace {
9567 class MemberPointerExprEvaluator
9568   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9569   MemberPtr &Result;
9570 
9571   bool Success(const ValueDecl *D) {
9572     Result = MemberPtr(D);
9573     return true;
9574   }
9575 public:
9576 
9577   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9578     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9579 
9580   bool Success(const APValue &V, const Expr *E) {
9581     Result.setFrom(V);
9582     return true;
9583   }
9584   bool ZeroInitialization(const Expr *E) {
9585     return Success((const ValueDecl*)nullptr);
9586   }
9587 
9588   bool VisitCastExpr(const CastExpr *E);
9589   bool VisitUnaryAddrOf(const UnaryOperator *E);
9590 };
9591 } // end anonymous namespace
9592 
9593 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9594                                   EvalInfo &Info) {
9595   assert(!E->isValueDependent());
9596   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9597   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9598 }
9599 
9600 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9601   switch (E->getCastKind()) {
9602   default:
9603     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9604 
9605   case CK_NullToMemberPointer:
9606     VisitIgnoredValue(E->getSubExpr());
9607     return ZeroInitialization(E);
9608 
9609   case CK_BaseToDerivedMemberPointer: {
9610     if (!Visit(E->getSubExpr()))
9611       return false;
9612     if (E->path_empty())
9613       return true;
9614     // Base-to-derived member pointer casts store the path in derived-to-base
9615     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9616     // the wrong end of the derived->base arc, so stagger the path by one class.
9617     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9618     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9619          PathI != PathE; ++PathI) {
9620       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9621       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9622       if (!Result.castToDerived(Derived))
9623         return Error(E);
9624     }
9625     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9626     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9627       return Error(E);
9628     return true;
9629   }
9630 
9631   case CK_DerivedToBaseMemberPointer:
9632     if (!Visit(E->getSubExpr()))
9633       return false;
9634     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9635          PathE = E->path_end(); PathI != PathE; ++PathI) {
9636       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9637       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9638       if (!Result.castToBase(Base))
9639         return Error(E);
9640     }
9641     return true;
9642   }
9643 }
9644 
9645 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9646   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9647   // member can be formed.
9648   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9649 }
9650 
9651 //===----------------------------------------------------------------------===//
9652 // Record Evaluation
9653 //===----------------------------------------------------------------------===//
9654 
9655 namespace {
9656   class RecordExprEvaluator
9657   : public ExprEvaluatorBase<RecordExprEvaluator> {
9658     const LValue &This;
9659     APValue &Result;
9660   public:
9661 
9662     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9663       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9664 
9665     bool Success(const APValue &V, const Expr *E) {
9666       Result = V;
9667       return true;
9668     }
9669     bool ZeroInitialization(const Expr *E) {
9670       return ZeroInitialization(E, E->getType());
9671     }
9672     bool ZeroInitialization(const Expr *E, QualType T);
9673 
9674     bool VisitCallExpr(const CallExpr *E) {
9675       return handleCallExpr(E, Result, &This);
9676     }
9677     bool VisitCastExpr(const CastExpr *E);
9678     bool VisitInitListExpr(const InitListExpr *E);
9679     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9680       return VisitCXXConstructExpr(E, E->getType());
9681     }
9682     bool VisitLambdaExpr(const LambdaExpr *E);
9683     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9684     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9685     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9686     bool VisitBinCmp(const BinaryOperator *E);
9687   };
9688 }
9689 
9690 /// Perform zero-initialization on an object of non-union class type.
9691 /// C++11 [dcl.init]p5:
9692 ///  To zero-initialize an object or reference of type T means:
9693 ///    [...]
9694 ///    -- if T is a (possibly cv-qualified) non-union class type,
9695 ///       each non-static data member and each base-class subobject is
9696 ///       zero-initialized
9697 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9698                                           const RecordDecl *RD,
9699                                           const LValue &This, APValue &Result) {
9700   assert(!RD->isUnion() && "Expected non-union class type");
9701   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9702   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9703                    std::distance(RD->field_begin(), RD->field_end()));
9704 
9705   if (RD->isInvalidDecl()) return false;
9706   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9707 
9708   if (CD) {
9709     unsigned Index = 0;
9710     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9711            End = CD->bases_end(); I != End; ++I, ++Index) {
9712       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9713       LValue Subobject = This;
9714       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9715         return false;
9716       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9717                                          Result.getStructBase(Index)))
9718         return false;
9719     }
9720   }
9721 
9722   for (const auto *I : RD->fields()) {
9723     // -- if T is a reference type, no initialization is performed.
9724     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9725       continue;
9726 
9727     LValue Subobject = This;
9728     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9729       return false;
9730 
9731     ImplicitValueInitExpr VIE(I->getType());
9732     if (!EvaluateInPlace(
9733           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9734       return false;
9735   }
9736 
9737   return true;
9738 }
9739 
9740 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9741   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9742   if (RD->isInvalidDecl()) return false;
9743   if (RD->isUnion()) {
9744     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9745     // object's first non-static named data member is zero-initialized
9746     RecordDecl::field_iterator I = RD->field_begin();
9747     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9748       ++I;
9749     if (I == RD->field_end()) {
9750       Result = APValue((const FieldDecl*)nullptr);
9751       return true;
9752     }
9753 
9754     LValue Subobject = This;
9755     if (!HandleLValueMember(Info, E, Subobject, *I))
9756       return false;
9757     Result = APValue(*I);
9758     ImplicitValueInitExpr VIE(I->getType());
9759     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9760   }
9761 
9762   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9763     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9764     return false;
9765   }
9766 
9767   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9768 }
9769 
9770 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9771   switch (E->getCastKind()) {
9772   default:
9773     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9774 
9775   case CK_ConstructorConversion:
9776     return Visit(E->getSubExpr());
9777 
9778   case CK_DerivedToBase:
9779   case CK_UncheckedDerivedToBase: {
9780     APValue DerivedObject;
9781     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9782       return false;
9783     if (!DerivedObject.isStruct())
9784       return Error(E->getSubExpr());
9785 
9786     // Derived-to-base rvalue conversion: just slice off the derived part.
9787     APValue *Value = &DerivedObject;
9788     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9789     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9790          PathE = E->path_end(); PathI != PathE; ++PathI) {
9791       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9792       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9793       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9794       RD = Base;
9795     }
9796     Result = *Value;
9797     return true;
9798   }
9799   }
9800 }
9801 
9802 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9803   if (E->isTransparent())
9804     return Visit(E->getInit(0));
9805 
9806   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9807   if (RD->isInvalidDecl()) return false;
9808   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9809   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9810 
9811   EvalInfo::EvaluatingConstructorRAII EvalObj(
9812       Info,
9813       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9814       CXXRD && CXXRD->getNumBases());
9815 
9816   if (RD->isUnion()) {
9817     const FieldDecl *Field = E->getInitializedFieldInUnion();
9818     Result = APValue(Field);
9819     if (!Field)
9820       return true;
9821 
9822     // If the initializer list for a union does not contain any elements, the
9823     // first element of the union is value-initialized.
9824     // FIXME: The element should be initialized from an initializer list.
9825     //        Is this difference ever observable for initializer lists which
9826     //        we don't build?
9827     ImplicitValueInitExpr VIE(Field->getType());
9828     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9829 
9830     LValue Subobject = This;
9831     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9832       return false;
9833 
9834     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9835     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9836                                   isa<CXXDefaultInitExpr>(InitExpr));
9837 
9838     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9839       if (Field->isBitField())
9840         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9841                                      Field);
9842       return true;
9843     }
9844 
9845     return false;
9846   }
9847 
9848   if (!Result.hasValue())
9849     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9850                      std::distance(RD->field_begin(), RD->field_end()));
9851   unsigned ElementNo = 0;
9852   bool Success = true;
9853 
9854   // Initialize base classes.
9855   if (CXXRD && CXXRD->getNumBases()) {
9856     for (const auto &Base : CXXRD->bases()) {
9857       assert(ElementNo < E->getNumInits() && "missing init for base class");
9858       const Expr *Init = E->getInit(ElementNo);
9859 
9860       LValue Subobject = This;
9861       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9862         return false;
9863 
9864       APValue &FieldVal = Result.getStructBase(ElementNo);
9865       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9866         if (!Info.noteFailure())
9867           return false;
9868         Success = false;
9869       }
9870       ++ElementNo;
9871     }
9872 
9873     EvalObj.finishedConstructingBases();
9874   }
9875 
9876   // Initialize members.
9877   for (const auto *Field : RD->fields()) {
9878     // Anonymous bit-fields are not considered members of the class for
9879     // purposes of aggregate initialization.
9880     if (Field->isUnnamedBitfield())
9881       continue;
9882 
9883     LValue Subobject = This;
9884 
9885     bool HaveInit = ElementNo < E->getNumInits();
9886 
9887     // FIXME: Diagnostics here should point to the end of the initializer
9888     // list, not the start.
9889     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9890                             Subobject, Field, &Layout))
9891       return false;
9892 
9893     // Perform an implicit value-initialization for members beyond the end of
9894     // the initializer list.
9895     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9896     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9897 
9898     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9899     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9900                                   isa<CXXDefaultInitExpr>(Init));
9901 
9902     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9903     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9904         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9905                                                        FieldVal, Field))) {
9906       if (!Info.noteFailure())
9907         return false;
9908       Success = false;
9909     }
9910   }
9911 
9912   EvalObj.finishedConstructingFields();
9913 
9914   return Success;
9915 }
9916 
9917 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9918                                                 QualType T) {
9919   // Note that E's type is not necessarily the type of our class here; we might
9920   // be initializing an array element instead.
9921   const CXXConstructorDecl *FD = E->getConstructor();
9922   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9923 
9924   bool ZeroInit = E->requiresZeroInitialization();
9925   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9926     // If we've already performed zero-initialization, we're already done.
9927     if (Result.hasValue())
9928       return true;
9929 
9930     if (ZeroInit)
9931       return ZeroInitialization(E, T);
9932 
9933     return getDefaultInitValue(T, Result);
9934   }
9935 
9936   const FunctionDecl *Definition = nullptr;
9937   auto Body = FD->getBody(Definition);
9938 
9939   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9940     return false;
9941 
9942   // Avoid materializing a temporary for an elidable copy/move constructor.
9943   if (E->isElidable() && !ZeroInit) {
9944     // FIXME: This only handles the simplest case, where the source object
9945     //        is passed directly as the first argument to the constructor.
9946     //        This should also handle stepping though implicit casts and
9947     //        and conversion sequences which involve two steps, with a
9948     //        conversion operator followed by a converting constructor.
9949     const Expr *SrcObj = E->getArg(0);
9950     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9951     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9952     if (const MaterializeTemporaryExpr *ME =
9953             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9954       return Visit(ME->getSubExpr());
9955   }
9956 
9957   if (ZeroInit && !ZeroInitialization(E, T))
9958     return false;
9959 
9960   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9961   return HandleConstructorCall(E, This, Args,
9962                                cast<CXXConstructorDecl>(Definition), Info,
9963                                Result);
9964 }
9965 
9966 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9967     const CXXInheritedCtorInitExpr *E) {
9968   if (!Info.CurrentCall) {
9969     assert(Info.checkingPotentialConstantExpression());
9970     return false;
9971   }
9972 
9973   const CXXConstructorDecl *FD = E->getConstructor();
9974   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9975     return false;
9976 
9977   const FunctionDecl *Definition = nullptr;
9978   auto Body = FD->getBody(Definition);
9979 
9980   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9981     return false;
9982 
9983   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9984                                cast<CXXConstructorDecl>(Definition), Info,
9985                                Result);
9986 }
9987 
9988 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9989     const CXXStdInitializerListExpr *E) {
9990   const ConstantArrayType *ArrayType =
9991       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9992 
9993   LValue Array;
9994   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9995     return false;
9996 
9997   // Get a pointer to the first element of the array.
9998   Array.addArray(Info, E, ArrayType);
9999 
10000   auto InvalidType = [&] {
10001     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10002       << E->getType();
10003     return false;
10004   };
10005 
10006   // FIXME: Perform the checks on the field types in SemaInit.
10007   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10008   RecordDecl::field_iterator Field = Record->field_begin();
10009   if (Field == Record->field_end())
10010     return InvalidType();
10011 
10012   // Start pointer.
10013   if (!Field->getType()->isPointerType() ||
10014       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10015                             ArrayType->getElementType()))
10016     return InvalidType();
10017 
10018   // FIXME: What if the initializer_list type has base classes, etc?
10019   Result = APValue(APValue::UninitStruct(), 0, 2);
10020   Array.moveInto(Result.getStructField(0));
10021 
10022   if (++Field == Record->field_end())
10023     return InvalidType();
10024 
10025   if (Field->getType()->isPointerType() &&
10026       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10027                            ArrayType->getElementType())) {
10028     // End pointer.
10029     if (!HandleLValueArrayAdjustment(Info, E, Array,
10030                                      ArrayType->getElementType(),
10031                                      ArrayType->getSize().getZExtValue()))
10032       return false;
10033     Array.moveInto(Result.getStructField(1));
10034   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10035     // Length.
10036     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10037   else
10038     return InvalidType();
10039 
10040   if (++Field != Record->field_end())
10041     return InvalidType();
10042 
10043   return true;
10044 }
10045 
10046 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10047   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10048   if (ClosureClass->isInvalidDecl())
10049     return false;
10050 
10051   const size_t NumFields =
10052       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10053 
10054   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10055                                             E->capture_init_end()) &&
10056          "The number of lambda capture initializers should equal the number of "
10057          "fields within the closure type");
10058 
10059   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10060   // Iterate through all the lambda's closure object's fields and initialize
10061   // them.
10062   auto *CaptureInitIt = E->capture_init_begin();
10063   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10064   bool Success = true;
10065   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10066   for (const auto *Field : ClosureClass->fields()) {
10067     assert(CaptureInitIt != E->capture_init_end());
10068     // Get the initializer for this field
10069     Expr *const CurFieldInit = *CaptureInitIt++;
10070 
10071     // If there is no initializer, either this is a VLA or an error has
10072     // occurred.
10073     if (!CurFieldInit)
10074       return Error(E);
10075 
10076     LValue Subobject = This;
10077 
10078     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10079       return false;
10080 
10081     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10082     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10083       if (!Info.keepEvaluatingAfterFailure())
10084         return false;
10085       Success = false;
10086     }
10087     ++CaptureIt;
10088   }
10089   return Success;
10090 }
10091 
10092 static bool EvaluateRecord(const Expr *E, const LValue &This,
10093                            APValue &Result, EvalInfo &Info) {
10094   assert(!E->isValueDependent());
10095   assert(E->isPRValue() && E->getType()->isRecordType() &&
10096          "can't evaluate expression as a record rvalue");
10097   return RecordExprEvaluator(Info, This, Result).Visit(E);
10098 }
10099 
10100 //===----------------------------------------------------------------------===//
10101 // Temporary Evaluation
10102 //
10103 // Temporaries are represented in the AST as rvalues, but generally behave like
10104 // lvalues. The full-object of which the temporary is a subobject is implicitly
10105 // materialized so that a reference can bind to it.
10106 //===----------------------------------------------------------------------===//
10107 namespace {
10108 class TemporaryExprEvaluator
10109   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10110 public:
10111   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10112     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10113 
10114   /// Visit an expression which constructs the value of this temporary.
10115   bool VisitConstructExpr(const Expr *E) {
10116     APValue &Value = Info.CurrentCall->createTemporary(
10117         E, E->getType(), ScopeKind::FullExpression, Result);
10118     return EvaluateInPlace(Value, Info, Result, E);
10119   }
10120 
10121   bool VisitCastExpr(const CastExpr *E) {
10122     switch (E->getCastKind()) {
10123     default:
10124       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10125 
10126     case CK_ConstructorConversion:
10127       return VisitConstructExpr(E->getSubExpr());
10128     }
10129   }
10130   bool VisitInitListExpr(const InitListExpr *E) {
10131     return VisitConstructExpr(E);
10132   }
10133   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10134     return VisitConstructExpr(E);
10135   }
10136   bool VisitCallExpr(const CallExpr *E) {
10137     return VisitConstructExpr(E);
10138   }
10139   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10140     return VisitConstructExpr(E);
10141   }
10142   bool VisitLambdaExpr(const LambdaExpr *E) {
10143     return VisitConstructExpr(E);
10144   }
10145 };
10146 } // end anonymous namespace
10147 
10148 /// Evaluate an expression of record type as a temporary.
10149 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10150   assert(!E->isValueDependent());
10151   assert(E->isPRValue() && E->getType()->isRecordType());
10152   return TemporaryExprEvaluator(Info, Result).Visit(E);
10153 }
10154 
10155 //===----------------------------------------------------------------------===//
10156 // Vector Evaluation
10157 //===----------------------------------------------------------------------===//
10158 
10159 namespace {
10160   class VectorExprEvaluator
10161   : public ExprEvaluatorBase<VectorExprEvaluator> {
10162     APValue &Result;
10163   public:
10164 
10165     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10166       : ExprEvaluatorBaseTy(info), Result(Result) {}
10167 
10168     bool Success(ArrayRef<APValue> V, const Expr *E) {
10169       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10170       // FIXME: remove this APValue copy.
10171       Result = APValue(V.data(), V.size());
10172       return true;
10173     }
10174     bool Success(const APValue &V, const Expr *E) {
10175       assert(V.isVector());
10176       Result = V;
10177       return true;
10178     }
10179     bool ZeroInitialization(const Expr *E);
10180 
10181     bool VisitUnaryReal(const UnaryOperator *E)
10182       { return Visit(E->getSubExpr()); }
10183     bool VisitCastExpr(const CastExpr* E);
10184     bool VisitInitListExpr(const InitListExpr *E);
10185     bool VisitUnaryImag(const UnaryOperator *E);
10186     bool VisitBinaryOperator(const BinaryOperator *E);
10187     bool VisitUnaryOperator(const UnaryOperator *E);
10188     // FIXME: Missing: conditional operator (for GNU
10189     //                 conditional select), shufflevector, ExtVectorElementExpr
10190   };
10191 } // end anonymous namespace
10192 
10193 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10194   assert(E->isPRValue() && E->getType()->isVectorType() &&
10195          "not a vector prvalue");
10196   return VectorExprEvaluator(Info, Result).Visit(E);
10197 }
10198 
10199 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10200   const VectorType *VTy = E->getType()->castAs<VectorType>();
10201   unsigned NElts = VTy->getNumElements();
10202 
10203   const Expr *SE = E->getSubExpr();
10204   QualType SETy = SE->getType();
10205 
10206   switch (E->getCastKind()) {
10207   case CK_VectorSplat: {
10208     APValue Val = APValue();
10209     if (SETy->isIntegerType()) {
10210       APSInt IntResult;
10211       if (!EvaluateInteger(SE, IntResult, Info))
10212         return false;
10213       Val = APValue(std::move(IntResult));
10214     } else if (SETy->isRealFloatingType()) {
10215       APFloat FloatResult(0.0);
10216       if (!EvaluateFloat(SE, FloatResult, Info))
10217         return false;
10218       Val = APValue(std::move(FloatResult));
10219     } else {
10220       return Error(E);
10221     }
10222 
10223     // Splat and create vector APValue.
10224     SmallVector<APValue, 4> Elts(NElts, Val);
10225     return Success(Elts, E);
10226   }
10227   case CK_BitCast: {
10228     // Evaluate the operand into an APInt we can extract from.
10229     llvm::APInt SValInt;
10230     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10231       return false;
10232     // Extract the elements
10233     QualType EltTy = VTy->getElementType();
10234     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10235     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10236     SmallVector<APValue, 4> Elts;
10237     if (EltTy->isRealFloatingType()) {
10238       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10239       unsigned FloatEltSize = EltSize;
10240       if (&Sem == &APFloat::x87DoubleExtended())
10241         FloatEltSize = 80;
10242       for (unsigned i = 0; i < NElts; i++) {
10243         llvm::APInt Elt;
10244         if (BigEndian)
10245           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10246         else
10247           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10248         Elts.push_back(APValue(APFloat(Sem, Elt)));
10249       }
10250     } else if (EltTy->isIntegerType()) {
10251       for (unsigned i = 0; i < NElts; i++) {
10252         llvm::APInt Elt;
10253         if (BigEndian)
10254           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10255         else
10256           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10257         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10258       }
10259     } else {
10260       return Error(E);
10261     }
10262     return Success(Elts, E);
10263   }
10264   default:
10265     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10266   }
10267 }
10268 
10269 bool
10270 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10271   const VectorType *VT = E->getType()->castAs<VectorType>();
10272   unsigned NumInits = E->getNumInits();
10273   unsigned NumElements = VT->getNumElements();
10274 
10275   QualType EltTy = VT->getElementType();
10276   SmallVector<APValue, 4> Elements;
10277 
10278   // The number of initializers can be less than the number of
10279   // vector elements. For OpenCL, this can be due to nested vector
10280   // initialization. For GCC compatibility, missing trailing elements
10281   // should be initialized with zeroes.
10282   unsigned CountInits = 0, CountElts = 0;
10283   while (CountElts < NumElements) {
10284     // Handle nested vector initialization.
10285     if (CountInits < NumInits
10286         && E->getInit(CountInits)->getType()->isVectorType()) {
10287       APValue v;
10288       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10289         return Error(E);
10290       unsigned vlen = v.getVectorLength();
10291       for (unsigned j = 0; j < vlen; j++)
10292         Elements.push_back(v.getVectorElt(j));
10293       CountElts += vlen;
10294     } else if (EltTy->isIntegerType()) {
10295       llvm::APSInt sInt(32);
10296       if (CountInits < NumInits) {
10297         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10298           return false;
10299       } else // trailing integer zero.
10300         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10301       Elements.push_back(APValue(sInt));
10302       CountElts++;
10303     } else {
10304       llvm::APFloat f(0.0);
10305       if (CountInits < NumInits) {
10306         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10307           return false;
10308       } else // trailing float zero.
10309         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10310       Elements.push_back(APValue(f));
10311       CountElts++;
10312     }
10313     CountInits++;
10314   }
10315   return Success(Elements, E);
10316 }
10317 
10318 bool
10319 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10320   const auto *VT = E->getType()->castAs<VectorType>();
10321   QualType EltTy = VT->getElementType();
10322   APValue ZeroElement;
10323   if (EltTy->isIntegerType())
10324     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10325   else
10326     ZeroElement =
10327         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10328 
10329   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10330   return Success(Elements, E);
10331 }
10332 
10333 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10334   VisitIgnoredValue(E->getSubExpr());
10335   return ZeroInitialization(E);
10336 }
10337 
10338 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10339   BinaryOperatorKind Op = E->getOpcode();
10340   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10341          "Operation not supported on vector types");
10342 
10343   if (Op == BO_Comma)
10344     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10345 
10346   Expr *LHS = E->getLHS();
10347   Expr *RHS = E->getRHS();
10348 
10349   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10350          "Must both be vector types");
10351   // Checking JUST the types are the same would be fine, except shifts don't
10352   // need to have their types be the same (since you always shift by an int).
10353   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10354              E->getType()->castAs<VectorType>()->getNumElements() &&
10355          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10356              E->getType()->castAs<VectorType>()->getNumElements() &&
10357          "All operands must be the same size.");
10358 
10359   APValue LHSValue;
10360   APValue RHSValue;
10361   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10362   if (!LHSOK && !Info.noteFailure())
10363     return false;
10364   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10365     return false;
10366 
10367   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10368     return false;
10369 
10370   return Success(LHSValue, E);
10371 }
10372 
10373 static llvm::Optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10374                                                          QualType ResultTy,
10375                                                          UnaryOperatorKind Op,
10376                                                          APValue Elt) {
10377   switch (Op) {
10378   case UO_Plus:
10379     // Nothing to do here.
10380     return Elt;
10381   case UO_Minus:
10382     if (Elt.getKind() == APValue::Int) {
10383       Elt.getInt().negate();
10384     } else {
10385       assert(Elt.getKind() == APValue::Float &&
10386              "Vector can only be int or float type");
10387       Elt.getFloat().changeSign();
10388     }
10389     return Elt;
10390   case UO_Not:
10391     // This is only valid for integral types anyway, so we don't have to handle
10392     // float here.
10393     assert(Elt.getKind() == APValue::Int &&
10394            "Vector operator ~ can only be int");
10395     Elt.getInt().flipAllBits();
10396     return Elt;
10397   case UO_LNot: {
10398     if (Elt.getKind() == APValue::Int) {
10399       Elt.getInt() = !Elt.getInt();
10400       // operator ! on vectors returns -1 for 'truth', so negate it.
10401       Elt.getInt().negate();
10402       return Elt;
10403     }
10404     assert(Elt.getKind() == APValue::Float &&
10405            "Vector can only be int or float type");
10406     // Float types result in an int of the same size, but -1 for true, or 0 for
10407     // false.
10408     APSInt EltResult{Ctx.getIntWidth(ResultTy),
10409                      ResultTy->isUnsignedIntegerType()};
10410     if (Elt.getFloat().isZero())
10411       EltResult.setAllBits();
10412     else
10413       EltResult.clearAllBits();
10414 
10415     return APValue{EltResult};
10416   }
10417   default:
10418     // FIXME: Implement the rest of the unary operators.
10419     return llvm::None;
10420   }
10421 }
10422 
10423 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10424   Expr *SubExpr = E->getSubExpr();
10425   const auto *VD = SubExpr->getType()->castAs<VectorType>();
10426   // This result element type differs in the case of negating a floating point
10427   // vector, since the result type is the a vector of the equivilant sized
10428   // integer.
10429   const QualType ResultEltTy = VD->getElementType();
10430   UnaryOperatorKind Op = E->getOpcode();
10431 
10432   APValue SubExprValue;
10433   if (!Evaluate(SubExprValue, Info, SubExpr))
10434     return false;
10435 
10436   assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10437          "Vector length doesn't match type?");
10438 
10439   SmallVector<APValue, 4> ResultElements;
10440   for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10441     llvm::Optional<APValue> Elt = handleVectorUnaryOperator(
10442         Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10443     if (!Elt)
10444       return false;
10445     ResultElements.push_back(*Elt);
10446   }
10447   return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10448 }
10449 
10450 //===----------------------------------------------------------------------===//
10451 // Array Evaluation
10452 //===----------------------------------------------------------------------===//
10453 
10454 namespace {
10455   class ArrayExprEvaluator
10456   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10457     const LValue &This;
10458     APValue &Result;
10459   public:
10460 
10461     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10462       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10463 
10464     bool Success(const APValue &V, const Expr *E) {
10465       assert(V.isArray() && "expected array");
10466       Result = V;
10467       return true;
10468     }
10469 
10470     bool ZeroInitialization(const Expr *E) {
10471       const ConstantArrayType *CAT =
10472           Info.Ctx.getAsConstantArrayType(E->getType());
10473       if (!CAT) {
10474         if (E->getType()->isIncompleteArrayType()) {
10475           // We can be asked to zero-initialize a flexible array member; this
10476           // is represented as an ImplicitValueInitExpr of incomplete array
10477           // type. In this case, the array has zero elements.
10478           Result = APValue(APValue::UninitArray(), 0, 0);
10479           return true;
10480         }
10481         // FIXME: We could handle VLAs here.
10482         return Error(E);
10483       }
10484 
10485       Result = APValue(APValue::UninitArray(), 0,
10486                        CAT->getSize().getZExtValue());
10487       if (!Result.hasArrayFiller())
10488         return true;
10489 
10490       // Zero-initialize all elements.
10491       LValue Subobject = This;
10492       Subobject.addArray(Info, E, CAT);
10493       ImplicitValueInitExpr VIE(CAT->getElementType());
10494       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10495     }
10496 
10497     bool VisitCallExpr(const CallExpr *E) {
10498       return handleCallExpr(E, Result, &This);
10499     }
10500     bool VisitInitListExpr(const InitListExpr *E,
10501                            QualType AllocType = QualType());
10502     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10503     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10504     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10505                                const LValue &Subobject,
10506                                APValue *Value, QualType Type);
10507     bool VisitStringLiteral(const StringLiteral *E,
10508                             QualType AllocType = QualType()) {
10509       expandStringLiteral(Info, E, Result, AllocType);
10510       return true;
10511     }
10512   };
10513 } // end anonymous namespace
10514 
10515 static bool EvaluateArray(const Expr *E, const LValue &This,
10516                           APValue &Result, EvalInfo &Info) {
10517   assert(!E->isValueDependent());
10518   assert(E->isPRValue() && E->getType()->isArrayType() &&
10519          "not an array prvalue");
10520   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10521 }
10522 
10523 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10524                                      APValue &Result, const InitListExpr *ILE,
10525                                      QualType AllocType) {
10526   assert(!ILE->isValueDependent());
10527   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10528          "not an array prvalue");
10529   return ArrayExprEvaluator(Info, This, Result)
10530       .VisitInitListExpr(ILE, AllocType);
10531 }
10532 
10533 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10534                                           APValue &Result,
10535                                           const CXXConstructExpr *CCE,
10536                                           QualType AllocType) {
10537   assert(!CCE->isValueDependent());
10538   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10539          "not an array prvalue");
10540   return ArrayExprEvaluator(Info, This, Result)
10541       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10542 }
10543 
10544 // Return true iff the given array filler may depend on the element index.
10545 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10546   // For now, just allow non-class value-initialization and initialization
10547   // lists comprised of them.
10548   if (isa<ImplicitValueInitExpr>(FillerExpr))
10549     return false;
10550   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10551     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10552       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10553         return true;
10554     }
10555     return false;
10556   }
10557   return true;
10558 }
10559 
10560 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10561                                            QualType AllocType) {
10562   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10563       AllocType.isNull() ? E->getType() : AllocType);
10564   if (!CAT)
10565     return Error(E);
10566 
10567   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10568   // an appropriately-typed string literal enclosed in braces.
10569   if (E->isStringLiteralInit()) {
10570     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10571     // FIXME: Support ObjCEncodeExpr here once we support it in
10572     // ArrayExprEvaluator generally.
10573     if (!SL)
10574       return Error(E);
10575     return VisitStringLiteral(SL, AllocType);
10576   }
10577   // Any other transparent list init will need proper handling of the
10578   // AllocType; we can't just recurse to the inner initializer.
10579   assert(!E->isTransparent() &&
10580          "transparent array list initialization is not string literal init?");
10581 
10582   bool Success = true;
10583 
10584   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10585          "zero-initialized array shouldn't have any initialized elts");
10586   APValue Filler;
10587   if (Result.isArray() && Result.hasArrayFiller())
10588     Filler = Result.getArrayFiller();
10589 
10590   unsigned NumEltsToInit = E->getNumInits();
10591   unsigned NumElts = CAT->getSize().getZExtValue();
10592   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10593 
10594   // If the initializer might depend on the array index, run it for each
10595   // array element.
10596   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10597     NumEltsToInit = NumElts;
10598 
10599   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10600                           << NumEltsToInit << ".\n");
10601 
10602   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10603 
10604   // If the array was previously zero-initialized, preserve the
10605   // zero-initialized values.
10606   if (Filler.hasValue()) {
10607     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10608       Result.getArrayInitializedElt(I) = Filler;
10609     if (Result.hasArrayFiller())
10610       Result.getArrayFiller() = Filler;
10611   }
10612 
10613   LValue Subobject = This;
10614   Subobject.addArray(Info, E, CAT);
10615   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10616     const Expr *Init =
10617         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10618     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10619                          Info, Subobject, Init) ||
10620         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10621                                      CAT->getElementType(), 1)) {
10622       if (!Info.noteFailure())
10623         return false;
10624       Success = false;
10625     }
10626   }
10627 
10628   if (!Result.hasArrayFiller())
10629     return Success;
10630 
10631   // If we get here, we have a trivial filler, which we can just evaluate
10632   // once and splat over the rest of the array elements.
10633   assert(FillerExpr && "no array filler for incomplete init list");
10634   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10635                          FillerExpr) && Success;
10636 }
10637 
10638 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10639   LValue CommonLV;
10640   if (E->getCommonExpr() &&
10641       !Evaluate(Info.CurrentCall->createTemporary(
10642                     E->getCommonExpr(),
10643                     getStorageType(Info.Ctx, E->getCommonExpr()),
10644                     ScopeKind::FullExpression, CommonLV),
10645                 Info, E->getCommonExpr()->getSourceExpr()))
10646     return false;
10647 
10648   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10649 
10650   uint64_t Elements = CAT->getSize().getZExtValue();
10651   Result = APValue(APValue::UninitArray(), Elements, Elements);
10652 
10653   LValue Subobject = This;
10654   Subobject.addArray(Info, E, CAT);
10655 
10656   bool Success = true;
10657   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10658     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10659                          Info, Subobject, E->getSubExpr()) ||
10660         !HandleLValueArrayAdjustment(Info, E, Subobject,
10661                                      CAT->getElementType(), 1)) {
10662       if (!Info.noteFailure())
10663         return false;
10664       Success = false;
10665     }
10666   }
10667 
10668   return Success;
10669 }
10670 
10671 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10672   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10673 }
10674 
10675 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10676                                                const LValue &Subobject,
10677                                                APValue *Value,
10678                                                QualType Type) {
10679   bool HadZeroInit = Value->hasValue();
10680 
10681   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10682     unsigned N = CAT->getSize().getZExtValue();
10683 
10684     // Preserve the array filler if we had prior zero-initialization.
10685     APValue Filler =
10686       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10687                                              : APValue();
10688 
10689     *Value = APValue(APValue::UninitArray(), N, N);
10690 
10691     if (HadZeroInit)
10692       for (unsigned I = 0; I != N; ++I)
10693         Value->getArrayInitializedElt(I) = Filler;
10694 
10695     // Initialize the elements.
10696     LValue ArrayElt = Subobject;
10697     ArrayElt.addArray(Info, E, CAT);
10698     for (unsigned I = 0; I != N; ++I)
10699       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10700                                  CAT->getElementType()) ||
10701           !HandleLValueArrayAdjustment(Info, E, ArrayElt, CAT->getElementType(),
10702                                        1))
10703         return false;
10704 
10705     return true;
10706   }
10707 
10708   if (!Type->isRecordType())
10709     return Error(E);
10710 
10711   return RecordExprEvaluator(Info, Subobject, *Value)
10712              .VisitCXXConstructExpr(E, Type);
10713 }
10714 
10715 //===----------------------------------------------------------------------===//
10716 // Integer Evaluation
10717 //
10718 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10719 // types and back in constant folding. Integer values are thus represented
10720 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10721 //===----------------------------------------------------------------------===//
10722 
10723 namespace {
10724 class IntExprEvaluator
10725         : public ExprEvaluatorBase<IntExprEvaluator> {
10726   APValue &Result;
10727 public:
10728   IntExprEvaluator(EvalInfo &info, APValue &result)
10729       : ExprEvaluatorBaseTy(info), Result(result) {}
10730 
10731   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10732     assert(E->getType()->isIntegralOrEnumerationType() &&
10733            "Invalid evaluation result.");
10734     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10735            "Invalid evaluation result.");
10736     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10737            "Invalid evaluation result.");
10738     Result = APValue(SI);
10739     return true;
10740   }
10741   bool Success(const llvm::APSInt &SI, const Expr *E) {
10742     return Success(SI, E, Result);
10743   }
10744 
10745   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10746     assert(E->getType()->isIntegralOrEnumerationType() &&
10747            "Invalid evaluation result.");
10748     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10749            "Invalid evaluation result.");
10750     Result = APValue(APSInt(I));
10751     Result.getInt().setIsUnsigned(
10752                             E->getType()->isUnsignedIntegerOrEnumerationType());
10753     return true;
10754   }
10755   bool Success(const llvm::APInt &I, const Expr *E) {
10756     return Success(I, E, Result);
10757   }
10758 
10759   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10760     assert(E->getType()->isIntegralOrEnumerationType() &&
10761            "Invalid evaluation result.");
10762     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10763     return true;
10764   }
10765   bool Success(uint64_t Value, const Expr *E) {
10766     return Success(Value, E, Result);
10767   }
10768 
10769   bool Success(CharUnits Size, const Expr *E) {
10770     return Success(Size.getQuantity(), E);
10771   }
10772 
10773   bool Success(const APValue &V, const Expr *E) {
10774     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10775       Result = V;
10776       return true;
10777     }
10778     return Success(V.getInt(), E);
10779   }
10780 
10781   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10782 
10783   //===--------------------------------------------------------------------===//
10784   //                            Visitor Methods
10785   //===--------------------------------------------------------------------===//
10786 
10787   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10788     return Success(E->getValue(), E);
10789   }
10790   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10791     return Success(E->getValue(), E);
10792   }
10793 
10794   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10795   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10796     if (CheckReferencedDecl(E, E->getDecl()))
10797       return true;
10798 
10799     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10800   }
10801   bool VisitMemberExpr(const MemberExpr *E) {
10802     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10803       VisitIgnoredBaseExpression(E->getBase());
10804       return true;
10805     }
10806 
10807     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10808   }
10809 
10810   bool VisitCallExpr(const CallExpr *E);
10811   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10812   bool VisitBinaryOperator(const BinaryOperator *E);
10813   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10814   bool VisitUnaryOperator(const UnaryOperator *E);
10815 
10816   bool VisitCastExpr(const CastExpr* E);
10817   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10818 
10819   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10820     return Success(E->getValue(), E);
10821   }
10822 
10823   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10824     return Success(E->getValue(), E);
10825   }
10826 
10827   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10828     if (Info.ArrayInitIndex == uint64_t(-1)) {
10829       // We were asked to evaluate this subexpression independent of the
10830       // enclosing ArrayInitLoopExpr. We can't do that.
10831       Info.FFDiag(E);
10832       return false;
10833     }
10834     return Success(Info.ArrayInitIndex, E);
10835   }
10836 
10837   // Note, GNU defines __null as an integer, not a pointer.
10838   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10839     return ZeroInitialization(E);
10840   }
10841 
10842   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10843     return Success(E->getValue(), E);
10844   }
10845 
10846   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10847     return Success(E->getValue(), E);
10848   }
10849 
10850   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10851     return Success(E->getValue(), E);
10852   }
10853 
10854   bool VisitUnaryReal(const UnaryOperator *E);
10855   bool VisitUnaryImag(const UnaryOperator *E);
10856 
10857   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10858   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10859   bool VisitSourceLocExpr(const SourceLocExpr *E);
10860   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10861   bool VisitRequiresExpr(const RequiresExpr *E);
10862   // FIXME: Missing: array subscript of vector, member of vector
10863 };
10864 
10865 class FixedPointExprEvaluator
10866     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10867   APValue &Result;
10868 
10869  public:
10870   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10871       : ExprEvaluatorBaseTy(info), Result(result) {}
10872 
10873   bool Success(const llvm::APInt &I, const Expr *E) {
10874     return Success(
10875         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10876   }
10877 
10878   bool Success(uint64_t Value, const Expr *E) {
10879     return Success(
10880         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10881   }
10882 
10883   bool Success(const APValue &V, const Expr *E) {
10884     return Success(V.getFixedPoint(), E);
10885   }
10886 
10887   bool Success(const APFixedPoint &V, const Expr *E) {
10888     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10889     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10890            "Invalid evaluation result.");
10891     Result = APValue(V);
10892     return true;
10893   }
10894 
10895   //===--------------------------------------------------------------------===//
10896   //                            Visitor Methods
10897   //===--------------------------------------------------------------------===//
10898 
10899   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10900     return Success(E->getValue(), E);
10901   }
10902 
10903   bool VisitCastExpr(const CastExpr *E);
10904   bool VisitUnaryOperator(const UnaryOperator *E);
10905   bool VisitBinaryOperator(const BinaryOperator *E);
10906 };
10907 } // end anonymous namespace
10908 
10909 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10910 /// produce either the integer value or a pointer.
10911 ///
10912 /// GCC has a heinous extension which folds casts between pointer types and
10913 /// pointer-sized integral types. We support this by allowing the evaluation of
10914 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10915 /// Some simple arithmetic on such values is supported (they are treated much
10916 /// like char*).
10917 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10918                                     EvalInfo &Info) {
10919   assert(!E->isValueDependent());
10920   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10921   return IntExprEvaluator(Info, Result).Visit(E);
10922 }
10923 
10924 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10925   assert(!E->isValueDependent());
10926   APValue Val;
10927   if (!EvaluateIntegerOrLValue(E, Val, Info))
10928     return false;
10929   if (!Val.isInt()) {
10930     // FIXME: It would be better to produce the diagnostic for casting
10931     //        a pointer to an integer.
10932     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10933     return false;
10934   }
10935   Result = Val.getInt();
10936   return true;
10937 }
10938 
10939 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10940   APValue Evaluated = E->EvaluateInContext(
10941       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10942   return Success(Evaluated, E);
10943 }
10944 
10945 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10946                                EvalInfo &Info) {
10947   assert(!E->isValueDependent());
10948   if (E->getType()->isFixedPointType()) {
10949     APValue Val;
10950     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10951       return false;
10952     if (!Val.isFixedPoint())
10953       return false;
10954 
10955     Result = Val.getFixedPoint();
10956     return true;
10957   }
10958   return false;
10959 }
10960 
10961 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10962                                         EvalInfo &Info) {
10963   assert(!E->isValueDependent());
10964   if (E->getType()->isIntegerType()) {
10965     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10966     APSInt Val;
10967     if (!EvaluateInteger(E, Val, Info))
10968       return false;
10969     Result = APFixedPoint(Val, FXSema);
10970     return true;
10971   } else if (E->getType()->isFixedPointType()) {
10972     return EvaluateFixedPoint(E, Result, Info);
10973   }
10974   return false;
10975 }
10976 
10977 /// Check whether the given declaration can be directly converted to an integral
10978 /// rvalue. If not, no diagnostic is produced; there are other things we can
10979 /// try.
10980 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10981   // Enums are integer constant exprs.
10982   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10983     // Check for signedness/width mismatches between E type and ECD value.
10984     bool SameSign = (ECD->getInitVal().isSigned()
10985                      == E->getType()->isSignedIntegerOrEnumerationType());
10986     bool SameWidth = (ECD->getInitVal().getBitWidth()
10987                       == Info.Ctx.getIntWidth(E->getType()));
10988     if (SameSign && SameWidth)
10989       return Success(ECD->getInitVal(), E);
10990     else {
10991       // Get rid of mismatch (otherwise Success assertions will fail)
10992       // by computing a new value matching the type of E.
10993       llvm::APSInt Val = ECD->getInitVal();
10994       if (!SameSign)
10995         Val.setIsSigned(!ECD->getInitVal().isSigned());
10996       if (!SameWidth)
10997         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10998       return Success(Val, E);
10999     }
11000   }
11001   return false;
11002 }
11003 
11004 /// Values returned by __builtin_classify_type, chosen to match the values
11005 /// produced by GCC's builtin.
11006 enum class GCCTypeClass {
11007   None = -1,
11008   Void = 0,
11009   Integer = 1,
11010   // GCC reserves 2 for character types, but instead classifies them as
11011   // integers.
11012   Enum = 3,
11013   Bool = 4,
11014   Pointer = 5,
11015   // GCC reserves 6 for references, but appears to never use it (because
11016   // expressions never have reference type, presumably).
11017   PointerToDataMember = 7,
11018   RealFloat = 8,
11019   Complex = 9,
11020   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11021   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11022   // GCC claims to reserve 11 for pointers to member functions, but *actually*
11023   // uses 12 for that purpose, same as for a class or struct. Maybe it
11024   // internally implements a pointer to member as a struct?  Who knows.
11025   PointerToMemberFunction = 12, // Not a bug, see above.
11026   ClassOrStruct = 12,
11027   Union = 13,
11028   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11029   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11030   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11031   // literals.
11032 };
11033 
11034 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11035 /// as GCC.
11036 static GCCTypeClass
11037 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11038   assert(!T->isDependentType() && "unexpected dependent type");
11039 
11040   QualType CanTy = T.getCanonicalType();
11041   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11042 
11043   switch (CanTy->getTypeClass()) {
11044 #define TYPE(ID, BASE)
11045 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11046 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11047 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11048 #include "clang/AST/TypeNodes.inc"
11049   case Type::Auto:
11050   case Type::DeducedTemplateSpecialization:
11051       llvm_unreachable("unexpected non-canonical or dependent type");
11052 
11053   case Type::Builtin:
11054     switch (BT->getKind()) {
11055 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11056 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11057     case BuiltinType::ID: return GCCTypeClass::Integer;
11058 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11059     case BuiltinType::ID: return GCCTypeClass::RealFloat;
11060 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11061     case BuiltinType::ID: break;
11062 #include "clang/AST/BuiltinTypes.def"
11063     case BuiltinType::Void:
11064       return GCCTypeClass::Void;
11065 
11066     case BuiltinType::Bool:
11067       return GCCTypeClass::Bool;
11068 
11069     case BuiltinType::Char_U:
11070     case BuiltinType::UChar:
11071     case BuiltinType::WChar_U:
11072     case BuiltinType::Char8:
11073     case BuiltinType::Char16:
11074     case BuiltinType::Char32:
11075     case BuiltinType::UShort:
11076     case BuiltinType::UInt:
11077     case BuiltinType::ULong:
11078     case BuiltinType::ULongLong:
11079     case BuiltinType::UInt128:
11080       return GCCTypeClass::Integer;
11081 
11082     case BuiltinType::UShortAccum:
11083     case BuiltinType::UAccum:
11084     case BuiltinType::ULongAccum:
11085     case BuiltinType::UShortFract:
11086     case BuiltinType::UFract:
11087     case BuiltinType::ULongFract:
11088     case BuiltinType::SatUShortAccum:
11089     case BuiltinType::SatUAccum:
11090     case BuiltinType::SatULongAccum:
11091     case BuiltinType::SatUShortFract:
11092     case BuiltinType::SatUFract:
11093     case BuiltinType::SatULongFract:
11094       return GCCTypeClass::None;
11095 
11096     case BuiltinType::NullPtr:
11097 
11098     case BuiltinType::ObjCId:
11099     case BuiltinType::ObjCClass:
11100     case BuiltinType::ObjCSel:
11101 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11102     case BuiltinType::Id:
11103 #include "clang/Basic/OpenCLImageTypes.def"
11104 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11105     case BuiltinType::Id:
11106 #include "clang/Basic/OpenCLExtensionTypes.def"
11107     case BuiltinType::OCLSampler:
11108     case BuiltinType::OCLEvent:
11109     case BuiltinType::OCLClkEvent:
11110     case BuiltinType::OCLQueue:
11111     case BuiltinType::OCLReserveID:
11112 #define SVE_TYPE(Name, Id, SingletonId) \
11113     case BuiltinType::Id:
11114 #include "clang/Basic/AArch64SVEACLETypes.def"
11115 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11116     case BuiltinType::Id:
11117 #include "clang/Basic/PPCTypes.def"
11118 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11119 #include "clang/Basic/RISCVVTypes.def"
11120       return GCCTypeClass::None;
11121 
11122     case BuiltinType::Dependent:
11123       llvm_unreachable("unexpected dependent type");
11124     };
11125     llvm_unreachable("unexpected placeholder type");
11126 
11127   case Type::Enum:
11128     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11129 
11130   case Type::Pointer:
11131   case Type::ConstantArray:
11132   case Type::VariableArray:
11133   case Type::IncompleteArray:
11134   case Type::FunctionNoProto:
11135   case Type::FunctionProto:
11136     return GCCTypeClass::Pointer;
11137 
11138   case Type::MemberPointer:
11139     return CanTy->isMemberDataPointerType()
11140                ? GCCTypeClass::PointerToDataMember
11141                : GCCTypeClass::PointerToMemberFunction;
11142 
11143   case Type::Complex:
11144     return GCCTypeClass::Complex;
11145 
11146   case Type::Record:
11147     return CanTy->isUnionType() ? GCCTypeClass::Union
11148                                 : GCCTypeClass::ClassOrStruct;
11149 
11150   case Type::Atomic:
11151     // GCC classifies _Atomic T the same as T.
11152     return EvaluateBuiltinClassifyType(
11153         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11154 
11155   case Type::BlockPointer:
11156   case Type::Vector:
11157   case Type::ExtVector:
11158   case Type::ConstantMatrix:
11159   case Type::ObjCObject:
11160   case Type::ObjCInterface:
11161   case Type::ObjCObjectPointer:
11162   case Type::Pipe:
11163   case Type::BitInt:
11164     // GCC classifies vectors as None. We follow its lead and classify all
11165     // other types that don't fit into the regular classification the same way.
11166     return GCCTypeClass::None;
11167 
11168   case Type::LValueReference:
11169   case Type::RValueReference:
11170     llvm_unreachable("invalid type for expression");
11171   }
11172 
11173   llvm_unreachable("unexpected type class");
11174 }
11175 
11176 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11177 /// as GCC.
11178 static GCCTypeClass
11179 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11180   // If no argument was supplied, default to None. This isn't
11181   // ideal, however it is what gcc does.
11182   if (E->getNumArgs() == 0)
11183     return GCCTypeClass::None;
11184 
11185   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11186   // being an ICE, but still folds it to a constant using the type of the first
11187   // argument.
11188   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11189 }
11190 
11191 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11192 /// __builtin_constant_p when applied to the given pointer.
11193 ///
11194 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11195 /// or it points to the first character of a string literal.
11196 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11197   APValue::LValueBase Base = LV.getLValueBase();
11198   if (Base.isNull()) {
11199     // A null base is acceptable.
11200     return true;
11201   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11202     if (!isa<StringLiteral>(E))
11203       return false;
11204     return LV.getLValueOffset().isZero();
11205   } else if (Base.is<TypeInfoLValue>()) {
11206     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11207     // evaluate to true.
11208     return true;
11209   } else {
11210     // Any other base is not constant enough for GCC.
11211     return false;
11212   }
11213 }
11214 
11215 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11216 /// GCC as we can manage.
11217 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11218   // This evaluation is not permitted to have side-effects, so evaluate it in
11219   // a speculative evaluation context.
11220   SpeculativeEvaluationRAII SpeculativeEval(Info);
11221 
11222   // Constant-folding is always enabled for the operand of __builtin_constant_p
11223   // (even when the enclosing evaluation context otherwise requires a strict
11224   // language-specific constant expression).
11225   FoldConstant Fold(Info, true);
11226 
11227   QualType ArgType = Arg->getType();
11228 
11229   // __builtin_constant_p always has one operand. The rules which gcc follows
11230   // are not precisely documented, but are as follows:
11231   //
11232   //  - If the operand is of integral, floating, complex or enumeration type,
11233   //    and can be folded to a known value of that type, it returns 1.
11234   //  - If the operand can be folded to a pointer to the first character
11235   //    of a string literal (or such a pointer cast to an integral type)
11236   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11237   //
11238   // Otherwise, it returns 0.
11239   //
11240   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11241   // its support for this did not work prior to GCC 9 and is not yet well
11242   // understood.
11243   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11244       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11245       ArgType->isNullPtrType()) {
11246     APValue V;
11247     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11248       Fold.keepDiagnostics();
11249       return false;
11250     }
11251 
11252     // For a pointer (possibly cast to integer), there are special rules.
11253     if (V.getKind() == APValue::LValue)
11254       return EvaluateBuiltinConstantPForLValue(V);
11255 
11256     // Otherwise, any constant value is good enough.
11257     return V.hasValue();
11258   }
11259 
11260   // Anything else isn't considered to be sufficiently constant.
11261   return false;
11262 }
11263 
11264 /// Retrieves the "underlying object type" of the given expression,
11265 /// as used by __builtin_object_size.
11266 static QualType getObjectType(APValue::LValueBase B) {
11267   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11268     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11269       return VD->getType();
11270   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11271     if (isa<CompoundLiteralExpr>(E))
11272       return E->getType();
11273   } else if (B.is<TypeInfoLValue>()) {
11274     return B.getTypeInfoType();
11275   } else if (B.is<DynamicAllocLValue>()) {
11276     return B.getDynamicAllocType();
11277   }
11278 
11279   return QualType();
11280 }
11281 
11282 /// A more selective version of E->IgnoreParenCasts for
11283 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11284 /// to change the type of E.
11285 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11286 ///
11287 /// Always returns an RValue with a pointer representation.
11288 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11289   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11290 
11291   auto *NoParens = E->IgnoreParens();
11292   auto *Cast = dyn_cast<CastExpr>(NoParens);
11293   if (Cast == nullptr)
11294     return NoParens;
11295 
11296   // We only conservatively allow a few kinds of casts, because this code is
11297   // inherently a simple solution that seeks to support the common case.
11298   auto CastKind = Cast->getCastKind();
11299   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11300       CastKind != CK_AddressSpaceConversion)
11301     return NoParens;
11302 
11303   auto *SubExpr = Cast->getSubExpr();
11304   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11305     return NoParens;
11306   return ignorePointerCastsAndParens(SubExpr);
11307 }
11308 
11309 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11310 /// record layout. e.g.
11311 ///   struct { struct { int a, b; } fst, snd; } obj;
11312 ///   obj.fst   // no
11313 ///   obj.snd   // yes
11314 ///   obj.fst.a // no
11315 ///   obj.fst.b // no
11316 ///   obj.snd.a // no
11317 ///   obj.snd.b // yes
11318 ///
11319 /// Please note: this function is specialized for how __builtin_object_size
11320 /// views "objects".
11321 ///
11322 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11323 /// correct result, it will always return true.
11324 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11325   assert(!LVal.Designator.Invalid);
11326 
11327   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11328     const RecordDecl *Parent = FD->getParent();
11329     Invalid = Parent->isInvalidDecl();
11330     if (Invalid || Parent->isUnion())
11331       return true;
11332     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11333     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11334   };
11335 
11336   auto &Base = LVal.getLValueBase();
11337   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11338     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11339       bool Invalid;
11340       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11341         return Invalid;
11342     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11343       for (auto *FD : IFD->chain()) {
11344         bool Invalid;
11345         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11346           return Invalid;
11347       }
11348     }
11349   }
11350 
11351   unsigned I = 0;
11352   QualType BaseType = getType(Base);
11353   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11354     // If we don't know the array bound, conservatively assume we're looking at
11355     // the final array element.
11356     ++I;
11357     if (BaseType->isIncompleteArrayType())
11358       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11359     else
11360       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11361   }
11362 
11363   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11364     const auto &Entry = LVal.Designator.Entries[I];
11365     if (BaseType->isArrayType()) {
11366       // Because __builtin_object_size treats arrays as objects, we can ignore
11367       // the index iff this is the last array in the Designator.
11368       if (I + 1 == E)
11369         return true;
11370       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11371       uint64_t Index = Entry.getAsArrayIndex();
11372       if (Index + 1 != CAT->getSize())
11373         return false;
11374       BaseType = CAT->getElementType();
11375     } else if (BaseType->isAnyComplexType()) {
11376       const auto *CT = BaseType->castAs<ComplexType>();
11377       uint64_t Index = Entry.getAsArrayIndex();
11378       if (Index != 1)
11379         return false;
11380       BaseType = CT->getElementType();
11381     } else if (auto *FD = getAsField(Entry)) {
11382       bool Invalid;
11383       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11384         return Invalid;
11385       BaseType = FD->getType();
11386     } else {
11387       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11388       return false;
11389     }
11390   }
11391   return true;
11392 }
11393 
11394 /// Tests to see if the LValue has a user-specified designator (that isn't
11395 /// necessarily valid). Note that this always returns 'true' if the LValue has
11396 /// an unsized array as its first designator entry, because there's currently no
11397 /// way to tell if the user typed *foo or foo[0].
11398 static bool refersToCompleteObject(const LValue &LVal) {
11399   if (LVal.Designator.Invalid)
11400     return false;
11401 
11402   if (!LVal.Designator.Entries.empty())
11403     return LVal.Designator.isMostDerivedAnUnsizedArray();
11404 
11405   if (!LVal.InvalidBase)
11406     return true;
11407 
11408   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11409   // the LValueBase.
11410   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11411   return !E || !isa<MemberExpr>(E);
11412 }
11413 
11414 /// Attempts to detect a user writing into a piece of memory that's impossible
11415 /// to figure out the size of by just using types.
11416 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11417   const SubobjectDesignator &Designator = LVal.Designator;
11418   // Notes:
11419   // - Users can only write off of the end when we have an invalid base. Invalid
11420   //   bases imply we don't know where the memory came from.
11421   // - We used to be a bit more aggressive here; we'd only be conservative if
11422   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11423   //   broke some common standard library extensions (PR30346), but was
11424   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11425   //   with some sort of list. OTOH, it seems that GCC is always
11426   //   conservative with the last element in structs (if it's an array), so our
11427   //   current behavior is more compatible than an explicit list approach would
11428   //   be.
11429   return LVal.InvalidBase &&
11430          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11431          Designator.MostDerivedIsArrayElement &&
11432          isDesignatorAtObjectEnd(Ctx, LVal);
11433 }
11434 
11435 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11436 /// Fails if the conversion would cause loss of precision.
11437 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11438                                             CharUnits &Result) {
11439   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11440   if (Int.ugt(CharUnitsMax))
11441     return false;
11442   Result = CharUnits::fromQuantity(Int.getZExtValue());
11443   return true;
11444 }
11445 
11446 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11447 /// determine how many bytes exist from the beginning of the object to either
11448 /// the end of the current subobject, or the end of the object itself, depending
11449 /// on what the LValue looks like + the value of Type.
11450 ///
11451 /// If this returns false, the value of Result is undefined.
11452 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11453                                unsigned Type, const LValue &LVal,
11454                                CharUnits &EndOffset) {
11455   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11456 
11457   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11458     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11459       return false;
11460     return HandleSizeof(Info, ExprLoc, Ty, Result);
11461   };
11462 
11463   // We want to evaluate the size of the entire object. This is a valid fallback
11464   // for when Type=1 and the designator is invalid, because we're asked for an
11465   // upper-bound.
11466   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11467     // Type=3 wants a lower bound, so we can't fall back to this.
11468     if (Type == 3 && !DetermineForCompleteObject)
11469       return false;
11470 
11471     llvm::APInt APEndOffset;
11472     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11473         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11474       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11475 
11476     if (LVal.InvalidBase)
11477       return false;
11478 
11479     QualType BaseTy = getObjectType(LVal.getLValueBase());
11480     return CheckedHandleSizeof(BaseTy, EndOffset);
11481   }
11482 
11483   // We want to evaluate the size of a subobject.
11484   const SubobjectDesignator &Designator = LVal.Designator;
11485 
11486   // The following is a moderately common idiom in C:
11487   //
11488   // struct Foo { int a; char c[1]; };
11489   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11490   // strcpy(&F->c[0], Bar);
11491   //
11492   // In order to not break too much legacy code, we need to support it.
11493   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11494     // If we can resolve this to an alloc_size call, we can hand that back,
11495     // because we know for certain how many bytes there are to write to.
11496     llvm::APInt APEndOffset;
11497     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11498         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11499       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11500 
11501     // If we cannot determine the size of the initial allocation, then we can't
11502     // given an accurate upper-bound. However, we are still able to give
11503     // conservative lower-bounds for Type=3.
11504     if (Type == 1)
11505       return false;
11506   }
11507 
11508   CharUnits BytesPerElem;
11509   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11510     return false;
11511 
11512   // According to the GCC documentation, we want the size of the subobject
11513   // denoted by the pointer. But that's not quite right -- what we actually
11514   // want is the size of the immediately-enclosing array, if there is one.
11515   int64_t ElemsRemaining;
11516   if (Designator.MostDerivedIsArrayElement &&
11517       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11518     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11519     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11520     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11521   } else {
11522     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11523   }
11524 
11525   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11526   return true;
11527 }
11528 
11529 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11530 /// returns true and stores the result in @p Size.
11531 ///
11532 /// If @p WasError is non-null, this will report whether the failure to evaluate
11533 /// is to be treated as an Error in IntExprEvaluator.
11534 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11535                                          EvalInfo &Info, uint64_t &Size) {
11536   // Determine the denoted object.
11537   LValue LVal;
11538   {
11539     // The operand of __builtin_object_size is never evaluated for side-effects.
11540     // If there are any, but we can determine the pointed-to object anyway, then
11541     // ignore the side-effects.
11542     SpeculativeEvaluationRAII SpeculativeEval(Info);
11543     IgnoreSideEffectsRAII Fold(Info);
11544 
11545     if (E->isGLValue()) {
11546       // It's possible for us to be given GLValues if we're called via
11547       // Expr::tryEvaluateObjectSize.
11548       APValue RVal;
11549       if (!EvaluateAsRValue(Info, E, RVal))
11550         return false;
11551       LVal.setFrom(Info.Ctx, RVal);
11552     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11553                                 /*InvalidBaseOK=*/true))
11554       return false;
11555   }
11556 
11557   // If we point to before the start of the object, there are no accessible
11558   // bytes.
11559   if (LVal.getLValueOffset().isNegative()) {
11560     Size = 0;
11561     return true;
11562   }
11563 
11564   CharUnits EndOffset;
11565   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11566     return false;
11567 
11568   // If we've fallen outside of the end offset, just pretend there's nothing to
11569   // write to/read from.
11570   if (EndOffset <= LVal.getLValueOffset())
11571     Size = 0;
11572   else
11573     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11574   return true;
11575 }
11576 
11577 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11578   if (unsigned BuiltinOp = E->getBuiltinCallee())
11579     return VisitBuiltinCallExpr(E, BuiltinOp);
11580 
11581   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11582 }
11583 
11584 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11585                                      APValue &Val, APSInt &Alignment) {
11586   QualType SrcTy = E->getArg(0)->getType();
11587   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11588     return false;
11589   // Even though we are evaluating integer expressions we could get a pointer
11590   // argument for the __builtin_is_aligned() case.
11591   if (SrcTy->isPointerType()) {
11592     LValue Ptr;
11593     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11594       return false;
11595     Ptr.moveInto(Val);
11596   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11597     Info.FFDiag(E->getArg(0));
11598     return false;
11599   } else {
11600     APSInt SrcInt;
11601     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11602       return false;
11603     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11604            "Bit widths must be the same");
11605     Val = APValue(SrcInt);
11606   }
11607   assert(Val.hasValue());
11608   return true;
11609 }
11610 
11611 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11612                                             unsigned BuiltinOp) {
11613   switch (BuiltinOp) {
11614   default:
11615     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11616 
11617   case Builtin::BI__builtin_dynamic_object_size:
11618   case Builtin::BI__builtin_object_size: {
11619     // The type was checked when we built the expression.
11620     unsigned Type =
11621         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11622     assert(Type <= 3 && "unexpected type");
11623 
11624     uint64_t Size;
11625     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11626       return Success(Size, E);
11627 
11628     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11629       return Success((Type & 2) ? 0 : -1, E);
11630 
11631     // Expression had no side effects, but we couldn't statically determine the
11632     // size of the referenced object.
11633     switch (Info.EvalMode) {
11634     case EvalInfo::EM_ConstantExpression:
11635     case EvalInfo::EM_ConstantFold:
11636     case EvalInfo::EM_IgnoreSideEffects:
11637       // Leave it to IR generation.
11638       return Error(E);
11639     case EvalInfo::EM_ConstantExpressionUnevaluated:
11640       // Reduce it to a constant now.
11641       return Success((Type & 2) ? 0 : -1, E);
11642     }
11643 
11644     llvm_unreachable("unexpected EvalMode");
11645   }
11646 
11647   case Builtin::BI__builtin_os_log_format_buffer_size: {
11648     analyze_os_log::OSLogBufferLayout Layout;
11649     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11650     return Success(Layout.size().getQuantity(), E);
11651   }
11652 
11653   case Builtin::BI__builtin_is_aligned: {
11654     APValue Src;
11655     APSInt Alignment;
11656     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11657       return false;
11658     if (Src.isLValue()) {
11659       // If we evaluated a pointer, check the minimum known alignment.
11660       LValue Ptr;
11661       Ptr.setFrom(Info.Ctx, Src);
11662       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11663       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11664       // We can return true if the known alignment at the computed offset is
11665       // greater than the requested alignment.
11666       assert(PtrAlign.isPowerOfTwo());
11667       assert(Alignment.isPowerOf2());
11668       if (PtrAlign.getQuantity() >= Alignment)
11669         return Success(1, E);
11670       // If the alignment is not known to be sufficient, some cases could still
11671       // be aligned at run time. However, if the requested alignment is less or
11672       // equal to the base alignment and the offset is not aligned, we know that
11673       // the run-time value can never be aligned.
11674       if (BaseAlignment.getQuantity() >= Alignment &&
11675           PtrAlign.getQuantity() < Alignment)
11676         return Success(0, E);
11677       // Otherwise we can't infer whether the value is sufficiently aligned.
11678       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11679       //  in cases where we can't fully evaluate the pointer.
11680       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11681           << Alignment;
11682       return false;
11683     }
11684     assert(Src.isInt());
11685     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11686   }
11687   case Builtin::BI__builtin_align_up: {
11688     APValue Src;
11689     APSInt Alignment;
11690     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11691       return false;
11692     if (!Src.isInt())
11693       return Error(E);
11694     APSInt AlignedVal =
11695         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11696                Src.getInt().isUnsigned());
11697     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11698     return Success(AlignedVal, E);
11699   }
11700   case Builtin::BI__builtin_align_down: {
11701     APValue Src;
11702     APSInt Alignment;
11703     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11704       return false;
11705     if (!Src.isInt())
11706       return Error(E);
11707     APSInt AlignedVal =
11708         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11709     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11710     return Success(AlignedVal, E);
11711   }
11712 
11713   case Builtin::BI__builtin_bitreverse8:
11714   case Builtin::BI__builtin_bitreverse16:
11715   case Builtin::BI__builtin_bitreverse32:
11716   case Builtin::BI__builtin_bitreverse64: {
11717     APSInt Val;
11718     if (!EvaluateInteger(E->getArg(0), Val, Info))
11719       return false;
11720 
11721     return Success(Val.reverseBits(), E);
11722   }
11723 
11724   case Builtin::BI__builtin_bswap16:
11725   case Builtin::BI__builtin_bswap32:
11726   case Builtin::BI__builtin_bswap64: {
11727     APSInt Val;
11728     if (!EvaluateInteger(E->getArg(0), Val, Info))
11729       return false;
11730 
11731     return Success(Val.byteSwap(), E);
11732   }
11733 
11734   case Builtin::BI__builtin_classify_type:
11735     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11736 
11737   case Builtin::BI__builtin_clrsb:
11738   case Builtin::BI__builtin_clrsbl:
11739   case Builtin::BI__builtin_clrsbll: {
11740     APSInt Val;
11741     if (!EvaluateInteger(E->getArg(0), Val, Info))
11742       return false;
11743 
11744     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11745   }
11746 
11747   case Builtin::BI__builtin_clz:
11748   case Builtin::BI__builtin_clzl:
11749   case Builtin::BI__builtin_clzll:
11750   case Builtin::BI__builtin_clzs: {
11751     APSInt Val;
11752     if (!EvaluateInteger(E->getArg(0), Val, Info))
11753       return false;
11754     if (!Val)
11755       return Error(E);
11756 
11757     return Success(Val.countLeadingZeros(), E);
11758   }
11759 
11760   case Builtin::BI__builtin_constant_p: {
11761     const Expr *Arg = E->getArg(0);
11762     if (EvaluateBuiltinConstantP(Info, Arg))
11763       return Success(true, E);
11764     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11765       // Outside a constant context, eagerly evaluate to false in the presence
11766       // of side-effects in order to avoid -Wunsequenced false-positives in
11767       // a branch on __builtin_constant_p(expr).
11768       return Success(false, E);
11769     }
11770     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11771     return false;
11772   }
11773 
11774   case Builtin::BI__builtin_is_constant_evaluated: {
11775     const auto *Callee = Info.CurrentCall->getCallee();
11776     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11777         (Info.CallStackDepth == 1 ||
11778          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11779           Callee->getIdentifier() &&
11780           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11781       // FIXME: Find a better way to avoid duplicated diagnostics.
11782       if (Info.EvalStatus.Diag)
11783         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11784                                                : Info.CurrentCall->CallLoc,
11785                     diag::warn_is_constant_evaluated_always_true_constexpr)
11786             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11787                                          : "std::is_constant_evaluated");
11788     }
11789 
11790     return Success(Info.InConstantContext, E);
11791   }
11792 
11793   case Builtin::BI__builtin_ctz:
11794   case Builtin::BI__builtin_ctzl:
11795   case Builtin::BI__builtin_ctzll:
11796   case Builtin::BI__builtin_ctzs: {
11797     APSInt Val;
11798     if (!EvaluateInteger(E->getArg(0), Val, Info))
11799       return false;
11800     if (!Val)
11801       return Error(E);
11802 
11803     return Success(Val.countTrailingZeros(), E);
11804   }
11805 
11806   case Builtin::BI__builtin_eh_return_data_regno: {
11807     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11808     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11809     return Success(Operand, E);
11810   }
11811 
11812   case Builtin::BI__builtin_expect:
11813   case Builtin::BI__builtin_expect_with_probability:
11814     return Visit(E->getArg(0));
11815 
11816   case Builtin::BI__builtin_ffs:
11817   case Builtin::BI__builtin_ffsl:
11818   case Builtin::BI__builtin_ffsll: {
11819     APSInt Val;
11820     if (!EvaluateInteger(E->getArg(0), Val, Info))
11821       return false;
11822 
11823     unsigned N = Val.countTrailingZeros();
11824     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11825   }
11826 
11827   case Builtin::BI__builtin_fpclassify: {
11828     APFloat Val(0.0);
11829     if (!EvaluateFloat(E->getArg(5), Val, Info))
11830       return false;
11831     unsigned Arg;
11832     switch (Val.getCategory()) {
11833     case APFloat::fcNaN: Arg = 0; break;
11834     case APFloat::fcInfinity: Arg = 1; break;
11835     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11836     case APFloat::fcZero: Arg = 4; break;
11837     }
11838     return Visit(E->getArg(Arg));
11839   }
11840 
11841   case Builtin::BI__builtin_isinf_sign: {
11842     APFloat Val(0.0);
11843     return EvaluateFloat(E->getArg(0), Val, Info) &&
11844            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11845   }
11846 
11847   case Builtin::BI__builtin_isinf: {
11848     APFloat Val(0.0);
11849     return EvaluateFloat(E->getArg(0), Val, Info) &&
11850            Success(Val.isInfinity() ? 1 : 0, E);
11851   }
11852 
11853   case Builtin::BI__builtin_isfinite: {
11854     APFloat Val(0.0);
11855     return EvaluateFloat(E->getArg(0), Val, Info) &&
11856            Success(Val.isFinite() ? 1 : 0, E);
11857   }
11858 
11859   case Builtin::BI__builtin_isnan: {
11860     APFloat Val(0.0);
11861     return EvaluateFloat(E->getArg(0), Val, Info) &&
11862            Success(Val.isNaN() ? 1 : 0, E);
11863   }
11864 
11865   case Builtin::BI__builtin_isnormal: {
11866     APFloat Val(0.0);
11867     return EvaluateFloat(E->getArg(0), Val, Info) &&
11868            Success(Val.isNormal() ? 1 : 0, E);
11869   }
11870 
11871   case Builtin::BI__builtin_parity:
11872   case Builtin::BI__builtin_parityl:
11873   case Builtin::BI__builtin_parityll: {
11874     APSInt Val;
11875     if (!EvaluateInteger(E->getArg(0), Val, Info))
11876       return false;
11877 
11878     return Success(Val.countPopulation() % 2, E);
11879   }
11880 
11881   case Builtin::BI__builtin_popcount:
11882   case Builtin::BI__builtin_popcountl:
11883   case Builtin::BI__builtin_popcountll: {
11884     APSInt Val;
11885     if (!EvaluateInteger(E->getArg(0), Val, Info))
11886       return false;
11887 
11888     return Success(Val.countPopulation(), E);
11889   }
11890 
11891   case Builtin::BI__builtin_rotateleft8:
11892   case Builtin::BI__builtin_rotateleft16:
11893   case Builtin::BI__builtin_rotateleft32:
11894   case Builtin::BI__builtin_rotateleft64:
11895   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11896   case Builtin::BI_rotl16:
11897   case Builtin::BI_rotl:
11898   case Builtin::BI_lrotl:
11899   case Builtin::BI_rotl64: {
11900     APSInt Val, Amt;
11901     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11902         !EvaluateInteger(E->getArg(1), Amt, Info))
11903       return false;
11904 
11905     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11906   }
11907 
11908   case Builtin::BI__builtin_rotateright8:
11909   case Builtin::BI__builtin_rotateright16:
11910   case Builtin::BI__builtin_rotateright32:
11911   case Builtin::BI__builtin_rotateright64:
11912   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11913   case Builtin::BI_rotr16:
11914   case Builtin::BI_rotr:
11915   case Builtin::BI_lrotr:
11916   case Builtin::BI_rotr64: {
11917     APSInt Val, Amt;
11918     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11919         !EvaluateInteger(E->getArg(1), Amt, Info))
11920       return false;
11921 
11922     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11923   }
11924 
11925   case Builtin::BIstrlen:
11926   case Builtin::BIwcslen:
11927     // A call to strlen is not a constant expression.
11928     if (Info.getLangOpts().CPlusPlus11)
11929       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11930         << /*isConstexpr*/0 << /*isConstructor*/0
11931         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11932     else
11933       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11934     LLVM_FALLTHROUGH;
11935   case Builtin::BI__builtin_strlen:
11936   case Builtin::BI__builtin_wcslen: {
11937     // As an extension, we support __builtin_strlen() as a constant expression,
11938     // and support folding strlen() to a constant.
11939     uint64_t StrLen;
11940     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
11941       return Success(StrLen, E);
11942     return false;
11943   }
11944 
11945   case Builtin::BIstrcmp:
11946   case Builtin::BIwcscmp:
11947   case Builtin::BIstrncmp:
11948   case Builtin::BIwcsncmp:
11949   case Builtin::BImemcmp:
11950   case Builtin::BIbcmp:
11951   case Builtin::BIwmemcmp:
11952     // A call to strlen is not a constant expression.
11953     if (Info.getLangOpts().CPlusPlus11)
11954       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11955         << /*isConstexpr*/0 << /*isConstructor*/0
11956         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11957     else
11958       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11959     LLVM_FALLTHROUGH;
11960   case Builtin::BI__builtin_strcmp:
11961   case Builtin::BI__builtin_wcscmp:
11962   case Builtin::BI__builtin_strncmp:
11963   case Builtin::BI__builtin_wcsncmp:
11964   case Builtin::BI__builtin_memcmp:
11965   case Builtin::BI__builtin_bcmp:
11966   case Builtin::BI__builtin_wmemcmp: {
11967     LValue String1, String2;
11968     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11969         !EvaluatePointer(E->getArg(1), String2, Info))
11970       return false;
11971 
11972     uint64_t MaxLength = uint64_t(-1);
11973     if (BuiltinOp != Builtin::BIstrcmp &&
11974         BuiltinOp != Builtin::BIwcscmp &&
11975         BuiltinOp != Builtin::BI__builtin_strcmp &&
11976         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11977       APSInt N;
11978       if (!EvaluateInteger(E->getArg(2), N, Info))
11979         return false;
11980       MaxLength = N.getExtValue();
11981     }
11982 
11983     // Empty substrings compare equal by definition.
11984     if (MaxLength == 0u)
11985       return Success(0, E);
11986 
11987     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11988         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11989         String1.Designator.Invalid || String2.Designator.Invalid)
11990       return false;
11991 
11992     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11993     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11994 
11995     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11996                      BuiltinOp == Builtin::BIbcmp ||
11997                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11998                      BuiltinOp == Builtin::BI__builtin_bcmp;
11999 
12000     assert(IsRawByte ||
12001            (Info.Ctx.hasSameUnqualifiedType(
12002                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12003             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12004 
12005     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12006     // 'char8_t', but no other types.
12007     if (IsRawByte &&
12008         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12009       // FIXME: Consider using our bit_cast implementation to support this.
12010       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12011           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
12012           << CharTy1 << CharTy2;
12013       return false;
12014     }
12015 
12016     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12017       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12018              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12019              Char1.isInt() && Char2.isInt();
12020     };
12021     const auto &AdvanceElems = [&] {
12022       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12023              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12024     };
12025 
12026     bool StopAtNull =
12027         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12028          BuiltinOp != Builtin::BIwmemcmp &&
12029          BuiltinOp != Builtin::BI__builtin_memcmp &&
12030          BuiltinOp != Builtin::BI__builtin_bcmp &&
12031          BuiltinOp != Builtin::BI__builtin_wmemcmp);
12032     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12033                   BuiltinOp == Builtin::BIwcsncmp ||
12034                   BuiltinOp == Builtin::BIwmemcmp ||
12035                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
12036                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12037                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
12038 
12039     for (; MaxLength; --MaxLength) {
12040       APValue Char1, Char2;
12041       if (!ReadCurElems(Char1, Char2))
12042         return false;
12043       if (Char1.getInt().ne(Char2.getInt())) {
12044         if (IsWide) // wmemcmp compares with wchar_t signedness.
12045           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12046         // memcmp always compares unsigned chars.
12047         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12048       }
12049       if (StopAtNull && !Char1.getInt())
12050         return Success(0, E);
12051       assert(!(StopAtNull && !Char2.getInt()));
12052       if (!AdvanceElems())
12053         return false;
12054     }
12055     // We hit the strncmp / memcmp limit.
12056     return Success(0, E);
12057   }
12058 
12059   case Builtin::BI__atomic_always_lock_free:
12060   case Builtin::BI__atomic_is_lock_free:
12061   case Builtin::BI__c11_atomic_is_lock_free: {
12062     APSInt SizeVal;
12063     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12064       return false;
12065 
12066     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12067     // of two less than or equal to the maximum inline atomic width, we know it
12068     // is lock-free.  If the size isn't a power of two, or greater than the
12069     // maximum alignment where we promote atomics, we know it is not lock-free
12070     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12071     // the answer can only be determined at runtime; for example, 16-byte
12072     // atomics have lock-free implementations on some, but not all,
12073     // x86-64 processors.
12074 
12075     // Check power-of-two.
12076     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12077     if (Size.isPowerOfTwo()) {
12078       // Check against inlining width.
12079       unsigned InlineWidthBits =
12080           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12081       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12082         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12083             Size == CharUnits::One() ||
12084             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12085                                                 Expr::NPC_NeverValueDependent))
12086           // OK, we will inline appropriately-aligned operations of this size,
12087           // and _Atomic(T) is appropriately-aligned.
12088           return Success(1, E);
12089 
12090         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12091           castAs<PointerType>()->getPointeeType();
12092         if (!PointeeType->isIncompleteType() &&
12093             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12094           // OK, we will inline operations on this object.
12095           return Success(1, E);
12096         }
12097       }
12098     }
12099 
12100     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12101         Success(0, E) : Error(E);
12102   }
12103   case Builtin::BI__builtin_add_overflow:
12104   case Builtin::BI__builtin_sub_overflow:
12105   case Builtin::BI__builtin_mul_overflow:
12106   case Builtin::BI__builtin_sadd_overflow:
12107   case Builtin::BI__builtin_uadd_overflow:
12108   case Builtin::BI__builtin_uaddl_overflow:
12109   case Builtin::BI__builtin_uaddll_overflow:
12110   case Builtin::BI__builtin_usub_overflow:
12111   case Builtin::BI__builtin_usubl_overflow:
12112   case Builtin::BI__builtin_usubll_overflow:
12113   case Builtin::BI__builtin_umul_overflow:
12114   case Builtin::BI__builtin_umull_overflow:
12115   case Builtin::BI__builtin_umulll_overflow:
12116   case Builtin::BI__builtin_saddl_overflow:
12117   case Builtin::BI__builtin_saddll_overflow:
12118   case Builtin::BI__builtin_ssub_overflow:
12119   case Builtin::BI__builtin_ssubl_overflow:
12120   case Builtin::BI__builtin_ssubll_overflow:
12121   case Builtin::BI__builtin_smul_overflow:
12122   case Builtin::BI__builtin_smull_overflow:
12123   case Builtin::BI__builtin_smulll_overflow: {
12124     LValue ResultLValue;
12125     APSInt LHS, RHS;
12126 
12127     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12128     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12129         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12130         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12131       return false;
12132 
12133     APSInt Result;
12134     bool DidOverflow = false;
12135 
12136     // If the types don't have to match, enlarge all 3 to the largest of them.
12137     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12138         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12139         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12140       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12141                       ResultType->isSignedIntegerOrEnumerationType();
12142       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12143                       ResultType->isSignedIntegerOrEnumerationType();
12144       uint64_t LHSSize = LHS.getBitWidth();
12145       uint64_t RHSSize = RHS.getBitWidth();
12146       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12147       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12148 
12149       // Add an additional bit if the signedness isn't uniformly agreed to. We
12150       // could do this ONLY if there is a signed and an unsigned that both have
12151       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12152       // caught in the shrink-to-result later anyway.
12153       if (IsSigned && !AllSigned)
12154         ++MaxBits;
12155 
12156       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12157       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12158       Result = APSInt(MaxBits, !IsSigned);
12159     }
12160 
12161     // Find largest int.
12162     switch (BuiltinOp) {
12163     default:
12164       llvm_unreachable("Invalid value for BuiltinOp");
12165     case Builtin::BI__builtin_add_overflow:
12166     case Builtin::BI__builtin_sadd_overflow:
12167     case Builtin::BI__builtin_saddl_overflow:
12168     case Builtin::BI__builtin_saddll_overflow:
12169     case Builtin::BI__builtin_uadd_overflow:
12170     case Builtin::BI__builtin_uaddl_overflow:
12171     case Builtin::BI__builtin_uaddll_overflow:
12172       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12173                               : LHS.uadd_ov(RHS, DidOverflow);
12174       break;
12175     case Builtin::BI__builtin_sub_overflow:
12176     case Builtin::BI__builtin_ssub_overflow:
12177     case Builtin::BI__builtin_ssubl_overflow:
12178     case Builtin::BI__builtin_ssubll_overflow:
12179     case Builtin::BI__builtin_usub_overflow:
12180     case Builtin::BI__builtin_usubl_overflow:
12181     case Builtin::BI__builtin_usubll_overflow:
12182       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12183                               : LHS.usub_ov(RHS, DidOverflow);
12184       break;
12185     case Builtin::BI__builtin_mul_overflow:
12186     case Builtin::BI__builtin_smul_overflow:
12187     case Builtin::BI__builtin_smull_overflow:
12188     case Builtin::BI__builtin_smulll_overflow:
12189     case Builtin::BI__builtin_umul_overflow:
12190     case Builtin::BI__builtin_umull_overflow:
12191     case Builtin::BI__builtin_umulll_overflow:
12192       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12193                               : LHS.umul_ov(RHS, DidOverflow);
12194       break;
12195     }
12196 
12197     // In the case where multiple sizes are allowed, truncate and see if
12198     // the values are the same.
12199     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12200         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12201         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12202       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12203       // since it will give us the behavior of a TruncOrSelf in the case where
12204       // its parameter <= its size.  We previously set Result to be at least the
12205       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12206       // will work exactly like TruncOrSelf.
12207       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12208       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12209 
12210       if (!APSInt::isSameValue(Temp, Result))
12211         DidOverflow = true;
12212       Result = Temp;
12213     }
12214 
12215     APValue APV{Result};
12216     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12217       return false;
12218     return Success(DidOverflow, E);
12219   }
12220   }
12221 }
12222 
12223 /// Determine whether this is a pointer past the end of the complete
12224 /// object referred to by the lvalue.
12225 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12226                                             const LValue &LV) {
12227   // A null pointer can be viewed as being "past the end" but we don't
12228   // choose to look at it that way here.
12229   if (!LV.getLValueBase())
12230     return false;
12231 
12232   // If the designator is valid and refers to a subobject, we're not pointing
12233   // past the end.
12234   if (!LV.getLValueDesignator().Invalid &&
12235       !LV.getLValueDesignator().isOnePastTheEnd())
12236     return false;
12237 
12238   // A pointer to an incomplete type might be past-the-end if the type's size is
12239   // zero.  We cannot tell because the type is incomplete.
12240   QualType Ty = getType(LV.getLValueBase());
12241   if (Ty->isIncompleteType())
12242     return true;
12243 
12244   // We're a past-the-end pointer if we point to the byte after the object,
12245   // no matter what our type or path is.
12246   auto Size = Ctx.getTypeSizeInChars(Ty);
12247   return LV.getLValueOffset() == Size;
12248 }
12249 
12250 namespace {
12251 
12252 /// Data recursive integer evaluator of certain binary operators.
12253 ///
12254 /// We use a data recursive algorithm for binary operators so that we are able
12255 /// to handle extreme cases of chained binary operators without causing stack
12256 /// overflow.
12257 class DataRecursiveIntBinOpEvaluator {
12258   struct EvalResult {
12259     APValue Val;
12260     bool Failed;
12261 
12262     EvalResult() : Failed(false) { }
12263 
12264     void swap(EvalResult &RHS) {
12265       Val.swap(RHS.Val);
12266       Failed = RHS.Failed;
12267       RHS.Failed = false;
12268     }
12269   };
12270 
12271   struct Job {
12272     const Expr *E;
12273     EvalResult LHSResult; // meaningful only for binary operator expression.
12274     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12275 
12276     Job() = default;
12277     Job(Job &&) = default;
12278 
12279     void startSpeculativeEval(EvalInfo &Info) {
12280       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12281     }
12282 
12283   private:
12284     SpeculativeEvaluationRAII SpecEvalRAII;
12285   };
12286 
12287   SmallVector<Job, 16> Queue;
12288 
12289   IntExprEvaluator &IntEval;
12290   EvalInfo &Info;
12291   APValue &FinalResult;
12292 
12293 public:
12294   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12295     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12296 
12297   /// True if \param E is a binary operator that we are going to handle
12298   /// data recursively.
12299   /// We handle binary operators that are comma, logical, or that have operands
12300   /// with integral or enumeration type.
12301   static bool shouldEnqueue(const BinaryOperator *E) {
12302     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12303            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12304             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12305             E->getRHS()->getType()->isIntegralOrEnumerationType());
12306   }
12307 
12308   bool Traverse(const BinaryOperator *E) {
12309     enqueue(E);
12310     EvalResult PrevResult;
12311     while (!Queue.empty())
12312       process(PrevResult);
12313 
12314     if (PrevResult.Failed) return false;
12315 
12316     FinalResult.swap(PrevResult.Val);
12317     return true;
12318   }
12319 
12320 private:
12321   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12322     return IntEval.Success(Value, E, Result);
12323   }
12324   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12325     return IntEval.Success(Value, E, Result);
12326   }
12327   bool Error(const Expr *E) {
12328     return IntEval.Error(E);
12329   }
12330   bool Error(const Expr *E, diag::kind D) {
12331     return IntEval.Error(E, D);
12332   }
12333 
12334   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12335     return Info.CCEDiag(E, D);
12336   }
12337 
12338   // Returns true if visiting the RHS is necessary, false otherwise.
12339   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12340                          bool &SuppressRHSDiags);
12341 
12342   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12343                   const BinaryOperator *E, APValue &Result);
12344 
12345   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12346     Result.Failed = !Evaluate(Result.Val, Info, E);
12347     if (Result.Failed)
12348       Result.Val = APValue();
12349   }
12350 
12351   void process(EvalResult &Result);
12352 
12353   void enqueue(const Expr *E) {
12354     E = E->IgnoreParens();
12355     Queue.resize(Queue.size()+1);
12356     Queue.back().E = E;
12357     Queue.back().Kind = Job::AnyExprKind;
12358   }
12359 };
12360 
12361 }
12362 
12363 bool DataRecursiveIntBinOpEvaluator::
12364        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12365                          bool &SuppressRHSDiags) {
12366   if (E->getOpcode() == BO_Comma) {
12367     // Ignore LHS but note if we could not evaluate it.
12368     if (LHSResult.Failed)
12369       return Info.noteSideEffect();
12370     return true;
12371   }
12372 
12373   if (E->isLogicalOp()) {
12374     bool LHSAsBool;
12375     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12376       // We were able to evaluate the LHS, see if we can get away with not
12377       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12378       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12379         Success(LHSAsBool, E, LHSResult.Val);
12380         return false; // Ignore RHS
12381       }
12382     } else {
12383       LHSResult.Failed = true;
12384 
12385       // Since we weren't able to evaluate the left hand side, it
12386       // might have had side effects.
12387       if (!Info.noteSideEffect())
12388         return false;
12389 
12390       // We can't evaluate the LHS; however, sometimes the result
12391       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12392       // Don't ignore RHS and suppress diagnostics from this arm.
12393       SuppressRHSDiags = true;
12394     }
12395 
12396     return true;
12397   }
12398 
12399   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12400          E->getRHS()->getType()->isIntegralOrEnumerationType());
12401 
12402   if (LHSResult.Failed && !Info.noteFailure())
12403     return false; // Ignore RHS;
12404 
12405   return true;
12406 }
12407 
12408 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12409                                     bool IsSub) {
12410   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12411   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12412   // offsets.
12413   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12414   CharUnits &Offset = LVal.getLValueOffset();
12415   uint64_t Offset64 = Offset.getQuantity();
12416   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12417   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12418                                          : Offset64 + Index64);
12419 }
12420 
12421 bool DataRecursiveIntBinOpEvaluator::
12422        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12423                   const BinaryOperator *E, APValue &Result) {
12424   if (E->getOpcode() == BO_Comma) {
12425     if (RHSResult.Failed)
12426       return false;
12427     Result = RHSResult.Val;
12428     return true;
12429   }
12430 
12431   if (E->isLogicalOp()) {
12432     bool lhsResult, rhsResult;
12433     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12434     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12435 
12436     if (LHSIsOK) {
12437       if (RHSIsOK) {
12438         if (E->getOpcode() == BO_LOr)
12439           return Success(lhsResult || rhsResult, E, Result);
12440         else
12441           return Success(lhsResult && rhsResult, E, Result);
12442       }
12443     } else {
12444       if (RHSIsOK) {
12445         // We can't evaluate the LHS; however, sometimes the result
12446         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12447         if (rhsResult == (E->getOpcode() == BO_LOr))
12448           return Success(rhsResult, E, Result);
12449       }
12450     }
12451 
12452     return false;
12453   }
12454 
12455   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12456          E->getRHS()->getType()->isIntegralOrEnumerationType());
12457 
12458   if (LHSResult.Failed || RHSResult.Failed)
12459     return false;
12460 
12461   const APValue &LHSVal = LHSResult.Val;
12462   const APValue &RHSVal = RHSResult.Val;
12463 
12464   // Handle cases like (unsigned long)&a + 4.
12465   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12466     Result = LHSVal;
12467     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12468     return true;
12469   }
12470 
12471   // Handle cases like 4 + (unsigned long)&a
12472   if (E->getOpcode() == BO_Add &&
12473       RHSVal.isLValue() && LHSVal.isInt()) {
12474     Result = RHSVal;
12475     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12476     return true;
12477   }
12478 
12479   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12480     // Handle (intptr_t)&&A - (intptr_t)&&B.
12481     if (!LHSVal.getLValueOffset().isZero() ||
12482         !RHSVal.getLValueOffset().isZero())
12483       return false;
12484     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12485     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12486     if (!LHSExpr || !RHSExpr)
12487       return false;
12488     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12489     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12490     if (!LHSAddrExpr || !RHSAddrExpr)
12491       return false;
12492     // Make sure both labels come from the same function.
12493     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12494         RHSAddrExpr->getLabel()->getDeclContext())
12495       return false;
12496     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12497     return true;
12498   }
12499 
12500   // All the remaining cases expect both operands to be an integer
12501   if (!LHSVal.isInt() || !RHSVal.isInt())
12502     return Error(E);
12503 
12504   // Set up the width and signedness manually, in case it can't be deduced
12505   // from the operation we're performing.
12506   // FIXME: Don't do this in the cases where we can deduce it.
12507   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12508                E->getType()->isUnsignedIntegerOrEnumerationType());
12509   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12510                          RHSVal.getInt(), Value))
12511     return false;
12512   return Success(Value, E, Result);
12513 }
12514 
12515 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12516   Job &job = Queue.back();
12517 
12518   switch (job.Kind) {
12519     case Job::AnyExprKind: {
12520       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12521         if (shouldEnqueue(Bop)) {
12522           job.Kind = Job::BinOpKind;
12523           enqueue(Bop->getLHS());
12524           return;
12525         }
12526       }
12527 
12528       EvaluateExpr(job.E, Result);
12529       Queue.pop_back();
12530       return;
12531     }
12532 
12533     case Job::BinOpKind: {
12534       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12535       bool SuppressRHSDiags = false;
12536       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12537         Queue.pop_back();
12538         return;
12539       }
12540       if (SuppressRHSDiags)
12541         job.startSpeculativeEval(Info);
12542       job.LHSResult.swap(Result);
12543       job.Kind = Job::BinOpVisitedLHSKind;
12544       enqueue(Bop->getRHS());
12545       return;
12546     }
12547 
12548     case Job::BinOpVisitedLHSKind: {
12549       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12550       EvalResult RHS;
12551       RHS.swap(Result);
12552       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12553       Queue.pop_back();
12554       return;
12555     }
12556   }
12557 
12558   llvm_unreachable("Invalid Job::Kind!");
12559 }
12560 
12561 namespace {
12562 enum class CmpResult {
12563   Unequal,
12564   Less,
12565   Equal,
12566   Greater,
12567   Unordered,
12568 };
12569 }
12570 
12571 template <class SuccessCB, class AfterCB>
12572 static bool
12573 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12574                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12575   assert(!E->isValueDependent());
12576   assert(E->isComparisonOp() && "expected comparison operator");
12577   assert((E->getOpcode() == BO_Cmp ||
12578           E->getType()->isIntegralOrEnumerationType()) &&
12579          "unsupported binary expression evaluation");
12580   auto Error = [&](const Expr *E) {
12581     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12582     return false;
12583   };
12584 
12585   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12586   bool IsEquality = E->isEqualityOp();
12587 
12588   QualType LHSTy = E->getLHS()->getType();
12589   QualType RHSTy = E->getRHS()->getType();
12590 
12591   if (LHSTy->isIntegralOrEnumerationType() &&
12592       RHSTy->isIntegralOrEnumerationType()) {
12593     APSInt LHS, RHS;
12594     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12595     if (!LHSOK && !Info.noteFailure())
12596       return false;
12597     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12598       return false;
12599     if (LHS < RHS)
12600       return Success(CmpResult::Less, E);
12601     if (LHS > RHS)
12602       return Success(CmpResult::Greater, E);
12603     return Success(CmpResult::Equal, E);
12604   }
12605 
12606   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12607     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12608     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12609 
12610     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12611     if (!LHSOK && !Info.noteFailure())
12612       return false;
12613     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12614       return false;
12615     if (LHSFX < RHSFX)
12616       return Success(CmpResult::Less, E);
12617     if (LHSFX > RHSFX)
12618       return Success(CmpResult::Greater, E);
12619     return Success(CmpResult::Equal, E);
12620   }
12621 
12622   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12623     ComplexValue LHS, RHS;
12624     bool LHSOK;
12625     if (E->isAssignmentOp()) {
12626       LValue LV;
12627       EvaluateLValue(E->getLHS(), LV, Info);
12628       LHSOK = false;
12629     } else if (LHSTy->isRealFloatingType()) {
12630       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12631       if (LHSOK) {
12632         LHS.makeComplexFloat();
12633         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12634       }
12635     } else {
12636       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12637     }
12638     if (!LHSOK && !Info.noteFailure())
12639       return false;
12640 
12641     if (E->getRHS()->getType()->isRealFloatingType()) {
12642       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12643         return false;
12644       RHS.makeComplexFloat();
12645       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12646     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12647       return false;
12648 
12649     if (LHS.isComplexFloat()) {
12650       APFloat::cmpResult CR_r =
12651         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12652       APFloat::cmpResult CR_i =
12653         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12654       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12655       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12656     } else {
12657       assert(IsEquality && "invalid complex comparison");
12658       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12659                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12660       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12661     }
12662   }
12663 
12664   if (LHSTy->isRealFloatingType() &&
12665       RHSTy->isRealFloatingType()) {
12666     APFloat RHS(0.0), LHS(0.0);
12667 
12668     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12669     if (!LHSOK && !Info.noteFailure())
12670       return false;
12671 
12672     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12673       return false;
12674 
12675     assert(E->isComparisonOp() && "Invalid binary operator!");
12676     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12677     if (!Info.InConstantContext &&
12678         APFloatCmpResult == APFloat::cmpUnordered &&
12679         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12680       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12681       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12682       return false;
12683     }
12684     auto GetCmpRes = [&]() {
12685       switch (APFloatCmpResult) {
12686       case APFloat::cmpEqual:
12687         return CmpResult::Equal;
12688       case APFloat::cmpLessThan:
12689         return CmpResult::Less;
12690       case APFloat::cmpGreaterThan:
12691         return CmpResult::Greater;
12692       case APFloat::cmpUnordered:
12693         return CmpResult::Unordered;
12694       }
12695       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12696     };
12697     return Success(GetCmpRes(), E);
12698   }
12699 
12700   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12701     LValue LHSValue, RHSValue;
12702 
12703     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12704     if (!LHSOK && !Info.noteFailure())
12705       return false;
12706 
12707     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12708       return false;
12709 
12710     // Reject differing bases from the normal codepath; we special-case
12711     // comparisons to null.
12712     if (!HasSameBase(LHSValue, RHSValue)) {
12713       // Inequalities and subtractions between unrelated pointers have
12714       // unspecified or undefined behavior.
12715       if (!IsEquality) {
12716         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12717         return false;
12718       }
12719       // A constant address may compare equal to the address of a symbol.
12720       // The one exception is that address of an object cannot compare equal
12721       // to a null pointer constant.
12722       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12723           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12724         return Error(E);
12725       // It's implementation-defined whether distinct literals will have
12726       // distinct addresses. In clang, the result of such a comparison is
12727       // unspecified, so it is not a constant expression. However, we do know
12728       // that the address of a literal will be non-null.
12729       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12730           LHSValue.Base && RHSValue.Base)
12731         return Error(E);
12732       // We can't tell whether weak symbols will end up pointing to the same
12733       // object.
12734       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12735         return Error(E);
12736       // We can't compare the address of the start of one object with the
12737       // past-the-end address of another object, per C++ DR1652.
12738       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12739            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12740           (RHSValue.Base && RHSValue.Offset.isZero() &&
12741            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12742         return Error(E);
12743       // We can't tell whether an object is at the same address as another
12744       // zero sized object.
12745       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12746           (LHSValue.Base && isZeroSized(RHSValue)))
12747         return Error(E);
12748       return Success(CmpResult::Unequal, E);
12749     }
12750 
12751     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12752     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12753 
12754     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12755     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12756 
12757     // C++11 [expr.rel]p3:
12758     //   Pointers to void (after pointer conversions) can be compared, with a
12759     //   result defined as follows: If both pointers represent the same
12760     //   address or are both the null pointer value, the result is true if the
12761     //   operator is <= or >= and false otherwise; otherwise the result is
12762     //   unspecified.
12763     // We interpret this as applying to pointers to *cv* void.
12764     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12765       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12766 
12767     // C++11 [expr.rel]p2:
12768     // - If two pointers point to non-static data members of the same object,
12769     //   or to subobjects or array elements fo such members, recursively, the
12770     //   pointer to the later declared member compares greater provided the
12771     //   two members have the same access control and provided their class is
12772     //   not a union.
12773     //   [...]
12774     // - Otherwise pointer comparisons are unspecified.
12775     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12776       bool WasArrayIndex;
12777       unsigned Mismatch = FindDesignatorMismatch(
12778           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12779       // At the point where the designators diverge, the comparison has a
12780       // specified value if:
12781       //  - we are comparing array indices
12782       //  - we are comparing fields of a union, or fields with the same access
12783       // Otherwise, the result is unspecified and thus the comparison is not a
12784       // constant expression.
12785       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12786           Mismatch < RHSDesignator.Entries.size()) {
12787         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12788         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12789         if (!LF && !RF)
12790           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12791         else if (!LF)
12792           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12793               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12794               << RF->getParent() << RF;
12795         else if (!RF)
12796           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12797               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12798               << LF->getParent() << LF;
12799         else if (!LF->getParent()->isUnion() &&
12800                  LF->getAccess() != RF->getAccess())
12801           Info.CCEDiag(E,
12802                        diag::note_constexpr_pointer_comparison_differing_access)
12803               << LF << LF->getAccess() << RF << RF->getAccess()
12804               << LF->getParent();
12805       }
12806     }
12807 
12808     // The comparison here must be unsigned, and performed with the same
12809     // width as the pointer.
12810     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12811     uint64_t CompareLHS = LHSOffset.getQuantity();
12812     uint64_t CompareRHS = RHSOffset.getQuantity();
12813     assert(PtrSize <= 64 && "Unexpected pointer width");
12814     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12815     CompareLHS &= Mask;
12816     CompareRHS &= Mask;
12817 
12818     // If there is a base and this is a relational operator, we can only
12819     // compare pointers within the object in question; otherwise, the result
12820     // depends on where the object is located in memory.
12821     if (!LHSValue.Base.isNull() && IsRelational) {
12822       QualType BaseTy = getType(LHSValue.Base);
12823       if (BaseTy->isIncompleteType())
12824         return Error(E);
12825       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12826       uint64_t OffsetLimit = Size.getQuantity();
12827       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12828         return Error(E);
12829     }
12830 
12831     if (CompareLHS < CompareRHS)
12832       return Success(CmpResult::Less, E);
12833     if (CompareLHS > CompareRHS)
12834       return Success(CmpResult::Greater, E);
12835     return Success(CmpResult::Equal, E);
12836   }
12837 
12838   if (LHSTy->isMemberPointerType()) {
12839     assert(IsEquality && "unexpected member pointer operation");
12840     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12841 
12842     MemberPtr LHSValue, RHSValue;
12843 
12844     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12845     if (!LHSOK && !Info.noteFailure())
12846       return false;
12847 
12848     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12849       return false;
12850 
12851     // C++11 [expr.eq]p2:
12852     //   If both operands are null, they compare equal. Otherwise if only one is
12853     //   null, they compare unequal.
12854     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12855       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12856       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12857     }
12858 
12859     //   Otherwise if either is a pointer to a virtual member function, the
12860     //   result is unspecified.
12861     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12862       if (MD->isVirtual())
12863         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12864     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12865       if (MD->isVirtual())
12866         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12867 
12868     //   Otherwise they compare equal if and only if they would refer to the
12869     //   same member of the same most derived object or the same subobject if
12870     //   they were dereferenced with a hypothetical object of the associated
12871     //   class type.
12872     bool Equal = LHSValue == RHSValue;
12873     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12874   }
12875 
12876   if (LHSTy->isNullPtrType()) {
12877     assert(E->isComparisonOp() && "unexpected nullptr operation");
12878     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12879     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12880     // are compared, the result is true of the operator is <=, >= or ==, and
12881     // false otherwise.
12882     return Success(CmpResult::Equal, E);
12883   }
12884 
12885   return DoAfter();
12886 }
12887 
12888 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12889   if (!CheckLiteralType(Info, E))
12890     return false;
12891 
12892   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12893     ComparisonCategoryResult CCR;
12894     switch (CR) {
12895     case CmpResult::Unequal:
12896       llvm_unreachable("should never produce Unequal for three-way comparison");
12897     case CmpResult::Less:
12898       CCR = ComparisonCategoryResult::Less;
12899       break;
12900     case CmpResult::Equal:
12901       CCR = ComparisonCategoryResult::Equal;
12902       break;
12903     case CmpResult::Greater:
12904       CCR = ComparisonCategoryResult::Greater;
12905       break;
12906     case CmpResult::Unordered:
12907       CCR = ComparisonCategoryResult::Unordered;
12908       break;
12909     }
12910     // Evaluation succeeded. Lookup the information for the comparison category
12911     // type and fetch the VarDecl for the result.
12912     const ComparisonCategoryInfo &CmpInfo =
12913         Info.Ctx.CompCategories.getInfoForType(E->getType());
12914     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12915     // Check and evaluate the result as a constant expression.
12916     LValue LV;
12917     LV.set(VD);
12918     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12919       return false;
12920     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12921                                    ConstantExprKind::Normal);
12922   };
12923   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12924     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12925   });
12926 }
12927 
12928 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12929   // We don't support assignment in C. C++ assignments don't get here because
12930   // assignment is an lvalue in C++.
12931   if (E->isAssignmentOp()) {
12932     Error(E);
12933     if (!Info.noteFailure())
12934       return false;
12935   }
12936 
12937   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12938     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12939 
12940   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12941           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12942          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12943 
12944   if (E->isComparisonOp()) {
12945     // Evaluate builtin binary comparisons by evaluating them as three-way
12946     // comparisons and then translating the result.
12947     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12948       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12949              "should only produce Unequal for equality comparisons");
12950       bool IsEqual   = CR == CmpResult::Equal,
12951            IsLess    = CR == CmpResult::Less,
12952            IsGreater = CR == CmpResult::Greater;
12953       auto Op = E->getOpcode();
12954       switch (Op) {
12955       default:
12956         llvm_unreachable("unsupported binary operator");
12957       case BO_EQ:
12958       case BO_NE:
12959         return Success(IsEqual == (Op == BO_EQ), E);
12960       case BO_LT:
12961         return Success(IsLess, E);
12962       case BO_GT:
12963         return Success(IsGreater, E);
12964       case BO_LE:
12965         return Success(IsEqual || IsLess, E);
12966       case BO_GE:
12967         return Success(IsEqual || IsGreater, E);
12968       }
12969     };
12970     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12971       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12972     });
12973   }
12974 
12975   QualType LHSTy = E->getLHS()->getType();
12976   QualType RHSTy = E->getRHS()->getType();
12977 
12978   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12979       E->getOpcode() == BO_Sub) {
12980     LValue LHSValue, RHSValue;
12981 
12982     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12983     if (!LHSOK && !Info.noteFailure())
12984       return false;
12985 
12986     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12987       return false;
12988 
12989     // Reject differing bases from the normal codepath; we special-case
12990     // comparisons to null.
12991     if (!HasSameBase(LHSValue, RHSValue)) {
12992       // Handle &&A - &&B.
12993       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12994         return Error(E);
12995       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12996       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12997       if (!LHSExpr || !RHSExpr)
12998         return Error(E);
12999       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13000       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13001       if (!LHSAddrExpr || !RHSAddrExpr)
13002         return Error(E);
13003       // Make sure both labels come from the same function.
13004       if (LHSAddrExpr->getLabel()->getDeclContext() !=
13005           RHSAddrExpr->getLabel()->getDeclContext())
13006         return Error(E);
13007       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13008     }
13009     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13010     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13011 
13012     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13013     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13014 
13015     // C++11 [expr.add]p6:
13016     //   Unless both pointers point to elements of the same array object, or
13017     //   one past the last element of the array object, the behavior is
13018     //   undefined.
13019     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13020         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13021                                 RHSDesignator))
13022       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13023 
13024     QualType Type = E->getLHS()->getType();
13025     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13026 
13027     CharUnits ElementSize;
13028     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13029       return false;
13030 
13031     // As an extension, a type may have zero size (empty struct or union in
13032     // C, array of zero length). Pointer subtraction in such cases has
13033     // undefined behavior, so is not constant.
13034     if (ElementSize.isZero()) {
13035       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13036           << ElementType;
13037       return false;
13038     }
13039 
13040     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13041     // and produce incorrect results when it overflows. Such behavior
13042     // appears to be non-conforming, but is common, so perhaps we should
13043     // assume the standard intended for such cases to be undefined behavior
13044     // and check for them.
13045 
13046     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13047     // overflow in the final conversion to ptrdiff_t.
13048     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13049     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13050     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13051                     false);
13052     APSInt TrueResult = (LHS - RHS) / ElemSize;
13053     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13054 
13055     if (Result.extend(65) != TrueResult &&
13056         !HandleOverflow(Info, E, TrueResult, E->getType()))
13057       return false;
13058     return Success(Result, E);
13059   }
13060 
13061   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13062 }
13063 
13064 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13065 /// a result as the expression's type.
13066 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13067                                     const UnaryExprOrTypeTraitExpr *E) {
13068   switch(E->getKind()) {
13069   case UETT_PreferredAlignOf:
13070   case UETT_AlignOf: {
13071     if (E->isArgumentType())
13072       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13073                      E);
13074     else
13075       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13076                      E);
13077   }
13078 
13079   case UETT_VecStep: {
13080     QualType Ty = E->getTypeOfArgument();
13081 
13082     if (Ty->isVectorType()) {
13083       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13084 
13085       // The vec_step built-in functions that take a 3-component
13086       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13087       if (n == 3)
13088         n = 4;
13089 
13090       return Success(n, E);
13091     } else
13092       return Success(1, E);
13093   }
13094 
13095   case UETT_SizeOf: {
13096     QualType SrcTy = E->getTypeOfArgument();
13097     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13098     //   the result is the size of the referenced type."
13099     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13100       SrcTy = Ref->getPointeeType();
13101 
13102     CharUnits Sizeof;
13103     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13104       return false;
13105     return Success(Sizeof, E);
13106   }
13107   case UETT_OpenMPRequiredSimdAlign:
13108     assert(E->isArgumentType());
13109     return Success(
13110         Info.Ctx.toCharUnitsFromBits(
13111                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13112             .getQuantity(),
13113         E);
13114   }
13115 
13116   llvm_unreachable("unknown expr/type trait");
13117 }
13118 
13119 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13120   CharUnits Result;
13121   unsigned n = OOE->getNumComponents();
13122   if (n == 0)
13123     return Error(OOE);
13124   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13125   for (unsigned i = 0; i != n; ++i) {
13126     OffsetOfNode ON = OOE->getComponent(i);
13127     switch (ON.getKind()) {
13128     case OffsetOfNode::Array: {
13129       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13130       APSInt IdxResult;
13131       if (!EvaluateInteger(Idx, IdxResult, Info))
13132         return false;
13133       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13134       if (!AT)
13135         return Error(OOE);
13136       CurrentType = AT->getElementType();
13137       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13138       Result += IdxResult.getSExtValue() * ElementSize;
13139       break;
13140     }
13141 
13142     case OffsetOfNode::Field: {
13143       FieldDecl *MemberDecl = ON.getField();
13144       const RecordType *RT = CurrentType->getAs<RecordType>();
13145       if (!RT)
13146         return Error(OOE);
13147       RecordDecl *RD = RT->getDecl();
13148       if (RD->isInvalidDecl()) return false;
13149       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13150       unsigned i = MemberDecl->getFieldIndex();
13151       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13152       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13153       CurrentType = MemberDecl->getType().getNonReferenceType();
13154       break;
13155     }
13156 
13157     case OffsetOfNode::Identifier:
13158       llvm_unreachable("dependent __builtin_offsetof");
13159 
13160     case OffsetOfNode::Base: {
13161       CXXBaseSpecifier *BaseSpec = ON.getBase();
13162       if (BaseSpec->isVirtual())
13163         return Error(OOE);
13164 
13165       // Find the layout of the class whose base we are looking into.
13166       const RecordType *RT = CurrentType->getAs<RecordType>();
13167       if (!RT)
13168         return Error(OOE);
13169       RecordDecl *RD = RT->getDecl();
13170       if (RD->isInvalidDecl()) return false;
13171       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13172 
13173       // Find the base class itself.
13174       CurrentType = BaseSpec->getType();
13175       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13176       if (!BaseRT)
13177         return Error(OOE);
13178 
13179       // Add the offset to the base.
13180       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13181       break;
13182     }
13183     }
13184   }
13185   return Success(Result, OOE);
13186 }
13187 
13188 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13189   switch (E->getOpcode()) {
13190   default:
13191     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13192     // See C99 6.6p3.
13193     return Error(E);
13194   case UO_Extension:
13195     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13196     // If so, we could clear the diagnostic ID.
13197     return Visit(E->getSubExpr());
13198   case UO_Plus:
13199     // The result is just the value.
13200     return Visit(E->getSubExpr());
13201   case UO_Minus: {
13202     if (!Visit(E->getSubExpr()))
13203       return false;
13204     if (!Result.isInt()) return Error(E);
13205     const APSInt &Value = Result.getInt();
13206     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13207         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13208                         E->getType()))
13209       return false;
13210     return Success(-Value, E);
13211   }
13212   case UO_Not: {
13213     if (!Visit(E->getSubExpr()))
13214       return false;
13215     if (!Result.isInt()) return Error(E);
13216     return Success(~Result.getInt(), E);
13217   }
13218   case UO_LNot: {
13219     bool bres;
13220     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13221       return false;
13222     return Success(!bres, E);
13223   }
13224   }
13225 }
13226 
13227 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13228 /// result type is integer.
13229 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13230   const Expr *SubExpr = E->getSubExpr();
13231   QualType DestType = E->getType();
13232   QualType SrcType = SubExpr->getType();
13233 
13234   switch (E->getCastKind()) {
13235   case CK_BaseToDerived:
13236   case CK_DerivedToBase:
13237   case CK_UncheckedDerivedToBase:
13238   case CK_Dynamic:
13239   case CK_ToUnion:
13240   case CK_ArrayToPointerDecay:
13241   case CK_FunctionToPointerDecay:
13242   case CK_NullToPointer:
13243   case CK_NullToMemberPointer:
13244   case CK_BaseToDerivedMemberPointer:
13245   case CK_DerivedToBaseMemberPointer:
13246   case CK_ReinterpretMemberPointer:
13247   case CK_ConstructorConversion:
13248   case CK_IntegralToPointer:
13249   case CK_ToVoid:
13250   case CK_VectorSplat:
13251   case CK_IntegralToFloating:
13252   case CK_FloatingCast:
13253   case CK_CPointerToObjCPointerCast:
13254   case CK_BlockPointerToObjCPointerCast:
13255   case CK_AnyPointerToBlockPointerCast:
13256   case CK_ObjCObjectLValueCast:
13257   case CK_FloatingRealToComplex:
13258   case CK_FloatingComplexToReal:
13259   case CK_FloatingComplexCast:
13260   case CK_FloatingComplexToIntegralComplex:
13261   case CK_IntegralRealToComplex:
13262   case CK_IntegralComplexCast:
13263   case CK_IntegralComplexToFloatingComplex:
13264   case CK_BuiltinFnToFnPtr:
13265   case CK_ZeroToOCLOpaqueType:
13266   case CK_NonAtomicToAtomic:
13267   case CK_AddressSpaceConversion:
13268   case CK_IntToOCLSampler:
13269   case CK_FloatingToFixedPoint:
13270   case CK_FixedPointToFloating:
13271   case CK_FixedPointCast:
13272   case CK_IntegralToFixedPoint:
13273   case CK_MatrixCast:
13274     llvm_unreachable("invalid cast kind for integral value");
13275 
13276   case CK_BitCast:
13277   case CK_Dependent:
13278   case CK_LValueBitCast:
13279   case CK_ARCProduceObject:
13280   case CK_ARCConsumeObject:
13281   case CK_ARCReclaimReturnedObject:
13282   case CK_ARCExtendBlockObject:
13283   case CK_CopyAndAutoreleaseBlockObject:
13284     return Error(E);
13285 
13286   case CK_UserDefinedConversion:
13287   case CK_LValueToRValue:
13288   case CK_AtomicToNonAtomic:
13289   case CK_NoOp:
13290   case CK_LValueToRValueBitCast:
13291     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13292 
13293   case CK_MemberPointerToBoolean:
13294   case CK_PointerToBoolean:
13295   case CK_IntegralToBoolean:
13296   case CK_FloatingToBoolean:
13297   case CK_BooleanToSignedIntegral:
13298   case CK_FloatingComplexToBoolean:
13299   case CK_IntegralComplexToBoolean: {
13300     bool BoolResult;
13301     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13302       return false;
13303     uint64_t IntResult = BoolResult;
13304     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13305       IntResult = (uint64_t)-1;
13306     return Success(IntResult, E);
13307   }
13308 
13309   case CK_FixedPointToIntegral: {
13310     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13311     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13312       return false;
13313     bool Overflowed;
13314     llvm::APSInt Result = Src.convertToInt(
13315         Info.Ctx.getIntWidth(DestType),
13316         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13317     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13318       return false;
13319     return Success(Result, E);
13320   }
13321 
13322   case CK_FixedPointToBoolean: {
13323     // Unsigned padding does not affect this.
13324     APValue Val;
13325     if (!Evaluate(Val, Info, SubExpr))
13326       return false;
13327     return Success(Val.getFixedPoint().getBoolValue(), E);
13328   }
13329 
13330   case CK_IntegralCast: {
13331     if (!Visit(SubExpr))
13332       return false;
13333 
13334     if (!Result.isInt()) {
13335       // Allow casts of address-of-label differences if they are no-ops
13336       // or narrowing.  (The narrowing case isn't actually guaranteed to
13337       // be constant-evaluatable except in some narrow cases which are hard
13338       // to detect here.  We let it through on the assumption the user knows
13339       // what they are doing.)
13340       if (Result.isAddrLabelDiff())
13341         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13342       // Only allow casts of lvalues if they are lossless.
13343       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13344     }
13345 
13346     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13347                                       Result.getInt()), E);
13348   }
13349 
13350   case CK_PointerToIntegral: {
13351     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13352 
13353     LValue LV;
13354     if (!EvaluatePointer(SubExpr, LV, Info))
13355       return false;
13356 
13357     if (LV.getLValueBase()) {
13358       // Only allow based lvalue casts if they are lossless.
13359       // FIXME: Allow a larger integer size than the pointer size, and allow
13360       // narrowing back down to pointer width in subsequent integral casts.
13361       // FIXME: Check integer type's active bits, not its type size.
13362       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13363         return Error(E);
13364 
13365       LV.Designator.setInvalid();
13366       LV.moveInto(Result);
13367       return true;
13368     }
13369 
13370     APSInt AsInt;
13371     APValue V;
13372     LV.moveInto(V);
13373     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13374       llvm_unreachable("Can't cast this!");
13375 
13376     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13377   }
13378 
13379   case CK_IntegralComplexToReal: {
13380     ComplexValue C;
13381     if (!EvaluateComplex(SubExpr, C, Info))
13382       return false;
13383     return Success(C.getComplexIntReal(), E);
13384   }
13385 
13386   case CK_FloatingToIntegral: {
13387     APFloat F(0.0);
13388     if (!EvaluateFloat(SubExpr, F, Info))
13389       return false;
13390 
13391     APSInt Value;
13392     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13393       return false;
13394     return Success(Value, E);
13395   }
13396   }
13397 
13398   llvm_unreachable("unknown cast resulting in integral value");
13399 }
13400 
13401 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13402   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13403     ComplexValue LV;
13404     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13405       return false;
13406     if (!LV.isComplexInt())
13407       return Error(E);
13408     return Success(LV.getComplexIntReal(), E);
13409   }
13410 
13411   return Visit(E->getSubExpr());
13412 }
13413 
13414 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13415   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13416     ComplexValue LV;
13417     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13418       return false;
13419     if (!LV.isComplexInt())
13420       return Error(E);
13421     return Success(LV.getComplexIntImag(), E);
13422   }
13423 
13424   VisitIgnoredValue(E->getSubExpr());
13425   return Success(0, E);
13426 }
13427 
13428 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13429   return Success(E->getPackLength(), E);
13430 }
13431 
13432 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13433   return Success(E->getValue(), E);
13434 }
13435 
13436 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13437        const ConceptSpecializationExpr *E) {
13438   return Success(E->isSatisfied(), E);
13439 }
13440 
13441 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13442   return Success(E->isSatisfied(), E);
13443 }
13444 
13445 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13446   switch (E->getOpcode()) {
13447     default:
13448       // Invalid unary operators
13449       return Error(E);
13450     case UO_Plus:
13451       // The result is just the value.
13452       return Visit(E->getSubExpr());
13453     case UO_Minus: {
13454       if (!Visit(E->getSubExpr())) return false;
13455       if (!Result.isFixedPoint())
13456         return Error(E);
13457       bool Overflowed;
13458       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13459       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13460         return false;
13461       return Success(Negated, E);
13462     }
13463     case UO_LNot: {
13464       bool bres;
13465       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13466         return false;
13467       return Success(!bres, E);
13468     }
13469   }
13470 }
13471 
13472 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13473   const Expr *SubExpr = E->getSubExpr();
13474   QualType DestType = E->getType();
13475   assert(DestType->isFixedPointType() &&
13476          "Expected destination type to be a fixed point type");
13477   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13478 
13479   switch (E->getCastKind()) {
13480   case CK_FixedPointCast: {
13481     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13482     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13483       return false;
13484     bool Overflowed;
13485     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13486     if (Overflowed) {
13487       if (Info.checkingForUndefinedBehavior())
13488         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13489                                          diag::warn_fixedpoint_constant_overflow)
13490           << Result.toString() << E->getType();
13491       if (!HandleOverflow(Info, E, Result, E->getType()))
13492         return false;
13493     }
13494     return Success(Result, E);
13495   }
13496   case CK_IntegralToFixedPoint: {
13497     APSInt Src;
13498     if (!EvaluateInteger(SubExpr, Src, Info))
13499       return false;
13500 
13501     bool Overflowed;
13502     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13503         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13504 
13505     if (Overflowed) {
13506       if (Info.checkingForUndefinedBehavior())
13507         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13508                                          diag::warn_fixedpoint_constant_overflow)
13509           << IntResult.toString() << E->getType();
13510       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13511         return false;
13512     }
13513 
13514     return Success(IntResult, E);
13515   }
13516   case CK_FloatingToFixedPoint: {
13517     APFloat Src(0.0);
13518     if (!EvaluateFloat(SubExpr, Src, Info))
13519       return false;
13520 
13521     bool Overflowed;
13522     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13523         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13524 
13525     if (Overflowed) {
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 
13534     return Success(Result, E);
13535   }
13536   case CK_NoOp:
13537   case CK_LValueToRValue:
13538     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13539   default:
13540     return Error(E);
13541   }
13542 }
13543 
13544 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13545   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13546     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13547 
13548   const Expr *LHS = E->getLHS();
13549   const Expr *RHS = E->getRHS();
13550   FixedPointSemantics ResultFXSema =
13551       Info.Ctx.getFixedPointSemantics(E->getType());
13552 
13553   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13554   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13555     return false;
13556   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13557   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13558     return false;
13559 
13560   bool OpOverflow = false, ConversionOverflow = false;
13561   APFixedPoint Result(LHSFX.getSemantics());
13562   switch (E->getOpcode()) {
13563   case BO_Add: {
13564     Result = LHSFX.add(RHSFX, &OpOverflow)
13565                   .convert(ResultFXSema, &ConversionOverflow);
13566     break;
13567   }
13568   case BO_Sub: {
13569     Result = LHSFX.sub(RHSFX, &OpOverflow)
13570                   .convert(ResultFXSema, &ConversionOverflow);
13571     break;
13572   }
13573   case BO_Mul: {
13574     Result = LHSFX.mul(RHSFX, &OpOverflow)
13575                   .convert(ResultFXSema, &ConversionOverflow);
13576     break;
13577   }
13578   case BO_Div: {
13579     if (RHSFX.getValue() == 0) {
13580       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13581       return false;
13582     }
13583     Result = LHSFX.div(RHSFX, &OpOverflow)
13584                   .convert(ResultFXSema, &ConversionOverflow);
13585     break;
13586   }
13587   case BO_Shl:
13588   case BO_Shr: {
13589     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13590     llvm::APSInt RHSVal = RHSFX.getValue();
13591 
13592     unsigned ShiftBW =
13593         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13594     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13595     // Embedded-C 4.1.6.2.2:
13596     //   The right operand must be nonnegative and less than the total number
13597     //   of (nonpadding) bits of the fixed-point operand ...
13598     if (RHSVal.isNegative())
13599       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13600     else if (Amt != RHSVal)
13601       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13602           << RHSVal << E->getType() << ShiftBW;
13603 
13604     if (E->getOpcode() == BO_Shl)
13605       Result = LHSFX.shl(Amt, &OpOverflow);
13606     else
13607       Result = LHSFX.shr(Amt, &OpOverflow);
13608     break;
13609   }
13610   default:
13611     return false;
13612   }
13613   if (OpOverflow || ConversionOverflow) {
13614     if (Info.checkingForUndefinedBehavior())
13615       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13616                                        diag::warn_fixedpoint_constant_overflow)
13617         << Result.toString() << E->getType();
13618     if (!HandleOverflow(Info, E, Result, E->getType()))
13619       return false;
13620   }
13621   return Success(Result, E);
13622 }
13623 
13624 //===----------------------------------------------------------------------===//
13625 // Float Evaluation
13626 //===----------------------------------------------------------------------===//
13627 
13628 namespace {
13629 class FloatExprEvaluator
13630   : public ExprEvaluatorBase<FloatExprEvaluator> {
13631   APFloat &Result;
13632 public:
13633   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13634     : ExprEvaluatorBaseTy(info), Result(result) {}
13635 
13636   bool Success(const APValue &V, const Expr *e) {
13637     Result = V.getFloat();
13638     return true;
13639   }
13640 
13641   bool ZeroInitialization(const Expr *E) {
13642     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13643     return true;
13644   }
13645 
13646   bool VisitCallExpr(const CallExpr *E);
13647 
13648   bool VisitUnaryOperator(const UnaryOperator *E);
13649   bool VisitBinaryOperator(const BinaryOperator *E);
13650   bool VisitFloatingLiteral(const FloatingLiteral *E);
13651   bool VisitCastExpr(const CastExpr *E);
13652 
13653   bool VisitUnaryReal(const UnaryOperator *E);
13654   bool VisitUnaryImag(const UnaryOperator *E);
13655 
13656   // FIXME: Missing: array subscript of vector, member of vector
13657 };
13658 } // end anonymous namespace
13659 
13660 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13661   assert(!E->isValueDependent());
13662   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13663   return FloatExprEvaluator(Info, Result).Visit(E);
13664 }
13665 
13666 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13667                                   QualType ResultTy,
13668                                   const Expr *Arg,
13669                                   bool SNaN,
13670                                   llvm::APFloat &Result) {
13671   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13672   if (!S) return false;
13673 
13674   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13675 
13676   llvm::APInt fill;
13677 
13678   // Treat empty strings as if they were zero.
13679   if (S->getString().empty())
13680     fill = llvm::APInt(32, 0);
13681   else if (S->getString().getAsInteger(0, fill))
13682     return false;
13683 
13684   if (Context.getTargetInfo().isNan2008()) {
13685     if (SNaN)
13686       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13687     else
13688       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13689   } else {
13690     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13691     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13692     // a different encoding to what became a standard in 2008, and for pre-
13693     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13694     // sNaN. This is now known as "legacy NaN" encoding.
13695     if (SNaN)
13696       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13697     else
13698       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13699   }
13700 
13701   return true;
13702 }
13703 
13704 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13705   switch (E->getBuiltinCallee()) {
13706   default:
13707     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13708 
13709   case Builtin::BI__builtin_huge_val:
13710   case Builtin::BI__builtin_huge_valf:
13711   case Builtin::BI__builtin_huge_vall:
13712   case Builtin::BI__builtin_huge_valf128:
13713   case Builtin::BI__builtin_inf:
13714   case Builtin::BI__builtin_inff:
13715   case Builtin::BI__builtin_infl:
13716   case Builtin::BI__builtin_inff128: {
13717     const llvm::fltSemantics &Sem =
13718       Info.Ctx.getFloatTypeSemantics(E->getType());
13719     Result = llvm::APFloat::getInf(Sem);
13720     return true;
13721   }
13722 
13723   case Builtin::BI__builtin_nans:
13724   case Builtin::BI__builtin_nansf:
13725   case Builtin::BI__builtin_nansl:
13726   case Builtin::BI__builtin_nansf128:
13727     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13728                                true, Result))
13729       return Error(E);
13730     return true;
13731 
13732   case Builtin::BI__builtin_nan:
13733   case Builtin::BI__builtin_nanf:
13734   case Builtin::BI__builtin_nanl:
13735   case Builtin::BI__builtin_nanf128:
13736     // If this is __builtin_nan() turn this into a nan, otherwise we
13737     // can't constant fold it.
13738     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13739                                false, Result))
13740       return Error(E);
13741     return true;
13742 
13743   case Builtin::BI__builtin_fabs:
13744   case Builtin::BI__builtin_fabsf:
13745   case Builtin::BI__builtin_fabsl:
13746   case Builtin::BI__builtin_fabsf128:
13747     // The C standard says "fabs raises no floating-point exceptions,
13748     // even if x is a signaling NaN. The returned value is independent of
13749     // the current rounding direction mode."  Therefore constant folding can
13750     // proceed without regard to the floating point settings.
13751     // Reference, WG14 N2478 F.10.4.3
13752     if (!EvaluateFloat(E->getArg(0), Result, Info))
13753       return false;
13754 
13755     if (Result.isNegative())
13756       Result.changeSign();
13757     return true;
13758 
13759   case Builtin::BI__arithmetic_fence:
13760     return EvaluateFloat(E->getArg(0), Result, Info);
13761 
13762   // FIXME: Builtin::BI__builtin_powi
13763   // FIXME: Builtin::BI__builtin_powif
13764   // FIXME: Builtin::BI__builtin_powil
13765 
13766   case Builtin::BI__builtin_copysign:
13767   case Builtin::BI__builtin_copysignf:
13768   case Builtin::BI__builtin_copysignl:
13769   case Builtin::BI__builtin_copysignf128: {
13770     APFloat RHS(0.);
13771     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13772         !EvaluateFloat(E->getArg(1), RHS, Info))
13773       return false;
13774     Result.copySign(RHS);
13775     return true;
13776   }
13777   }
13778 }
13779 
13780 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13781   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13782     ComplexValue CV;
13783     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13784       return false;
13785     Result = CV.FloatReal;
13786     return true;
13787   }
13788 
13789   return Visit(E->getSubExpr());
13790 }
13791 
13792 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13793   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13794     ComplexValue CV;
13795     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13796       return false;
13797     Result = CV.FloatImag;
13798     return true;
13799   }
13800 
13801   VisitIgnoredValue(E->getSubExpr());
13802   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13803   Result = llvm::APFloat::getZero(Sem);
13804   return true;
13805 }
13806 
13807 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13808   switch (E->getOpcode()) {
13809   default: return Error(E);
13810   case UO_Plus:
13811     return EvaluateFloat(E->getSubExpr(), Result, Info);
13812   case UO_Minus:
13813     // In C standard, WG14 N2478 F.3 p4
13814     // "the unary - raises no floating point exceptions,
13815     // even if the operand is signalling."
13816     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13817       return false;
13818     Result.changeSign();
13819     return true;
13820   }
13821 }
13822 
13823 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13824   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13825     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13826 
13827   APFloat RHS(0.0);
13828   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13829   if (!LHSOK && !Info.noteFailure())
13830     return false;
13831   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13832          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13833 }
13834 
13835 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13836   Result = E->getValue();
13837   return true;
13838 }
13839 
13840 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13841   const Expr* SubExpr = E->getSubExpr();
13842 
13843   switch (E->getCastKind()) {
13844   default:
13845     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13846 
13847   case CK_IntegralToFloating: {
13848     APSInt IntResult;
13849     const FPOptions FPO = E->getFPFeaturesInEffect(
13850                                   Info.Ctx.getLangOpts());
13851     return EvaluateInteger(SubExpr, IntResult, Info) &&
13852            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13853                                 IntResult, E->getType(), Result);
13854   }
13855 
13856   case CK_FixedPointToFloating: {
13857     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13858     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13859       return false;
13860     Result =
13861         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13862     return true;
13863   }
13864 
13865   case CK_FloatingCast: {
13866     if (!Visit(SubExpr))
13867       return false;
13868     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13869                                   Result);
13870   }
13871 
13872   case CK_FloatingComplexToReal: {
13873     ComplexValue V;
13874     if (!EvaluateComplex(SubExpr, V, Info))
13875       return false;
13876     Result = V.getComplexFloatReal();
13877     return true;
13878   }
13879   }
13880 }
13881 
13882 //===----------------------------------------------------------------------===//
13883 // Complex Evaluation (for float and integer)
13884 //===----------------------------------------------------------------------===//
13885 
13886 namespace {
13887 class ComplexExprEvaluator
13888   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13889   ComplexValue &Result;
13890 
13891 public:
13892   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13893     : ExprEvaluatorBaseTy(info), Result(Result) {}
13894 
13895   bool Success(const APValue &V, const Expr *e) {
13896     Result.setFrom(V);
13897     return true;
13898   }
13899 
13900   bool ZeroInitialization(const Expr *E);
13901 
13902   //===--------------------------------------------------------------------===//
13903   //                            Visitor Methods
13904   //===--------------------------------------------------------------------===//
13905 
13906   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13907   bool VisitCastExpr(const CastExpr *E);
13908   bool VisitBinaryOperator(const BinaryOperator *E);
13909   bool VisitUnaryOperator(const UnaryOperator *E);
13910   bool VisitInitListExpr(const InitListExpr *E);
13911   bool VisitCallExpr(const CallExpr *E);
13912 };
13913 } // end anonymous namespace
13914 
13915 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13916                             EvalInfo &Info) {
13917   assert(!E->isValueDependent());
13918   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13919   return ComplexExprEvaluator(Info, Result).Visit(E);
13920 }
13921 
13922 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13923   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13924   if (ElemTy->isRealFloatingType()) {
13925     Result.makeComplexFloat();
13926     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13927     Result.FloatReal = Zero;
13928     Result.FloatImag = Zero;
13929   } else {
13930     Result.makeComplexInt();
13931     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13932     Result.IntReal = Zero;
13933     Result.IntImag = Zero;
13934   }
13935   return true;
13936 }
13937 
13938 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13939   const Expr* SubExpr = E->getSubExpr();
13940 
13941   if (SubExpr->getType()->isRealFloatingType()) {
13942     Result.makeComplexFloat();
13943     APFloat &Imag = Result.FloatImag;
13944     if (!EvaluateFloat(SubExpr, Imag, Info))
13945       return false;
13946 
13947     Result.FloatReal = APFloat(Imag.getSemantics());
13948     return true;
13949   } else {
13950     assert(SubExpr->getType()->isIntegerType() &&
13951            "Unexpected imaginary literal.");
13952 
13953     Result.makeComplexInt();
13954     APSInt &Imag = Result.IntImag;
13955     if (!EvaluateInteger(SubExpr, Imag, Info))
13956       return false;
13957 
13958     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13959     return true;
13960   }
13961 }
13962 
13963 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13964 
13965   switch (E->getCastKind()) {
13966   case CK_BitCast:
13967   case CK_BaseToDerived:
13968   case CK_DerivedToBase:
13969   case CK_UncheckedDerivedToBase:
13970   case CK_Dynamic:
13971   case CK_ToUnion:
13972   case CK_ArrayToPointerDecay:
13973   case CK_FunctionToPointerDecay:
13974   case CK_NullToPointer:
13975   case CK_NullToMemberPointer:
13976   case CK_BaseToDerivedMemberPointer:
13977   case CK_DerivedToBaseMemberPointer:
13978   case CK_MemberPointerToBoolean:
13979   case CK_ReinterpretMemberPointer:
13980   case CK_ConstructorConversion:
13981   case CK_IntegralToPointer:
13982   case CK_PointerToIntegral:
13983   case CK_PointerToBoolean:
13984   case CK_ToVoid:
13985   case CK_VectorSplat:
13986   case CK_IntegralCast:
13987   case CK_BooleanToSignedIntegral:
13988   case CK_IntegralToBoolean:
13989   case CK_IntegralToFloating:
13990   case CK_FloatingToIntegral:
13991   case CK_FloatingToBoolean:
13992   case CK_FloatingCast:
13993   case CK_CPointerToObjCPointerCast:
13994   case CK_BlockPointerToObjCPointerCast:
13995   case CK_AnyPointerToBlockPointerCast:
13996   case CK_ObjCObjectLValueCast:
13997   case CK_FloatingComplexToReal:
13998   case CK_FloatingComplexToBoolean:
13999   case CK_IntegralComplexToReal:
14000   case CK_IntegralComplexToBoolean:
14001   case CK_ARCProduceObject:
14002   case CK_ARCConsumeObject:
14003   case CK_ARCReclaimReturnedObject:
14004   case CK_ARCExtendBlockObject:
14005   case CK_CopyAndAutoreleaseBlockObject:
14006   case CK_BuiltinFnToFnPtr:
14007   case CK_ZeroToOCLOpaqueType:
14008   case CK_NonAtomicToAtomic:
14009   case CK_AddressSpaceConversion:
14010   case CK_IntToOCLSampler:
14011   case CK_FloatingToFixedPoint:
14012   case CK_FixedPointToFloating:
14013   case CK_FixedPointCast:
14014   case CK_FixedPointToBoolean:
14015   case CK_FixedPointToIntegral:
14016   case CK_IntegralToFixedPoint:
14017   case CK_MatrixCast:
14018     llvm_unreachable("invalid cast kind for complex value");
14019 
14020   case CK_LValueToRValue:
14021   case CK_AtomicToNonAtomic:
14022   case CK_NoOp:
14023   case CK_LValueToRValueBitCast:
14024     return ExprEvaluatorBaseTy::VisitCastExpr(E);
14025 
14026   case CK_Dependent:
14027   case CK_LValueBitCast:
14028   case CK_UserDefinedConversion:
14029     return Error(E);
14030 
14031   case CK_FloatingRealToComplex: {
14032     APFloat &Real = Result.FloatReal;
14033     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14034       return false;
14035 
14036     Result.makeComplexFloat();
14037     Result.FloatImag = APFloat(Real.getSemantics());
14038     return true;
14039   }
14040 
14041   case CK_FloatingComplexCast: {
14042     if (!Visit(E->getSubExpr()))
14043       return false;
14044 
14045     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14046     QualType From
14047       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14048 
14049     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14050            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14051   }
14052 
14053   case CK_FloatingComplexToIntegralComplex: {
14054     if (!Visit(E->getSubExpr()))
14055       return false;
14056 
14057     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14058     QualType From
14059       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14060     Result.makeComplexInt();
14061     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14062                                 To, Result.IntReal) &&
14063            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14064                                 To, Result.IntImag);
14065   }
14066 
14067   case CK_IntegralRealToComplex: {
14068     APSInt &Real = Result.IntReal;
14069     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14070       return false;
14071 
14072     Result.makeComplexInt();
14073     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14074     return true;
14075   }
14076 
14077   case CK_IntegralComplexCast: {
14078     if (!Visit(E->getSubExpr()))
14079       return false;
14080 
14081     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14082     QualType From
14083       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14084 
14085     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14086     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14087     return true;
14088   }
14089 
14090   case CK_IntegralComplexToFloatingComplex: {
14091     if (!Visit(E->getSubExpr()))
14092       return false;
14093 
14094     const FPOptions FPO = E->getFPFeaturesInEffect(
14095                                   Info.Ctx.getLangOpts());
14096     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14097     QualType From
14098       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14099     Result.makeComplexFloat();
14100     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14101                                 To, Result.FloatReal) &&
14102            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14103                                 To, Result.FloatImag);
14104   }
14105   }
14106 
14107   llvm_unreachable("unknown cast resulting in complex value");
14108 }
14109 
14110 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14111   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14112     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14113 
14114   // Track whether the LHS or RHS is real at the type system level. When this is
14115   // the case we can simplify our evaluation strategy.
14116   bool LHSReal = false, RHSReal = false;
14117 
14118   bool LHSOK;
14119   if (E->getLHS()->getType()->isRealFloatingType()) {
14120     LHSReal = true;
14121     APFloat &Real = Result.FloatReal;
14122     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14123     if (LHSOK) {
14124       Result.makeComplexFloat();
14125       Result.FloatImag = APFloat(Real.getSemantics());
14126     }
14127   } else {
14128     LHSOK = Visit(E->getLHS());
14129   }
14130   if (!LHSOK && !Info.noteFailure())
14131     return false;
14132 
14133   ComplexValue RHS;
14134   if (E->getRHS()->getType()->isRealFloatingType()) {
14135     RHSReal = true;
14136     APFloat &Real = RHS.FloatReal;
14137     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14138       return false;
14139     RHS.makeComplexFloat();
14140     RHS.FloatImag = APFloat(Real.getSemantics());
14141   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14142     return false;
14143 
14144   assert(!(LHSReal && RHSReal) &&
14145          "Cannot have both operands of a complex operation be real.");
14146   switch (E->getOpcode()) {
14147   default: return Error(E);
14148   case BO_Add:
14149     if (Result.isComplexFloat()) {
14150       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14151                                        APFloat::rmNearestTiesToEven);
14152       if (LHSReal)
14153         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14154       else if (!RHSReal)
14155         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14156                                          APFloat::rmNearestTiesToEven);
14157     } else {
14158       Result.getComplexIntReal() += RHS.getComplexIntReal();
14159       Result.getComplexIntImag() += RHS.getComplexIntImag();
14160     }
14161     break;
14162   case BO_Sub:
14163     if (Result.isComplexFloat()) {
14164       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14165                                             APFloat::rmNearestTiesToEven);
14166       if (LHSReal) {
14167         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14168         Result.getComplexFloatImag().changeSign();
14169       } else if (!RHSReal) {
14170         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14171                                               APFloat::rmNearestTiesToEven);
14172       }
14173     } else {
14174       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14175       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14176     }
14177     break;
14178   case BO_Mul:
14179     if (Result.isComplexFloat()) {
14180       // This is an implementation of complex multiplication according to the
14181       // constraints laid out in C11 Annex G. The implementation uses the
14182       // following naming scheme:
14183       //   (a + ib) * (c + id)
14184       ComplexValue LHS = Result;
14185       APFloat &A = LHS.getComplexFloatReal();
14186       APFloat &B = LHS.getComplexFloatImag();
14187       APFloat &C = RHS.getComplexFloatReal();
14188       APFloat &D = RHS.getComplexFloatImag();
14189       APFloat &ResR = Result.getComplexFloatReal();
14190       APFloat &ResI = Result.getComplexFloatImag();
14191       if (LHSReal) {
14192         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14193         ResR = A * C;
14194         ResI = A * D;
14195       } else if (RHSReal) {
14196         ResR = C * A;
14197         ResI = C * B;
14198       } else {
14199         // In the fully general case, we need to handle NaNs and infinities
14200         // robustly.
14201         APFloat AC = A * C;
14202         APFloat BD = B * D;
14203         APFloat AD = A * D;
14204         APFloat BC = B * C;
14205         ResR = AC - BD;
14206         ResI = AD + BC;
14207         if (ResR.isNaN() && ResI.isNaN()) {
14208           bool Recalc = false;
14209           if (A.isInfinity() || B.isInfinity()) {
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             if (C.isNaN())
14215               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14216             if (D.isNaN())
14217               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14218             Recalc = true;
14219           }
14220           if (C.isInfinity() || D.isInfinity()) {
14221             C = APFloat::copySign(
14222                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14223             D = APFloat::copySign(
14224                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14225             if (A.isNaN())
14226               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14227             if (B.isNaN())
14228               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14229             Recalc = true;
14230           }
14231           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14232                           AD.isInfinity() || BC.isInfinity())) {
14233             if (A.isNaN())
14234               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14235             if (B.isNaN())
14236               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14237             if (C.isNaN())
14238               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14239             if (D.isNaN())
14240               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14241             Recalc = true;
14242           }
14243           if (Recalc) {
14244             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14245             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14246           }
14247         }
14248       }
14249     } else {
14250       ComplexValue LHS = Result;
14251       Result.getComplexIntReal() =
14252         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14253          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14254       Result.getComplexIntImag() =
14255         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14256          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14257     }
14258     break;
14259   case BO_Div:
14260     if (Result.isComplexFloat()) {
14261       // This is an implementation of complex division according to the
14262       // constraints laid out in C11 Annex G. The implementation uses the
14263       // following naming scheme:
14264       //   (a + ib) / (c + id)
14265       ComplexValue LHS = Result;
14266       APFloat &A = LHS.getComplexFloatReal();
14267       APFloat &B = LHS.getComplexFloatImag();
14268       APFloat &C = RHS.getComplexFloatReal();
14269       APFloat &D = RHS.getComplexFloatImag();
14270       APFloat &ResR = Result.getComplexFloatReal();
14271       APFloat &ResI = Result.getComplexFloatImag();
14272       if (RHSReal) {
14273         ResR = A / C;
14274         ResI = B / C;
14275       } else {
14276         if (LHSReal) {
14277           // No real optimizations we can do here, stub out with zero.
14278           B = APFloat::getZero(A.getSemantics());
14279         }
14280         int DenomLogB = 0;
14281         APFloat MaxCD = maxnum(abs(C), abs(D));
14282         if (MaxCD.isFinite()) {
14283           DenomLogB = ilogb(MaxCD);
14284           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14285           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14286         }
14287         APFloat Denom = C * C + D * D;
14288         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14289                       APFloat::rmNearestTiesToEven);
14290         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14291                       APFloat::rmNearestTiesToEven);
14292         if (ResR.isNaN() && ResI.isNaN()) {
14293           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14294             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14295             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14296           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14297                      D.isFinite()) {
14298             A = APFloat::copySign(
14299                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14300             B = APFloat::copySign(
14301                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14302             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14303             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14304           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14305             C = APFloat::copySign(
14306                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14307             D = APFloat::copySign(
14308                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14309             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14310             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14311           }
14312         }
14313       }
14314     } else {
14315       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14316         return Error(E, diag::note_expr_divide_by_zero);
14317 
14318       ComplexValue LHS = Result;
14319       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14320         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14321       Result.getComplexIntReal() =
14322         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14323          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14324       Result.getComplexIntImag() =
14325         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14326          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14327     }
14328     break;
14329   }
14330 
14331   return true;
14332 }
14333 
14334 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14335   // Get the operand value into 'Result'.
14336   if (!Visit(E->getSubExpr()))
14337     return false;
14338 
14339   switch (E->getOpcode()) {
14340   default:
14341     return Error(E);
14342   case UO_Extension:
14343     return true;
14344   case UO_Plus:
14345     // The result is always just the subexpr.
14346     return true;
14347   case UO_Minus:
14348     if (Result.isComplexFloat()) {
14349       Result.getComplexFloatReal().changeSign();
14350       Result.getComplexFloatImag().changeSign();
14351     }
14352     else {
14353       Result.getComplexIntReal() = -Result.getComplexIntReal();
14354       Result.getComplexIntImag() = -Result.getComplexIntImag();
14355     }
14356     return true;
14357   case UO_Not:
14358     if (Result.isComplexFloat())
14359       Result.getComplexFloatImag().changeSign();
14360     else
14361       Result.getComplexIntImag() = -Result.getComplexIntImag();
14362     return true;
14363   }
14364 }
14365 
14366 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14367   if (E->getNumInits() == 2) {
14368     if (E->getType()->isComplexType()) {
14369       Result.makeComplexFloat();
14370       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14371         return false;
14372       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14373         return false;
14374     } else {
14375       Result.makeComplexInt();
14376       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14377         return false;
14378       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14379         return false;
14380     }
14381     return true;
14382   }
14383   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14384 }
14385 
14386 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14387   switch (E->getBuiltinCallee()) {
14388   case Builtin::BI__builtin_complex:
14389     Result.makeComplexFloat();
14390     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14391       return false;
14392     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14393       return false;
14394     return true;
14395 
14396   default:
14397     break;
14398   }
14399 
14400   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14401 }
14402 
14403 //===----------------------------------------------------------------------===//
14404 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14405 // implicit conversion.
14406 //===----------------------------------------------------------------------===//
14407 
14408 namespace {
14409 class AtomicExprEvaluator :
14410     public ExprEvaluatorBase<AtomicExprEvaluator> {
14411   const LValue *This;
14412   APValue &Result;
14413 public:
14414   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14415       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14416 
14417   bool Success(const APValue &V, const Expr *E) {
14418     Result = V;
14419     return true;
14420   }
14421 
14422   bool ZeroInitialization(const Expr *E) {
14423     ImplicitValueInitExpr VIE(
14424         E->getType()->castAs<AtomicType>()->getValueType());
14425     // For atomic-qualified class (and array) types in C++, initialize the
14426     // _Atomic-wrapped subobject directly, in-place.
14427     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14428                 : Evaluate(Result, Info, &VIE);
14429   }
14430 
14431   bool VisitCastExpr(const CastExpr *E) {
14432     switch (E->getCastKind()) {
14433     default:
14434       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14435     case CK_NonAtomicToAtomic:
14436       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14437                   : Evaluate(Result, Info, E->getSubExpr());
14438     }
14439   }
14440 };
14441 } // end anonymous namespace
14442 
14443 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14444                            EvalInfo &Info) {
14445   assert(!E->isValueDependent());
14446   assert(E->isPRValue() && E->getType()->isAtomicType());
14447   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14448 }
14449 
14450 //===----------------------------------------------------------------------===//
14451 // Void expression evaluation, primarily for a cast to void on the LHS of a
14452 // comma operator
14453 //===----------------------------------------------------------------------===//
14454 
14455 namespace {
14456 class VoidExprEvaluator
14457   : public ExprEvaluatorBase<VoidExprEvaluator> {
14458 public:
14459   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14460 
14461   bool Success(const APValue &V, const Expr *e) { return true; }
14462 
14463   bool ZeroInitialization(const Expr *E) { return true; }
14464 
14465   bool VisitCastExpr(const CastExpr *E) {
14466     switch (E->getCastKind()) {
14467     default:
14468       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14469     case CK_ToVoid:
14470       VisitIgnoredValue(E->getSubExpr());
14471       return true;
14472     }
14473   }
14474 
14475   bool VisitCallExpr(const CallExpr *E) {
14476     switch (E->getBuiltinCallee()) {
14477     case Builtin::BI__assume:
14478     case Builtin::BI__builtin_assume:
14479       // The argument is not evaluated!
14480       return true;
14481 
14482     case Builtin::BI__builtin_operator_delete:
14483       return HandleOperatorDeleteCall(Info, E);
14484 
14485     default:
14486       break;
14487     }
14488 
14489     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14490   }
14491 
14492   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14493 };
14494 } // end anonymous namespace
14495 
14496 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14497   // We cannot speculatively evaluate a delete expression.
14498   if (Info.SpeculativeEvaluationDepth)
14499     return false;
14500 
14501   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14502   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14503     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14504         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14505     return false;
14506   }
14507 
14508   const Expr *Arg = E->getArgument();
14509 
14510   LValue Pointer;
14511   if (!EvaluatePointer(Arg, Pointer, Info))
14512     return false;
14513   if (Pointer.Designator.Invalid)
14514     return false;
14515 
14516   // Deleting a null pointer has no effect.
14517   if (Pointer.isNullPointer()) {
14518     // This is the only case where we need to produce an extension warning:
14519     // the only other way we can succeed is if we find a dynamic allocation,
14520     // and we will have warned when we allocated it in that case.
14521     if (!Info.getLangOpts().CPlusPlus20)
14522       Info.CCEDiag(E, diag::note_constexpr_new);
14523     return true;
14524   }
14525 
14526   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14527       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14528   if (!Alloc)
14529     return false;
14530   QualType AllocType = Pointer.Base.getDynamicAllocType();
14531 
14532   // For the non-array case, the designator must be empty if the static type
14533   // does not have a virtual destructor.
14534   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14535       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14536     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14537         << Arg->getType()->getPointeeType() << AllocType;
14538     return false;
14539   }
14540 
14541   // For a class type with a virtual destructor, the selected operator delete
14542   // is the one looked up when building the destructor.
14543   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14544     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14545     if (VirtualDelete &&
14546         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14547       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14548           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14549       return false;
14550     }
14551   }
14552 
14553   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14554                          (*Alloc)->Value, AllocType))
14555     return false;
14556 
14557   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14558     // The element was already erased. This means the destructor call also
14559     // deleted the object.
14560     // FIXME: This probably results in undefined behavior before we get this
14561     // far, and should be diagnosed elsewhere first.
14562     Info.FFDiag(E, diag::note_constexpr_double_delete);
14563     return false;
14564   }
14565 
14566   return true;
14567 }
14568 
14569 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14570   assert(!E->isValueDependent());
14571   assert(E->isPRValue() && E->getType()->isVoidType());
14572   return VoidExprEvaluator(Info).Visit(E);
14573 }
14574 
14575 //===----------------------------------------------------------------------===//
14576 // Top level Expr::EvaluateAsRValue method.
14577 //===----------------------------------------------------------------------===//
14578 
14579 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14580   assert(!E->isValueDependent());
14581   // In C, function designators are not lvalues, but we evaluate them as if they
14582   // are.
14583   QualType T = E->getType();
14584   if (E->isGLValue() || T->isFunctionType()) {
14585     LValue LV;
14586     if (!EvaluateLValue(E, LV, Info))
14587       return false;
14588     LV.moveInto(Result);
14589   } else if (T->isVectorType()) {
14590     if (!EvaluateVector(E, Result, Info))
14591       return false;
14592   } else if (T->isIntegralOrEnumerationType()) {
14593     if (!IntExprEvaluator(Info, Result).Visit(E))
14594       return false;
14595   } else if (T->hasPointerRepresentation()) {
14596     LValue LV;
14597     if (!EvaluatePointer(E, LV, Info))
14598       return false;
14599     LV.moveInto(Result);
14600   } else if (T->isRealFloatingType()) {
14601     llvm::APFloat F(0.0);
14602     if (!EvaluateFloat(E, F, Info))
14603       return false;
14604     Result = APValue(F);
14605   } else if (T->isAnyComplexType()) {
14606     ComplexValue C;
14607     if (!EvaluateComplex(E, C, Info))
14608       return false;
14609     C.moveInto(Result);
14610   } else if (T->isFixedPointType()) {
14611     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14612   } else if (T->isMemberPointerType()) {
14613     MemberPtr P;
14614     if (!EvaluateMemberPointer(E, P, Info))
14615       return false;
14616     P.moveInto(Result);
14617     return true;
14618   } else if (T->isArrayType()) {
14619     LValue LV;
14620     APValue &Value =
14621         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14622     if (!EvaluateArray(E, LV, Value, Info))
14623       return false;
14624     Result = Value;
14625   } else if (T->isRecordType()) {
14626     LValue LV;
14627     APValue &Value =
14628         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14629     if (!EvaluateRecord(E, LV, Value, Info))
14630       return false;
14631     Result = Value;
14632   } else if (T->isVoidType()) {
14633     if (!Info.getLangOpts().CPlusPlus11)
14634       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14635         << E->getType();
14636     if (!EvaluateVoid(E, Info))
14637       return false;
14638   } else if (T->isAtomicType()) {
14639     QualType Unqual = T.getAtomicUnqualifiedType();
14640     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14641       LValue LV;
14642       APValue &Value = Info.CurrentCall->createTemporary(
14643           E, Unqual, ScopeKind::FullExpression, LV);
14644       if (!EvaluateAtomic(E, &LV, Value, Info))
14645         return false;
14646     } else {
14647       if (!EvaluateAtomic(E, nullptr, Result, Info))
14648         return false;
14649     }
14650   } else if (Info.getLangOpts().CPlusPlus11) {
14651     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14652     return false;
14653   } else {
14654     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14655     return false;
14656   }
14657 
14658   return true;
14659 }
14660 
14661 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14662 /// cases, the in-place evaluation is essential, since later initializers for
14663 /// an object can indirectly refer to subobjects which were initialized earlier.
14664 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14665                             const Expr *E, bool AllowNonLiteralTypes) {
14666   assert(!E->isValueDependent());
14667 
14668   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14669     return false;
14670 
14671   if (E->isPRValue()) {
14672     // Evaluate arrays and record types in-place, so that later initializers can
14673     // refer to earlier-initialized members of the object.
14674     QualType T = E->getType();
14675     if (T->isArrayType())
14676       return EvaluateArray(E, This, Result, Info);
14677     else if (T->isRecordType())
14678       return EvaluateRecord(E, This, Result, Info);
14679     else if (T->isAtomicType()) {
14680       QualType Unqual = T.getAtomicUnqualifiedType();
14681       if (Unqual->isArrayType() || Unqual->isRecordType())
14682         return EvaluateAtomic(E, &This, Result, Info);
14683     }
14684   }
14685 
14686   // For any other type, in-place evaluation is unimportant.
14687   return Evaluate(Result, Info, E);
14688 }
14689 
14690 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14691 /// lvalue-to-rvalue cast if it is an lvalue.
14692 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14693   assert(!E->isValueDependent());
14694   if (Info.EnableNewConstInterp) {
14695     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14696       return false;
14697   } else {
14698     if (E->getType().isNull())
14699       return false;
14700 
14701     if (!CheckLiteralType(Info, E))
14702       return false;
14703 
14704     if (!::Evaluate(Result, Info, E))
14705       return false;
14706 
14707     if (E->isGLValue()) {
14708       LValue LV;
14709       LV.setFrom(Info.Ctx, Result);
14710       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14711         return false;
14712     }
14713   }
14714 
14715   // Check this core constant expression is a constant expression.
14716   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14717                                  ConstantExprKind::Normal) &&
14718          CheckMemoryLeaks(Info);
14719 }
14720 
14721 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14722                                  const ASTContext &Ctx, bool &IsConst) {
14723   // Fast-path evaluations of integer literals, since we sometimes see files
14724   // containing vast quantities of these.
14725   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14726     Result.Val = APValue(APSInt(L->getValue(),
14727                                 L->getType()->isUnsignedIntegerType()));
14728     IsConst = true;
14729     return true;
14730   }
14731 
14732   // This case should be rare, but we need to check it before we check on
14733   // the type below.
14734   if (Exp->getType().isNull()) {
14735     IsConst = false;
14736     return true;
14737   }
14738 
14739   // FIXME: Evaluating values of large array and record types can cause
14740   // performance problems. Only do so in C++11 for now.
14741   if (Exp->isPRValue() &&
14742       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14743       !Ctx.getLangOpts().CPlusPlus11) {
14744     IsConst = false;
14745     return true;
14746   }
14747   return false;
14748 }
14749 
14750 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14751                                       Expr::SideEffectsKind SEK) {
14752   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14753          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14754 }
14755 
14756 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14757                              const ASTContext &Ctx, EvalInfo &Info) {
14758   assert(!E->isValueDependent());
14759   bool IsConst;
14760   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14761     return IsConst;
14762 
14763   return EvaluateAsRValue(Info, E, Result.Val);
14764 }
14765 
14766 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14767                           const ASTContext &Ctx,
14768                           Expr::SideEffectsKind AllowSideEffects,
14769                           EvalInfo &Info) {
14770   assert(!E->isValueDependent());
14771   if (!E->getType()->isIntegralOrEnumerationType())
14772     return false;
14773 
14774   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14775       !ExprResult.Val.isInt() ||
14776       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14777     return false;
14778 
14779   return true;
14780 }
14781 
14782 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14783                                  const ASTContext &Ctx,
14784                                  Expr::SideEffectsKind AllowSideEffects,
14785                                  EvalInfo &Info) {
14786   assert(!E->isValueDependent());
14787   if (!E->getType()->isFixedPointType())
14788     return false;
14789 
14790   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14791     return false;
14792 
14793   if (!ExprResult.Val.isFixedPoint() ||
14794       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14795     return false;
14796 
14797   return true;
14798 }
14799 
14800 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14801 /// any crazy technique (that has nothing to do with language standards) that
14802 /// we want to.  If this function returns true, it returns the folded constant
14803 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14804 /// will be applied to the result.
14805 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14806                             bool InConstantContext) const {
14807   assert(!isValueDependent() &&
14808          "Expression evaluator can't be called on a dependent expression.");
14809   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14810   Info.InConstantContext = InConstantContext;
14811   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14812 }
14813 
14814 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14815                                       bool InConstantContext) const {
14816   assert(!isValueDependent() &&
14817          "Expression evaluator can't be called on a dependent expression.");
14818   EvalResult Scratch;
14819   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14820          HandleConversionToBool(Scratch.Val, Result);
14821 }
14822 
14823 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14824                          SideEffectsKind AllowSideEffects,
14825                          bool InConstantContext) const {
14826   assert(!isValueDependent() &&
14827          "Expression evaluator can't be called on a dependent expression.");
14828   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14829   Info.InConstantContext = InConstantContext;
14830   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14831 }
14832 
14833 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14834                                 SideEffectsKind AllowSideEffects,
14835                                 bool InConstantContext) const {
14836   assert(!isValueDependent() &&
14837          "Expression evaluator can't be called on a dependent expression.");
14838   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14839   Info.InConstantContext = InConstantContext;
14840   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14841 }
14842 
14843 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14844                            SideEffectsKind AllowSideEffects,
14845                            bool InConstantContext) const {
14846   assert(!isValueDependent() &&
14847          "Expression evaluator can't be called on a dependent expression.");
14848 
14849   if (!getType()->isRealFloatingType())
14850     return false;
14851 
14852   EvalResult ExprResult;
14853   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14854       !ExprResult.Val.isFloat() ||
14855       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14856     return false;
14857 
14858   Result = ExprResult.Val.getFloat();
14859   return true;
14860 }
14861 
14862 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14863                             bool InConstantContext) const {
14864   assert(!isValueDependent() &&
14865          "Expression evaluator can't be called on a dependent expression.");
14866 
14867   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14868   Info.InConstantContext = InConstantContext;
14869   LValue LV;
14870   CheckedTemporaries CheckedTemps;
14871   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14872       Result.HasSideEffects ||
14873       !CheckLValueConstantExpression(Info, getExprLoc(),
14874                                      Ctx.getLValueReferenceType(getType()), LV,
14875                                      ConstantExprKind::Normal, CheckedTemps))
14876     return false;
14877 
14878   LV.moveInto(Result.Val);
14879   return true;
14880 }
14881 
14882 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14883                                 APValue DestroyedValue, QualType Type,
14884                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14885                                 bool IsConstantDestruction) {
14886   EvalInfo Info(Ctx, EStatus,
14887                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14888                                       : EvalInfo::EM_ConstantFold);
14889   Info.setEvaluatingDecl(Base, DestroyedValue,
14890                          EvalInfo::EvaluatingDeclKind::Dtor);
14891   Info.InConstantContext = IsConstantDestruction;
14892 
14893   LValue LVal;
14894   LVal.set(Base);
14895 
14896   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14897       EStatus.HasSideEffects)
14898     return false;
14899 
14900   if (!Info.discardCleanups())
14901     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14902 
14903   return true;
14904 }
14905 
14906 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14907                                   ConstantExprKind Kind) const {
14908   assert(!isValueDependent() &&
14909          "Expression evaluator can't be called on a dependent expression.");
14910 
14911   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14912   EvalInfo Info(Ctx, Result, EM);
14913   Info.InConstantContext = true;
14914 
14915   // The type of the object we're initializing is 'const T' for a class NTTP.
14916   QualType T = getType();
14917   if (Kind == ConstantExprKind::ClassTemplateArgument)
14918     T.addConst();
14919 
14920   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14921   // represent the result of the evaluation. CheckConstantExpression ensures
14922   // this doesn't escape.
14923   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14924   APValue::LValueBase Base(&BaseMTE);
14925 
14926   Info.setEvaluatingDecl(Base, Result.Val);
14927   LValue LVal;
14928   LVal.set(Base);
14929 
14930   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14931     return false;
14932 
14933   if (!Info.discardCleanups())
14934     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14935 
14936   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14937                                Result.Val, Kind))
14938     return false;
14939   if (!CheckMemoryLeaks(Info))
14940     return false;
14941 
14942   // If this is a class template argument, it's required to have constant
14943   // destruction too.
14944   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14945       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14946                             true) ||
14947        Result.HasSideEffects)) {
14948     // FIXME: Prefix a note to indicate that the problem is lack of constant
14949     // destruction.
14950     return false;
14951   }
14952 
14953   return true;
14954 }
14955 
14956 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14957                                  const VarDecl *VD,
14958                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14959                                  bool IsConstantInitialization) const {
14960   assert(!isValueDependent() &&
14961          "Expression evaluator can't be called on a dependent expression.");
14962 
14963   // FIXME: Evaluating initializers for large array and record types can cause
14964   // performance problems. Only do so in C++11 for now.
14965   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14966       !Ctx.getLangOpts().CPlusPlus11)
14967     return false;
14968 
14969   Expr::EvalStatus EStatus;
14970   EStatus.Diag = &Notes;
14971 
14972   EvalInfo Info(Ctx, EStatus,
14973                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14974                     ? EvalInfo::EM_ConstantExpression
14975                     : EvalInfo::EM_ConstantFold);
14976   Info.setEvaluatingDecl(VD, Value);
14977   Info.InConstantContext = IsConstantInitialization;
14978 
14979   SourceLocation DeclLoc = VD->getLocation();
14980   QualType DeclTy = VD->getType();
14981 
14982   if (Info.EnableNewConstInterp) {
14983     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14984     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14985       return false;
14986   } else {
14987     LValue LVal;
14988     LVal.set(VD);
14989 
14990     if (!EvaluateInPlace(Value, Info, LVal, this,
14991                          /*AllowNonLiteralTypes=*/true) ||
14992         EStatus.HasSideEffects)
14993       return false;
14994 
14995     // At this point, any lifetime-extended temporaries are completely
14996     // initialized.
14997     Info.performLifetimeExtension();
14998 
14999     if (!Info.discardCleanups())
15000       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15001   }
15002   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15003                                  ConstantExprKind::Normal) &&
15004          CheckMemoryLeaks(Info);
15005 }
15006 
15007 bool VarDecl::evaluateDestruction(
15008     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15009   Expr::EvalStatus EStatus;
15010   EStatus.Diag = &Notes;
15011 
15012   // Only treat the destruction as constant destruction if we formally have
15013   // constant initialization (or are usable in a constant expression).
15014   bool IsConstantDestruction = hasConstantInitialization();
15015 
15016   // Make a copy of the value for the destructor to mutate, if we know it.
15017   // Otherwise, treat the value as default-initialized; if the destructor works
15018   // anyway, then the destruction is constant (and must be essentially empty).
15019   APValue DestroyedValue;
15020   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15021     DestroyedValue = *getEvaluatedValue();
15022   else if (!getDefaultInitValue(getType(), DestroyedValue))
15023     return false;
15024 
15025   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15026                            getType(), getLocation(), EStatus,
15027                            IsConstantDestruction) ||
15028       EStatus.HasSideEffects)
15029     return false;
15030 
15031   ensureEvaluatedStmt()->HasConstantDestruction = true;
15032   return true;
15033 }
15034 
15035 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15036 /// constant folded, but discard the result.
15037 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15038   assert(!isValueDependent() &&
15039          "Expression evaluator can't be called on a dependent expression.");
15040 
15041   EvalResult Result;
15042   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15043          !hasUnacceptableSideEffect(Result, SEK);
15044 }
15045 
15046 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15047                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15048   assert(!isValueDependent() &&
15049          "Expression evaluator can't be called on a dependent expression.");
15050 
15051   EvalResult EVResult;
15052   EVResult.Diag = Diag;
15053   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15054   Info.InConstantContext = true;
15055 
15056   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15057   (void)Result;
15058   assert(Result && "Could not evaluate expression");
15059   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15060 
15061   return EVResult.Val.getInt();
15062 }
15063 
15064 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15065     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15066   assert(!isValueDependent() &&
15067          "Expression evaluator can't be called on a dependent expression.");
15068 
15069   EvalResult EVResult;
15070   EVResult.Diag = Diag;
15071   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15072   Info.InConstantContext = true;
15073   Info.CheckingForUndefinedBehavior = true;
15074 
15075   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15076   (void)Result;
15077   assert(Result && "Could not evaluate expression");
15078   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15079 
15080   return EVResult.Val.getInt();
15081 }
15082 
15083 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15084   assert(!isValueDependent() &&
15085          "Expression evaluator can't be called on a dependent expression.");
15086 
15087   bool IsConst;
15088   EvalResult EVResult;
15089   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15090     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15091     Info.CheckingForUndefinedBehavior = true;
15092     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15093   }
15094 }
15095 
15096 bool Expr::EvalResult::isGlobalLValue() const {
15097   assert(Val.isLValue());
15098   return IsGlobalLValue(Val.getLValueBase());
15099 }
15100 
15101 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15102 /// an integer constant expression.
15103 
15104 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15105 /// comma, etc
15106 
15107 // CheckICE - This function does the fundamental ICE checking: the returned
15108 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15109 // and a (possibly null) SourceLocation indicating the location of the problem.
15110 //
15111 // Note that to reduce code duplication, this helper does no evaluation
15112 // itself; the caller checks whether the expression is evaluatable, and
15113 // in the rare cases where CheckICE actually cares about the evaluated
15114 // value, it calls into Evaluate.
15115 
15116 namespace {
15117 
15118 enum ICEKind {
15119   /// This expression is an ICE.
15120   IK_ICE,
15121   /// This expression is not an ICE, but if it isn't evaluated, it's
15122   /// a legal subexpression for an ICE. This return value is used to handle
15123   /// the comma operator in C99 mode, and non-constant subexpressions.
15124   IK_ICEIfUnevaluated,
15125   /// This expression is not an ICE, and is not a legal subexpression for one.
15126   IK_NotICE
15127 };
15128 
15129 struct ICEDiag {
15130   ICEKind Kind;
15131   SourceLocation Loc;
15132 
15133   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15134 };
15135 
15136 }
15137 
15138 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15139 
15140 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15141 
15142 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15143   Expr::EvalResult EVResult;
15144   Expr::EvalStatus Status;
15145   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15146 
15147   Info.InConstantContext = true;
15148   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15149       !EVResult.Val.isInt())
15150     return ICEDiag(IK_NotICE, E->getBeginLoc());
15151 
15152   return NoDiag();
15153 }
15154 
15155 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15156   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15157   if (!E->getType()->isIntegralOrEnumerationType())
15158     return ICEDiag(IK_NotICE, E->getBeginLoc());
15159 
15160   switch (E->getStmtClass()) {
15161 #define ABSTRACT_STMT(Node)
15162 #define STMT(Node, Base) case Expr::Node##Class:
15163 #define EXPR(Node, Base)
15164 #include "clang/AST/StmtNodes.inc"
15165   case Expr::PredefinedExprClass:
15166   case Expr::FloatingLiteralClass:
15167   case Expr::ImaginaryLiteralClass:
15168   case Expr::StringLiteralClass:
15169   case Expr::ArraySubscriptExprClass:
15170   case Expr::MatrixSubscriptExprClass:
15171   case Expr::OMPArraySectionExprClass:
15172   case Expr::OMPArrayShapingExprClass:
15173   case Expr::OMPIteratorExprClass:
15174   case Expr::MemberExprClass:
15175   case Expr::CompoundAssignOperatorClass:
15176   case Expr::CompoundLiteralExprClass:
15177   case Expr::ExtVectorElementExprClass:
15178   case Expr::DesignatedInitExprClass:
15179   case Expr::ArrayInitLoopExprClass:
15180   case Expr::ArrayInitIndexExprClass:
15181   case Expr::NoInitExprClass:
15182   case Expr::DesignatedInitUpdateExprClass:
15183   case Expr::ImplicitValueInitExprClass:
15184   case Expr::ParenListExprClass:
15185   case Expr::VAArgExprClass:
15186   case Expr::AddrLabelExprClass:
15187   case Expr::StmtExprClass:
15188   case Expr::CXXMemberCallExprClass:
15189   case Expr::CUDAKernelCallExprClass:
15190   case Expr::CXXAddrspaceCastExprClass:
15191   case Expr::CXXDynamicCastExprClass:
15192   case Expr::CXXTypeidExprClass:
15193   case Expr::CXXUuidofExprClass:
15194   case Expr::MSPropertyRefExprClass:
15195   case Expr::MSPropertySubscriptExprClass:
15196   case Expr::CXXNullPtrLiteralExprClass:
15197   case Expr::UserDefinedLiteralClass:
15198   case Expr::CXXThisExprClass:
15199   case Expr::CXXThrowExprClass:
15200   case Expr::CXXNewExprClass:
15201   case Expr::CXXDeleteExprClass:
15202   case Expr::CXXPseudoDestructorExprClass:
15203   case Expr::UnresolvedLookupExprClass:
15204   case Expr::TypoExprClass:
15205   case Expr::RecoveryExprClass:
15206   case Expr::DependentScopeDeclRefExprClass:
15207   case Expr::CXXConstructExprClass:
15208   case Expr::CXXInheritedCtorInitExprClass:
15209   case Expr::CXXStdInitializerListExprClass:
15210   case Expr::CXXBindTemporaryExprClass:
15211   case Expr::ExprWithCleanupsClass:
15212   case Expr::CXXTemporaryObjectExprClass:
15213   case Expr::CXXUnresolvedConstructExprClass:
15214   case Expr::CXXDependentScopeMemberExprClass:
15215   case Expr::UnresolvedMemberExprClass:
15216   case Expr::ObjCStringLiteralClass:
15217   case Expr::ObjCBoxedExprClass:
15218   case Expr::ObjCArrayLiteralClass:
15219   case Expr::ObjCDictionaryLiteralClass:
15220   case Expr::ObjCEncodeExprClass:
15221   case Expr::ObjCMessageExprClass:
15222   case Expr::ObjCSelectorExprClass:
15223   case Expr::ObjCProtocolExprClass:
15224   case Expr::ObjCIvarRefExprClass:
15225   case Expr::ObjCPropertyRefExprClass:
15226   case Expr::ObjCSubscriptRefExprClass:
15227   case Expr::ObjCIsaExprClass:
15228   case Expr::ObjCAvailabilityCheckExprClass:
15229   case Expr::ShuffleVectorExprClass:
15230   case Expr::ConvertVectorExprClass:
15231   case Expr::BlockExprClass:
15232   case Expr::NoStmtClass:
15233   case Expr::OpaqueValueExprClass:
15234   case Expr::PackExpansionExprClass:
15235   case Expr::SubstNonTypeTemplateParmPackExprClass:
15236   case Expr::FunctionParmPackExprClass:
15237   case Expr::AsTypeExprClass:
15238   case Expr::ObjCIndirectCopyRestoreExprClass:
15239   case Expr::MaterializeTemporaryExprClass:
15240   case Expr::PseudoObjectExprClass:
15241   case Expr::AtomicExprClass:
15242   case Expr::LambdaExprClass:
15243   case Expr::CXXFoldExprClass:
15244   case Expr::CoawaitExprClass:
15245   case Expr::DependentCoawaitExprClass:
15246   case Expr::CoyieldExprClass:
15247   case Expr::SYCLUniqueStableNameExprClass:
15248     return ICEDiag(IK_NotICE, E->getBeginLoc());
15249 
15250   case Expr::InitListExprClass: {
15251     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15252     // form "T x = { a };" is equivalent to "T x = a;".
15253     // Unless we're initializing a reference, T is a scalar as it is known to be
15254     // of integral or enumeration type.
15255     if (E->isPRValue())
15256       if (cast<InitListExpr>(E)->getNumInits() == 1)
15257         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15258     return ICEDiag(IK_NotICE, E->getBeginLoc());
15259   }
15260 
15261   case Expr::SizeOfPackExprClass:
15262   case Expr::GNUNullExprClass:
15263   case Expr::SourceLocExprClass:
15264     return NoDiag();
15265 
15266   case Expr::SubstNonTypeTemplateParmExprClass:
15267     return
15268       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15269 
15270   case Expr::ConstantExprClass:
15271     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15272 
15273   case Expr::ParenExprClass:
15274     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15275   case Expr::GenericSelectionExprClass:
15276     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15277   case Expr::IntegerLiteralClass:
15278   case Expr::FixedPointLiteralClass:
15279   case Expr::CharacterLiteralClass:
15280   case Expr::ObjCBoolLiteralExprClass:
15281   case Expr::CXXBoolLiteralExprClass:
15282   case Expr::CXXScalarValueInitExprClass:
15283   case Expr::TypeTraitExprClass:
15284   case Expr::ConceptSpecializationExprClass:
15285   case Expr::RequiresExprClass:
15286   case Expr::ArrayTypeTraitExprClass:
15287   case Expr::ExpressionTraitExprClass:
15288   case Expr::CXXNoexceptExprClass:
15289     return NoDiag();
15290   case Expr::CallExprClass:
15291   case Expr::CXXOperatorCallExprClass: {
15292     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15293     // constant expressions, but they can never be ICEs because an ICE cannot
15294     // contain an operand of (pointer to) function type.
15295     const CallExpr *CE = cast<CallExpr>(E);
15296     if (CE->getBuiltinCallee())
15297       return CheckEvalInICE(E, Ctx);
15298     return ICEDiag(IK_NotICE, E->getBeginLoc());
15299   }
15300   case Expr::CXXRewrittenBinaryOperatorClass:
15301     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15302                     Ctx);
15303   case Expr::DeclRefExprClass: {
15304     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15305     if (isa<EnumConstantDecl>(D))
15306       return NoDiag();
15307 
15308     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15309     // integer variables in constant expressions:
15310     //
15311     // C++ 7.1.5.1p2
15312     //   A variable of non-volatile const-qualified integral or enumeration
15313     //   type initialized by an ICE can be used in ICEs.
15314     //
15315     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15316     // that mode, use of reference variables should not be allowed.
15317     const VarDecl *VD = dyn_cast<VarDecl>(D);
15318     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15319         !VD->getType()->isReferenceType())
15320       return NoDiag();
15321 
15322     return ICEDiag(IK_NotICE, E->getBeginLoc());
15323   }
15324   case Expr::UnaryOperatorClass: {
15325     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15326     switch (Exp->getOpcode()) {
15327     case UO_PostInc:
15328     case UO_PostDec:
15329     case UO_PreInc:
15330     case UO_PreDec:
15331     case UO_AddrOf:
15332     case UO_Deref:
15333     case UO_Coawait:
15334       // C99 6.6/3 allows increment and decrement within unevaluated
15335       // subexpressions of constant expressions, but they can never be ICEs
15336       // because an ICE cannot contain an lvalue operand.
15337       return ICEDiag(IK_NotICE, E->getBeginLoc());
15338     case UO_Extension:
15339     case UO_LNot:
15340     case UO_Plus:
15341     case UO_Minus:
15342     case UO_Not:
15343     case UO_Real:
15344     case UO_Imag:
15345       return CheckICE(Exp->getSubExpr(), Ctx);
15346     }
15347     llvm_unreachable("invalid unary operator class");
15348   }
15349   case Expr::OffsetOfExprClass: {
15350     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15351     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15352     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15353     // compliance: we should warn earlier for offsetof expressions with
15354     // array subscripts that aren't ICEs, and if the array subscripts
15355     // are ICEs, the value of the offsetof must be an integer constant.
15356     return CheckEvalInICE(E, Ctx);
15357   }
15358   case Expr::UnaryExprOrTypeTraitExprClass: {
15359     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15360     if ((Exp->getKind() ==  UETT_SizeOf) &&
15361         Exp->getTypeOfArgument()->isVariableArrayType())
15362       return ICEDiag(IK_NotICE, E->getBeginLoc());
15363     return NoDiag();
15364   }
15365   case Expr::BinaryOperatorClass: {
15366     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15367     switch (Exp->getOpcode()) {
15368     case BO_PtrMemD:
15369     case BO_PtrMemI:
15370     case BO_Assign:
15371     case BO_MulAssign:
15372     case BO_DivAssign:
15373     case BO_RemAssign:
15374     case BO_AddAssign:
15375     case BO_SubAssign:
15376     case BO_ShlAssign:
15377     case BO_ShrAssign:
15378     case BO_AndAssign:
15379     case BO_XorAssign:
15380     case BO_OrAssign:
15381       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15382       // constant expressions, but they can never be ICEs because an ICE cannot
15383       // contain an lvalue operand.
15384       return ICEDiag(IK_NotICE, E->getBeginLoc());
15385 
15386     case BO_Mul:
15387     case BO_Div:
15388     case BO_Rem:
15389     case BO_Add:
15390     case BO_Sub:
15391     case BO_Shl:
15392     case BO_Shr:
15393     case BO_LT:
15394     case BO_GT:
15395     case BO_LE:
15396     case BO_GE:
15397     case BO_EQ:
15398     case BO_NE:
15399     case BO_And:
15400     case BO_Xor:
15401     case BO_Or:
15402     case BO_Comma:
15403     case BO_Cmp: {
15404       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15405       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15406       if (Exp->getOpcode() == BO_Div ||
15407           Exp->getOpcode() == BO_Rem) {
15408         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15409         // we don't evaluate one.
15410         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15411           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15412           if (REval == 0)
15413             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15414           if (REval.isSigned() && REval.isAllOnes()) {
15415             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15416             if (LEval.isMinSignedValue())
15417               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15418           }
15419         }
15420       }
15421       if (Exp->getOpcode() == BO_Comma) {
15422         if (Ctx.getLangOpts().C99) {
15423           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15424           // if it isn't evaluated.
15425           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15426             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15427         } else {
15428           // In both C89 and C++, commas in ICEs are illegal.
15429           return ICEDiag(IK_NotICE, E->getBeginLoc());
15430         }
15431       }
15432       return Worst(LHSResult, RHSResult);
15433     }
15434     case BO_LAnd:
15435     case BO_LOr: {
15436       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15437       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15438       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15439         // Rare case where the RHS has a comma "side-effect"; we need
15440         // to actually check the condition to see whether the side
15441         // with the comma is evaluated.
15442         if ((Exp->getOpcode() == BO_LAnd) !=
15443             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15444           return RHSResult;
15445         return NoDiag();
15446       }
15447 
15448       return Worst(LHSResult, RHSResult);
15449     }
15450     }
15451     llvm_unreachable("invalid binary operator kind");
15452   }
15453   case Expr::ImplicitCastExprClass:
15454   case Expr::CStyleCastExprClass:
15455   case Expr::CXXFunctionalCastExprClass:
15456   case Expr::CXXStaticCastExprClass:
15457   case Expr::CXXReinterpretCastExprClass:
15458   case Expr::CXXConstCastExprClass:
15459   case Expr::ObjCBridgedCastExprClass: {
15460     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15461     if (isa<ExplicitCastExpr>(E)) {
15462       if (const FloatingLiteral *FL
15463             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15464         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15465         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15466         APSInt IgnoredVal(DestWidth, !DestSigned);
15467         bool Ignored;
15468         // If the value does not fit in the destination type, the behavior is
15469         // undefined, so we are not required to treat it as a constant
15470         // expression.
15471         if (FL->getValue().convertToInteger(IgnoredVal,
15472                                             llvm::APFloat::rmTowardZero,
15473                                             &Ignored) & APFloat::opInvalidOp)
15474           return ICEDiag(IK_NotICE, E->getBeginLoc());
15475         return NoDiag();
15476       }
15477     }
15478     switch (cast<CastExpr>(E)->getCastKind()) {
15479     case CK_LValueToRValue:
15480     case CK_AtomicToNonAtomic:
15481     case CK_NonAtomicToAtomic:
15482     case CK_NoOp:
15483     case CK_IntegralToBoolean:
15484     case CK_IntegralCast:
15485       return CheckICE(SubExpr, Ctx);
15486     default:
15487       return ICEDiag(IK_NotICE, E->getBeginLoc());
15488     }
15489   }
15490   case Expr::BinaryConditionalOperatorClass: {
15491     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15492     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15493     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15494     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15495     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15496     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15497     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15498         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15499     return FalseResult;
15500   }
15501   case Expr::ConditionalOperatorClass: {
15502     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15503     // If the condition (ignoring parens) is a __builtin_constant_p call,
15504     // then only the true side is actually considered in an integer constant
15505     // expression, and it is fully evaluated.  This is an important GNU
15506     // extension.  See GCC PR38377 for discussion.
15507     if (const CallExpr *CallCE
15508         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15509       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15510         return CheckEvalInICE(E, Ctx);
15511     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15512     if (CondResult.Kind == IK_NotICE)
15513       return CondResult;
15514 
15515     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15516     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15517 
15518     if (TrueResult.Kind == IK_NotICE)
15519       return TrueResult;
15520     if (FalseResult.Kind == IK_NotICE)
15521       return FalseResult;
15522     if (CondResult.Kind == IK_ICEIfUnevaluated)
15523       return CondResult;
15524     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15525       return NoDiag();
15526     // Rare case where the diagnostics depend on which side is evaluated
15527     // Note that if we get here, CondResult is 0, and at least one of
15528     // TrueResult and FalseResult is non-zero.
15529     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15530       return FalseResult;
15531     return TrueResult;
15532   }
15533   case Expr::CXXDefaultArgExprClass:
15534     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15535   case Expr::CXXDefaultInitExprClass:
15536     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15537   case Expr::ChooseExprClass: {
15538     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15539   }
15540   case Expr::BuiltinBitCastExprClass: {
15541     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15542       return ICEDiag(IK_NotICE, E->getBeginLoc());
15543     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15544   }
15545   }
15546 
15547   llvm_unreachable("Invalid StmtClass!");
15548 }
15549 
15550 /// Evaluate an expression as a C++11 integral constant expression.
15551 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15552                                                     const Expr *E,
15553                                                     llvm::APSInt *Value,
15554                                                     SourceLocation *Loc) {
15555   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15556     if (Loc) *Loc = E->getExprLoc();
15557     return false;
15558   }
15559 
15560   APValue Result;
15561   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15562     return false;
15563 
15564   if (!Result.isInt()) {
15565     if (Loc) *Loc = E->getExprLoc();
15566     return false;
15567   }
15568 
15569   if (Value) *Value = Result.getInt();
15570   return true;
15571 }
15572 
15573 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15574                                  SourceLocation *Loc) const {
15575   assert(!isValueDependent() &&
15576          "Expression evaluator can't be called on a dependent expression.");
15577 
15578   if (Ctx.getLangOpts().CPlusPlus11)
15579     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15580 
15581   ICEDiag D = CheckICE(this, Ctx);
15582   if (D.Kind != IK_ICE) {
15583     if (Loc) *Loc = D.Loc;
15584     return false;
15585   }
15586   return true;
15587 }
15588 
15589 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15590                                                     SourceLocation *Loc,
15591                                                     bool isEvaluated) const {
15592   if (isValueDependent()) {
15593     // Expression evaluator can't succeed on a dependent expression.
15594     return None;
15595   }
15596 
15597   APSInt Value;
15598 
15599   if (Ctx.getLangOpts().CPlusPlus11) {
15600     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15601       return Value;
15602     return None;
15603   }
15604 
15605   if (!isIntegerConstantExpr(Ctx, Loc))
15606     return None;
15607 
15608   // The only possible side-effects here are due to UB discovered in the
15609   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15610   // required to treat the expression as an ICE, so we produce the folded
15611   // value.
15612   EvalResult ExprResult;
15613   Expr::EvalStatus Status;
15614   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15615   Info.InConstantContext = true;
15616 
15617   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15618     llvm_unreachable("ICE cannot be evaluated!");
15619 
15620   return ExprResult.Val.getInt();
15621 }
15622 
15623 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15624   assert(!isValueDependent() &&
15625          "Expression evaluator can't be called on a dependent expression.");
15626 
15627   return CheckICE(this, Ctx).Kind == IK_ICE;
15628 }
15629 
15630 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15631                                SourceLocation *Loc) const {
15632   assert(!isValueDependent() &&
15633          "Expression evaluator can't be called on a dependent expression.");
15634 
15635   // We support this checking in C++98 mode in order to diagnose compatibility
15636   // issues.
15637   assert(Ctx.getLangOpts().CPlusPlus);
15638 
15639   // Build evaluation settings.
15640   Expr::EvalStatus Status;
15641   SmallVector<PartialDiagnosticAt, 8> Diags;
15642   Status.Diag = &Diags;
15643   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15644 
15645   APValue Scratch;
15646   bool IsConstExpr =
15647       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15648       // FIXME: We don't produce a diagnostic for this, but the callers that
15649       // call us on arbitrary full-expressions should generally not care.
15650       Info.discardCleanups() && !Status.HasSideEffects;
15651 
15652   if (!Diags.empty()) {
15653     IsConstExpr = false;
15654     if (Loc) *Loc = Diags[0].first;
15655   } else if (!IsConstExpr) {
15656     // FIXME: This shouldn't happen.
15657     if (Loc) *Loc = getExprLoc();
15658   }
15659 
15660   return IsConstExpr;
15661 }
15662 
15663 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15664                                     const FunctionDecl *Callee,
15665                                     ArrayRef<const Expr*> Args,
15666                                     const Expr *This) const {
15667   assert(!isValueDependent() &&
15668          "Expression evaluator can't be called on a dependent expression.");
15669 
15670   Expr::EvalStatus Status;
15671   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15672   Info.InConstantContext = true;
15673 
15674   LValue ThisVal;
15675   const LValue *ThisPtr = nullptr;
15676   if (This) {
15677 #ifndef NDEBUG
15678     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15679     assert(MD && "Don't provide `this` for non-methods.");
15680     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15681 #endif
15682     if (!This->isValueDependent() &&
15683         EvaluateObjectArgument(Info, This, ThisVal) &&
15684         !Info.EvalStatus.HasSideEffects)
15685       ThisPtr = &ThisVal;
15686 
15687     // Ignore any side-effects from a failed evaluation. This is safe because
15688     // they can't interfere with any other argument evaluation.
15689     Info.EvalStatus.HasSideEffects = false;
15690   }
15691 
15692   CallRef Call = Info.CurrentCall->createCall(Callee);
15693   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15694        I != E; ++I) {
15695     unsigned Idx = I - Args.begin();
15696     if (Idx >= Callee->getNumParams())
15697       break;
15698     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15699     if ((*I)->isValueDependent() ||
15700         !EvaluateCallArg(PVD, *I, Call, Info) ||
15701         Info.EvalStatus.HasSideEffects) {
15702       // If evaluation fails, throw away the argument entirely.
15703       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15704         *Slot = APValue();
15705     }
15706 
15707     // Ignore any side-effects from a failed evaluation. This is safe because
15708     // they can't interfere with any other argument evaluation.
15709     Info.EvalStatus.HasSideEffects = false;
15710   }
15711 
15712   // Parameter cleanups happen in the caller and are not part of this
15713   // evaluation.
15714   Info.discardCleanups();
15715   Info.EvalStatus.HasSideEffects = false;
15716 
15717   // Build fake call to Callee.
15718   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15719   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15720   FullExpressionRAII Scope(Info);
15721   return Evaluate(Value, Info, this) && Scope.destroy() &&
15722          !Info.EvalStatus.HasSideEffects;
15723 }
15724 
15725 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15726                                    SmallVectorImpl<
15727                                      PartialDiagnosticAt> &Diags) {
15728   // FIXME: It would be useful to check constexpr function templates, but at the
15729   // moment the constant expression evaluator cannot cope with the non-rigorous
15730   // ASTs which we build for dependent expressions.
15731   if (FD->isDependentContext())
15732     return true;
15733 
15734   Expr::EvalStatus Status;
15735   Status.Diag = &Diags;
15736 
15737   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15738   Info.InConstantContext = true;
15739   Info.CheckingPotentialConstantExpression = true;
15740 
15741   // The constexpr VM attempts to compile all methods to bytecode here.
15742   if (Info.EnableNewConstInterp) {
15743     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15744     return Diags.empty();
15745   }
15746 
15747   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15748   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15749 
15750   // Fabricate an arbitrary expression on the stack and pretend that it
15751   // is a temporary being used as the 'this' pointer.
15752   LValue This;
15753   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15754   This.set({&VIE, Info.CurrentCall->Index});
15755 
15756   ArrayRef<const Expr*> Args;
15757 
15758   APValue Scratch;
15759   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15760     // Evaluate the call as a constant initializer, to allow the construction
15761     // of objects of non-literal types.
15762     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15763     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15764   } else {
15765     SourceLocation Loc = FD->getLocation();
15766     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15767                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15768   }
15769 
15770   return Diags.empty();
15771 }
15772 
15773 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15774                                               const FunctionDecl *FD,
15775                                               SmallVectorImpl<
15776                                                 PartialDiagnosticAt> &Diags) {
15777   assert(!E->isValueDependent() &&
15778          "Expression evaluator can't be called on a dependent expression.");
15779 
15780   Expr::EvalStatus Status;
15781   Status.Diag = &Diags;
15782 
15783   EvalInfo Info(FD->getASTContext(), Status,
15784                 EvalInfo::EM_ConstantExpressionUnevaluated);
15785   Info.InConstantContext = true;
15786   Info.CheckingPotentialConstantExpression = true;
15787 
15788   // Fabricate a call stack frame to give the arguments a plausible cover story.
15789   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15790 
15791   APValue ResultScratch;
15792   Evaluate(ResultScratch, Info, E);
15793   return Diags.empty();
15794 }
15795 
15796 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15797                                  unsigned Type) const {
15798   if (!getType()->isPointerType())
15799     return false;
15800 
15801   Expr::EvalStatus Status;
15802   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15803   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15804 }
15805 
15806 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15807                                   EvalInfo &Info) {
15808   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15809     return false;
15810 
15811   LValue String;
15812 
15813   if (!EvaluatePointer(E, String, Info))
15814     return false;
15815 
15816   QualType CharTy = E->getType()->getPointeeType();
15817 
15818   // Fast path: if it's a string literal, search the string value.
15819   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15820           String.getLValueBase().dyn_cast<const Expr *>())) {
15821     StringRef Str = S->getBytes();
15822     int64_t Off = String.Offset.getQuantity();
15823     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15824         S->getCharByteWidth() == 1 &&
15825         // FIXME: Add fast-path for wchar_t too.
15826         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15827       Str = Str.substr(Off);
15828 
15829       StringRef::size_type Pos = Str.find(0);
15830       if (Pos != StringRef::npos)
15831         Str = Str.substr(0, Pos);
15832 
15833       Result = Str.size();
15834       return true;
15835     }
15836 
15837     // Fall through to slow path.
15838   }
15839 
15840   // Slow path: scan the bytes of the string looking for the terminating 0.
15841   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15842     APValue Char;
15843     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15844         !Char.isInt())
15845       return false;
15846     if (!Char.getInt()) {
15847       Result = Strlen;
15848       return true;
15849     }
15850     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15851       return false;
15852   }
15853 }
15854 
15855 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15856   Expr::EvalStatus Status;
15857   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15858   return EvaluateBuiltinStrLen(this, Result, Info);
15859 }
15860