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     if (!B) return QualType();
83     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
84       // FIXME: It's unclear where we're supposed to take the type from, and
85       // this actually matters for arrays of unknown bound. Eg:
86       //
87       // extern int arr[]; void f() { extern int arr[3]; };
88       // constexpr int *p = &arr[1]; // valid?
89       //
90       // For now, we take the array bound from the most recent declaration.
91       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
92            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
93         QualType T = Redecl->getType();
94         if (!T->isIncompleteArrayType())
95           return T;
96       }
97       return D->getType();
98     }
99 
100     if (B.is<TypeInfoLValue>())
101       return B.getTypeInfoType();
102 
103     if (B.is<DynamicAllocLValue>())
104       return B.getDynamicAllocType();
105 
106     const Expr *Base = B.get<const Expr*>();
107 
108     // For a materialized temporary, the type of the temporary we materialized
109     // may not be the type of the expression.
110     if (const MaterializeTemporaryExpr *MTE =
111             dyn_cast<MaterializeTemporaryExpr>(Base)) {
112       SmallVector<const Expr *, 2> CommaLHSs;
113       SmallVector<SubobjectAdjustment, 2> Adjustments;
114       const Expr *Temp = MTE->getSubExpr();
115       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
116                                                                Adjustments);
117       // Keep any cv-qualifiers from the reference if we generated a temporary
118       // for it directly. Otherwise use the type after adjustment.
119       if (!Adjustments.empty())
120         return Inner->getType();
121     }
122 
123     return Base->getType();
124   }
125 
126   /// Get an LValue path entry, which is known to not be an array index, as a
127   /// field declaration.
128   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
129     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
130   }
131   /// Get an LValue path entry, which is known to not be an array index, as a
132   /// base class declaration.
133   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
134     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
135   }
136   /// Determine whether this LValue path entry for a base class names a virtual
137   /// base class.
138   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
139     return E.getAsBaseOrMember().getInt();
140   }
141 
142   /// Given an expression, determine the type used to store the result of
143   /// evaluating that expression.
144   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
145     if (E->isRValue())
146       return E->getType();
147     return Ctx.getLValueReferenceType(E->getType());
148   }
149 
150   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
151   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
152     const FunctionDecl *Callee = CE->getDirectCallee();
153     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
154   }
155 
156   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
157   /// This will look through a single cast.
158   ///
159   /// Returns null if we couldn't unwrap a function with alloc_size.
160   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
161     if (!E->getType()->isPointerType())
162       return nullptr;
163 
164     E = E->IgnoreParens();
165     // If we're doing a variable assignment from e.g. malloc(N), there will
166     // probably be a cast of some kind. In exotic cases, we might also see a
167     // top-level ExprWithCleanups. Ignore them either way.
168     if (const auto *FE = dyn_cast<FullExpr>(E))
169       E = FE->getSubExpr()->IgnoreParens();
170 
171     if (const auto *Cast = dyn_cast<CastExpr>(E))
172       E = Cast->getSubExpr()->IgnoreParens();
173 
174     if (const auto *CE = dyn_cast<CallExpr>(E))
175       return getAllocSizeAttr(CE) ? CE : nullptr;
176     return nullptr;
177   }
178 
179   /// Determines whether or not the given Base contains a call to a function
180   /// with the alloc_size attribute.
181   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
182     const auto *E = Base.dyn_cast<const Expr *>();
183     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
184   }
185 
186   /// The bound to claim that an array of unknown bound has.
187   /// The value in MostDerivedArraySize is undefined in this case. So, set it
188   /// to an arbitrary value that's likely to loudly break things if it's used.
189   static const uint64_t AssumedSizeForUnsizedArray =
190       std::numeric_limits<uint64_t>::max() / 2;
191 
192   /// Determines if an LValue with the given LValueBase will have an unsized
193   /// array in its designator.
194   /// Find the path length and type of the most-derived subobject in the given
195   /// path, and find the size of the containing array, if any.
196   static unsigned
197   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
198                            ArrayRef<APValue::LValuePathEntry> Path,
199                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
200                            bool &FirstEntryIsUnsizedArray) {
201     // This only accepts LValueBases from APValues, and APValues don't support
202     // arrays that lack size info.
203     assert(!isBaseAnAllocSizeCall(Base) &&
204            "Unsized arrays shouldn't appear here");
205     unsigned MostDerivedLength = 0;
206     Type = getType(Base);
207 
208     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
209       if (Type->isArrayType()) {
210         const ArrayType *AT = Ctx.getAsArrayType(Type);
211         Type = AT->getElementType();
212         MostDerivedLength = I + 1;
213         IsArray = true;
214 
215         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
216           ArraySize = CAT->getSize().getZExtValue();
217         } else {
218           assert(I == 0 && "unexpected unsized array designator");
219           FirstEntryIsUnsizedArray = true;
220           ArraySize = AssumedSizeForUnsizedArray;
221         }
222       } else if (Type->isAnyComplexType()) {
223         const ComplexType *CT = Type->castAs<ComplexType>();
224         Type = CT->getElementType();
225         ArraySize = 2;
226         MostDerivedLength = I + 1;
227         IsArray = true;
228       } else if (const FieldDecl *FD = getAsField(Path[I])) {
229         Type = FD->getType();
230         ArraySize = 0;
231         MostDerivedLength = I + 1;
232         IsArray = false;
233       } else {
234         // Path[I] describes a base class.
235         ArraySize = 0;
236         IsArray = false;
237       }
238     }
239     return MostDerivedLength;
240   }
241 
242   /// A path from a glvalue to a subobject of that glvalue.
243   struct SubobjectDesignator {
244     /// True if the subobject was named in a manner not supported by C++11. Such
245     /// lvalues can still be folded, but they are not core constant expressions
246     /// and we cannot perform lvalue-to-rvalue conversions on them.
247     unsigned Invalid : 1;
248 
249     /// Is this a pointer one past the end of an object?
250     unsigned IsOnePastTheEnd : 1;
251 
252     /// Indicator of whether the first entry is an unsized array.
253     unsigned FirstEntryIsAnUnsizedArray : 1;
254 
255     /// Indicator of whether the most-derived object is an array element.
256     unsigned MostDerivedIsArrayElement : 1;
257 
258     /// The length of the path to the most-derived object of which this is a
259     /// subobject.
260     unsigned MostDerivedPathLength : 28;
261 
262     /// The size of the array of which the most-derived object is an element.
263     /// This will always be 0 if the most-derived object is not an array
264     /// element. 0 is not an indicator of whether or not the most-derived object
265     /// is an array, however, because 0-length arrays are allowed.
266     ///
267     /// If the current array is an unsized array, the value of this is
268     /// undefined.
269     uint64_t MostDerivedArraySize;
270 
271     /// The type of the most derived object referred to by this address.
272     QualType MostDerivedType;
273 
274     typedef APValue::LValuePathEntry PathEntry;
275 
276     /// The entries on the path from the glvalue to the designated subobject.
277     SmallVector<PathEntry, 8> Entries;
278 
279     SubobjectDesignator() : Invalid(true) {}
280 
281     explicit SubobjectDesignator(QualType T)
282         : Invalid(false), IsOnePastTheEnd(false),
283           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
284           MostDerivedPathLength(0), MostDerivedArraySize(0),
285           MostDerivedType(T) {}
286 
287     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
288         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
289           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
290           MostDerivedPathLength(0), MostDerivedArraySize(0) {
291       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
292       if (!Invalid) {
293         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
294         ArrayRef<PathEntry> VEntries = V.getLValuePath();
295         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
296         if (V.getLValueBase()) {
297           bool IsArray = false;
298           bool FirstIsUnsizedArray = false;
299           MostDerivedPathLength = findMostDerivedSubobject(
300               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
301               MostDerivedType, IsArray, FirstIsUnsizedArray);
302           MostDerivedIsArrayElement = IsArray;
303           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
304         }
305       }
306     }
307 
308     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
309                   unsigned NewLength) {
310       if (Invalid)
311         return;
312 
313       assert(Base && "cannot truncate path for null pointer");
314       assert(NewLength <= Entries.size() && "not a truncation");
315 
316       if (NewLength == Entries.size())
317         return;
318       Entries.resize(NewLength);
319 
320       bool IsArray = false;
321       bool FirstIsUnsizedArray = false;
322       MostDerivedPathLength = findMostDerivedSubobject(
323           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
324           FirstIsUnsizedArray);
325       MostDerivedIsArrayElement = IsArray;
326       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
327     }
328 
329     void setInvalid() {
330       Invalid = true;
331       Entries.clear();
332     }
333 
334     /// Determine whether the most derived subobject is an array without a
335     /// known bound.
336     bool isMostDerivedAnUnsizedArray() const {
337       assert(!Invalid && "Calling this makes no sense on invalid designators");
338       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
339     }
340 
341     /// Determine what the most derived array's size is. Results in an assertion
342     /// failure if the most derived array lacks a size.
343     uint64_t getMostDerivedArraySize() const {
344       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
345       return MostDerivedArraySize;
346     }
347 
348     /// Determine whether this is a one-past-the-end pointer.
349     bool isOnePastTheEnd() const {
350       assert(!Invalid);
351       if (IsOnePastTheEnd)
352         return true;
353       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
354           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
355               MostDerivedArraySize)
356         return true;
357       return false;
358     }
359 
360     /// Get the range of valid index adjustments in the form
361     ///   {maximum value that can be subtracted from this pointer,
362     ///    maximum value that can be added to this pointer}
363     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
364       if (Invalid || isMostDerivedAnUnsizedArray())
365         return {0, 0};
366 
367       // [expr.add]p4: For the purposes of these operators, a pointer to a
368       // nonarray object behaves the same as a pointer to the first element of
369       // an array of length one with the type of the object as its element type.
370       bool IsArray = MostDerivedPathLength == Entries.size() &&
371                      MostDerivedIsArrayElement;
372       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
373                                     : (uint64_t)IsOnePastTheEnd;
374       uint64_t ArraySize =
375           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376       return {ArrayIndex, ArraySize - ArrayIndex};
377     }
378 
379     /// Check that this refers to a valid subobject.
380     bool isValidSubobject() const {
381       if (Invalid)
382         return false;
383       return !isOnePastTheEnd();
384     }
385     /// Check that this refers to a valid subobject, and if not, produce a
386     /// relevant diagnostic and set the designator as invalid.
387     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
388 
389     /// Get the type of the designated object.
390     QualType getType(ASTContext &Ctx) const {
391       assert(!Invalid && "invalid designator has no subobject type");
392       return MostDerivedPathLength == Entries.size()
393                  ? MostDerivedType
394                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
395     }
396 
397     /// Update this designator to refer to the first element within this array.
398     void addArrayUnchecked(const ConstantArrayType *CAT) {
399       Entries.push_back(PathEntry::ArrayIndex(0));
400 
401       // This is a most-derived object.
402       MostDerivedType = CAT->getElementType();
403       MostDerivedIsArrayElement = true;
404       MostDerivedArraySize = CAT->getSize().getZExtValue();
405       MostDerivedPathLength = Entries.size();
406     }
407     /// Update this designator to refer to the first element within the array of
408     /// elements of type T. This is an array of unknown size.
409     void addUnsizedArrayUnchecked(QualType ElemTy) {
410       Entries.push_back(PathEntry::ArrayIndex(0));
411 
412       MostDerivedType = ElemTy;
413       MostDerivedIsArrayElement = true;
414       // The value in MostDerivedArraySize is undefined in this case. So, set it
415       // to an arbitrary value that's likely to loudly break things if it's
416       // used.
417       MostDerivedArraySize = AssumedSizeForUnsizedArray;
418       MostDerivedPathLength = Entries.size();
419     }
420     /// Update this designator to refer to the given base or member of this
421     /// object.
422     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
423       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
424 
425       // If this isn't a base class, it's a new most-derived object.
426       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
427         MostDerivedType = FD->getType();
428         MostDerivedIsArrayElement = false;
429         MostDerivedArraySize = 0;
430         MostDerivedPathLength = Entries.size();
431       }
432     }
433     /// Update this designator to refer to the given complex component.
434     void addComplexUnchecked(QualType EltTy, bool Imag) {
435       Entries.push_back(PathEntry::ArrayIndex(Imag));
436 
437       // This is technically a most-derived object, though in practice this
438       // is unlikely to matter.
439       MostDerivedType = EltTy;
440       MostDerivedIsArrayElement = true;
441       MostDerivedArraySize = 2;
442       MostDerivedPathLength = Entries.size();
443     }
444     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
445     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
446                                    const APSInt &N);
447     /// Add N to the address of this subobject.
448     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
449       if (Invalid || !N) return;
450       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
451       if (isMostDerivedAnUnsizedArray()) {
452         diagnoseUnsizedArrayPointerArithmetic(Info, E);
453         // Can't verify -- trust that the user is doing the right thing (or if
454         // not, trust that the caller will catch the bad behavior).
455         // FIXME: Should we reject if this overflows, at least?
456         Entries.back() = PathEntry::ArrayIndex(
457             Entries.back().getAsArrayIndex() + TruncatedN);
458         return;
459       }
460 
461       // [expr.add]p4: For the purposes of these operators, a pointer to a
462       // nonarray object behaves the same as a pointer to the first element of
463       // an array of length one with the type of the object as its element type.
464       bool IsArray = MostDerivedPathLength == Entries.size() &&
465                      MostDerivedIsArrayElement;
466       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
467                                     : (uint64_t)IsOnePastTheEnd;
468       uint64_t ArraySize =
469           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
470 
471       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
472         // Calculate the actual index in a wide enough type, so we can include
473         // it in the note.
474         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
475         (llvm::APInt&)N += ArrayIndex;
476         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
477         diagnosePointerArithmetic(Info, E, N);
478         setInvalid();
479         return;
480       }
481 
482       ArrayIndex += TruncatedN;
483       assert(ArrayIndex <= ArraySize &&
484              "bounds check succeeded for out-of-bounds index");
485 
486       if (IsArray)
487         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
488       else
489         IsOnePastTheEnd = (ArrayIndex != 0);
490     }
491   };
492 
493   /// A stack frame in the constexpr call stack.
494   class CallStackFrame : public interp::Frame {
495   public:
496     EvalInfo &Info;
497 
498     /// Parent - The caller of this stack frame.
499     CallStackFrame *Caller;
500 
501     /// Callee - The function which was called.
502     const FunctionDecl *Callee;
503 
504     /// This - The binding for the this pointer in this call, if any.
505     const LValue *This;
506 
507     /// Arguments - Parameter bindings for this function call, indexed by
508     /// parameters' function scope indices.
509     APValue *Arguments;
510 
511     /// Source location information about the default argument or default
512     /// initializer expression we're evaluating, if any.
513     CurrentSourceLocExprScope CurSourceLocExprScope;
514 
515     // Note that we intentionally use std::map here so that references to
516     // values are stable.
517     typedef std::pair<const void *, unsigned> MapKeyTy;
518     typedef std::map<MapKeyTy, APValue> MapTy;
519     /// Temporaries - Temporary lvalues materialized within this stack frame.
520     MapTy Temporaries;
521 
522     /// CallLoc - The location of the call expression for this call.
523     SourceLocation CallLoc;
524 
525     /// Index - The call index of this call.
526     unsigned Index;
527 
528     /// The stack of integers for tracking version numbers for temporaries.
529     SmallVector<unsigned, 2> TempVersionStack = {1};
530     unsigned CurTempVersion = TempVersionStack.back();
531 
532     unsigned getTempVersion() const { return TempVersionStack.back(); }
533 
534     void pushTempVersion() {
535       TempVersionStack.push_back(++CurTempVersion);
536     }
537 
538     void popTempVersion() {
539       TempVersionStack.pop_back();
540     }
541 
542     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
543     // on the overall stack usage of deeply-recursing constexpr evaluations.
544     // (We should cache this map rather than recomputing it repeatedly.)
545     // But let's try this and see how it goes; we can look into caching the map
546     // as a later change.
547 
548     /// LambdaCaptureFields - Mapping from captured variables/this to
549     /// corresponding data members in the closure class.
550     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
551     FieldDecl *LambdaThisCaptureField;
552 
553     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
554                    const FunctionDecl *Callee, const LValue *This,
555                    APValue *Arguments);
556     ~CallStackFrame();
557 
558     // Return the temporary for Key whose version number is Version.
559     APValue *getTemporary(const void *Key, unsigned Version) {
560       MapKeyTy KV(Key, Version);
561       auto LB = Temporaries.lower_bound(KV);
562       if (LB != Temporaries.end() && LB->first == KV)
563         return &LB->second;
564       // Pair (Key,Version) wasn't found in the map. Check that no elements
565       // in the map have 'Key' as their key.
566       assert((LB == Temporaries.end() || LB->first.first != Key) &&
567              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
568              "Element with key 'Key' found in map");
569       return nullptr;
570     }
571 
572     // Return the current temporary for Key in the map.
573     APValue *getCurrentTemporary(const void *Key) {
574       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
575       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
576         return &std::prev(UB)->second;
577       return nullptr;
578     }
579 
580     // Return the version number of the current temporary for Key.
581     unsigned getCurrentTemporaryVersion(const void *Key) const {
582       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
583       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
584         return std::prev(UB)->first.second;
585       return 0;
586     }
587 
588     /// Allocate storage for an object of type T in this stack frame.
589     /// Populates LV with a handle to the created object. Key identifies
590     /// the temporary within the stack frame, and must not be reused without
591     /// bumping the temporary version number.
592     template<typename KeyT>
593     APValue &createTemporary(const KeyT *Key, QualType T,
594                              bool IsLifetimeExtended, LValue &LV);
595 
596     void describe(llvm::raw_ostream &OS) override;
597 
598     Frame *getCaller() const override { return Caller; }
599     SourceLocation getCallLocation() const override { return CallLoc; }
600     const FunctionDecl *getCallee() const override { return Callee; }
601 
602     bool isStdFunction() const {
603       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
604         if (DC->isStdNamespace())
605           return true;
606       return false;
607     }
608   };
609 
610   /// Temporarily override 'this'.
611   class ThisOverrideRAII {
612   public:
613     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
614         : Frame(Frame), OldThis(Frame.This) {
615       if (Enable)
616         Frame.This = NewThis;
617     }
618     ~ThisOverrideRAII() {
619       Frame.This = OldThis;
620     }
621   private:
622     CallStackFrame &Frame;
623     const LValue *OldThis;
624   };
625 }
626 
627 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
628                               const LValue &This, QualType ThisType);
629 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
630                               APValue::LValueBase LVBase, APValue &Value,
631                               QualType T);
632 
633 namespace {
634   /// A cleanup, and a flag indicating whether it is lifetime-extended.
635   class Cleanup {
636     llvm::PointerIntPair<APValue*, 1, bool> Value;
637     APValue::LValueBase Base;
638     QualType T;
639 
640   public:
641     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
642             bool IsLifetimeExtended)
643         : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
644 
645     bool isLifetimeExtended() const { return Value.getInt(); }
646     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
647       if (RunDestructors) {
648         SourceLocation Loc;
649         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
650           Loc = VD->getLocation();
651         else if (const Expr *E = Base.dyn_cast<const Expr*>())
652           Loc = E->getExprLoc();
653         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
654       }
655       *Value.getPointer() = APValue();
656       return true;
657     }
658 
659     bool hasSideEffect() {
660       return T.isDestructedType();
661     }
662   };
663 
664   /// A reference to an object whose construction we are currently evaluating.
665   struct ObjectUnderConstruction {
666     APValue::LValueBase Base;
667     ArrayRef<APValue::LValuePathEntry> Path;
668     friend bool operator==(const ObjectUnderConstruction &LHS,
669                            const ObjectUnderConstruction &RHS) {
670       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
671     }
672     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
673       return llvm::hash_combine(Obj.Base, Obj.Path);
674     }
675   };
676   enum class ConstructionPhase {
677     None,
678     Bases,
679     AfterBases,
680     AfterFields,
681     Destroying,
682     DestroyingBases
683   };
684 }
685 
686 namespace llvm {
687 template<> struct DenseMapInfo<ObjectUnderConstruction> {
688   using Base = DenseMapInfo<APValue::LValueBase>;
689   static ObjectUnderConstruction getEmptyKey() {
690     return {Base::getEmptyKey(), {}}; }
691   static ObjectUnderConstruction getTombstoneKey() {
692     return {Base::getTombstoneKey(), {}};
693   }
694   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
695     return hash_value(Object);
696   }
697   static bool isEqual(const ObjectUnderConstruction &LHS,
698                       const ObjectUnderConstruction &RHS) {
699     return LHS == RHS;
700   }
701 };
702 }
703 
704 namespace {
705   /// A dynamically-allocated heap object.
706   struct DynAlloc {
707     /// The value of this heap-allocated object.
708     APValue Value;
709     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
710     /// or a CallExpr (the latter is for direct calls to operator new inside
711     /// std::allocator<T>::allocate).
712     const Expr *AllocExpr = nullptr;
713 
714     enum Kind {
715       New,
716       ArrayNew,
717       StdAllocator
718     };
719 
720     /// Get the kind of the allocation. This must match between allocation
721     /// and deallocation.
722     Kind getKind() const {
723       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
724         return NE->isArray() ? ArrayNew : New;
725       assert(isa<CallExpr>(AllocExpr));
726       return StdAllocator;
727     }
728   };
729 
730   struct DynAllocOrder {
731     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
732       return L.getIndex() < R.getIndex();
733     }
734   };
735 
736   /// EvalInfo - This is a private struct used by the evaluator to capture
737   /// information about a subexpression as it is folded.  It retains information
738   /// about the AST context, but also maintains information about the folded
739   /// expression.
740   ///
741   /// If an expression could be evaluated, it is still possible it is not a C
742   /// "integer constant expression" or constant expression.  If not, this struct
743   /// captures information about how and why not.
744   ///
745   /// One bit of information passed *into* the request for constant folding
746   /// indicates whether the subexpression is "evaluated" or not according to C
747   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
748   /// evaluate the expression regardless of what the RHS is, but C only allows
749   /// certain things in certain situations.
750   class EvalInfo : public interp::State {
751   public:
752     ASTContext &Ctx;
753 
754     /// EvalStatus - Contains information about the evaluation.
755     Expr::EvalStatus &EvalStatus;
756 
757     /// CurrentCall - The top of the constexpr call stack.
758     CallStackFrame *CurrentCall;
759 
760     /// CallStackDepth - The number of calls in the call stack right now.
761     unsigned CallStackDepth;
762 
763     /// NextCallIndex - The next call index to assign.
764     unsigned NextCallIndex;
765 
766     /// StepsLeft - The remaining number of evaluation steps we're permitted
767     /// to perform. This is essentially a limit for the number of statements
768     /// we will evaluate.
769     unsigned StepsLeft;
770 
771     /// Enable the experimental new constant interpreter. If an expression is
772     /// not supported by the interpreter, an error is triggered.
773     bool EnableNewConstInterp;
774 
775     /// BottomFrame - The frame in which evaluation started. This must be
776     /// initialized after CurrentCall and CallStackDepth.
777     CallStackFrame BottomFrame;
778 
779     /// A stack of values whose lifetimes end at the end of some surrounding
780     /// evaluation frame.
781     llvm::SmallVector<Cleanup, 16> CleanupStack;
782 
783     /// EvaluatingDecl - This is the declaration whose initializer is being
784     /// evaluated, if any.
785     APValue::LValueBase EvaluatingDecl;
786 
787     enum class EvaluatingDeclKind {
788       None,
789       /// We're evaluating the construction of EvaluatingDecl.
790       Ctor,
791       /// We're evaluating the destruction of EvaluatingDecl.
792       Dtor,
793     };
794     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
795 
796     /// EvaluatingDeclValue - This is the value being constructed for the
797     /// declaration whose initializer is being evaluated, if any.
798     APValue *EvaluatingDeclValue;
799 
800     /// Set of objects that are currently being constructed.
801     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
802         ObjectsUnderConstruction;
803 
804     /// Current heap allocations, along with the location where each was
805     /// allocated. We use std::map here because we need stable addresses
806     /// for the stored APValues.
807     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
808 
809     /// The number of heap allocations performed so far in this evaluation.
810     unsigned NumHeapAllocs = 0;
811 
812     struct EvaluatingConstructorRAII {
813       EvalInfo &EI;
814       ObjectUnderConstruction Object;
815       bool DidInsert;
816       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
817                                 bool HasBases)
818           : EI(EI), Object(Object) {
819         DidInsert =
820             EI.ObjectsUnderConstruction
821                 .insert({Object, HasBases ? ConstructionPhase::Bases
822                                           : ConstructionPhase::AfterBases})
823                 .second;
824       }
825       void finishedConstructingBases() {
826         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
827       }
828       void finishedConstructingFields() {
829         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
830       }
831       ~EvaluatingConstructorRAII() {
832         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
833       }
834     };
835 
836     struct EvaluatingDestructorRAII {
837       EvalInfo &EI;
838       ObjectUnderConstruction Object;
839       bool DidInsert;
840       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
841           : EI(EI), Object(Object) {
842         DidInsert = EI.ObjectsUnderConstruction
843                         .insert({Object, ConstructionPhase::Destroying})
844                         .second;
845       }
846       void startedDestroyingBases() {
847         EI.ObjectsUnderConstruction[Object] =
848             ConstructionPhase::DestroyingBases;
849       }
850       ~EvaluatingDestructorRAII() {
851         if (DidInsert)
852           EI.ObjectsUnderConstruction.erase(Object);
853       }
854     };
855 
856     ConstructionPhase
857     isEvaluatingCtorDtor(APValue::LValueBase Base,
858                          ArrayRef<APValue::LValuePathEntry> Path) {
859       return ObjectsUnderConstruction.lookup({Base, Path});
860     }
861 
862     /// If we're currently speculatively evaluating, the outermost call stack
863     /// depth at which we can mutate state, otherwise 0.
864     unsigned SpeculativeEvaluationDepth = 0;
865 
866     /// The current array initialization index, if we're performing array
867     /// initialization.
868     uint64_t ArrayInitIndex = -1;
869 
870     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
871     /// notes attached to it will also be stored, otherwise they will not be.
872     bool HasActiveDiagnostic;
873 
874     /// Have we emitted a diagnostic explaining why we couldn't constant
875     /// fold (not just why it's not strictly a constant expression)?
876     bool HasFoldFailureDiagnostic;
877 
878     /// Whether or not we're in a context where the front end requires a
879     /// constant value.
880     bool InConstantContext;
881 
882     /// Whether we're checking that an expression is a potential constant
883     /// expression. If so, do not fail on constructs that could become constant
884     /// later on (such as a use of an undefined global).
885     bool CheckingPotentialConstantExpression = false;
886 
887     /// Whether we're checking for an expression that has undefined behavior.
888     /// If so, we will produce warnings if we encounter an operation that is
889     /// always undefined.
890     bool CheckingForUndefinedBehavior = false;
891 
892     enum EvaluationMode {
893       /// Evaluate as a constant expression. Stop if we find that the expression
894       /// is not a constant expression.
895       EM_ConstantExpression,
896 
897       /// Evaluate as a constant expression. Stop if we find that the expression
898       /// is not a constant expression. Some expressions can be retried in the
899       /// optimizer if we don't constant fold them here, but in an unevaluated
900       /// context we try to fold them immediately since the optimizer never
901       /// gets a chance to look at it.
902       EM_ConstantExpressionUnevaluated,
903 
904       /// Fold the expression to a constant. Stop if we hit a side-effect that
905       /// we can't model.
906       EM_ConstantFold,
907 
908       /// Evaluate in any way we know how. Don't worry about side-effects that
909       /// can't be modeled.
910       EM_IgnoreSideEffects,
911     } EvalMode;
912 
913     /// Are we checking whether the expression is a potential constant
914     /// expression?
915     bool checkingPotentialConstantExpression() const override  {
916       return CheckingPotentialConstantExpression;
917     }
918 
919     /// Are we checking an expression for overflow?
920     // FIXME: We should check for any kind of undefined or suspicious behavior
921     // in such constructs, not just overflow.
922     bool checkingForUndefinedBehavior() const override {
923       return CheckingForUndefinedBehavior;
924     }
925 
926     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
927         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
928           CallStackDepth(0), NextCallIndex(1),
929           StepsLeft(C.getLangOpts().ConstexprStepLimit),
930           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
931           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
932           EvaluatingDecl((const ValueDecl *)nullptr),
933           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
934           HasFoldFailureDiagnostic(false), InConstantContext(false),
935           EvalMode(Mode) {}
936 
937     ~EvalInfo() {
938       discardCleanups();
939     }
940 
941     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
942                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
943       EvaluatingDecl = Base;
944       IsEvaluatingDecl = EDK;
945       EvaluatingDeclValue = &Value;
946     }
947 
948     bool CheckCallLimit(SourceLocation Loc) {
949       // Don't perform any constexpr calls (other than the call we're checking)
950       // when checking a potential constant expression.
951       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
952         return false;
953       if (NextCallIndex == 0) {
954         // NextCallIndex has wrapped around.
955         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
956         return false;
957       }
958       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
959         return true;
960       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
961         << getLangOpts().ConstexprCallDepth;
962       return false;
963     }
964 
965     std::pair<CallStackFrame *, unsigned>
966     getCallFrameAndDepth(unsigned CallIndex) {
967       assert(CallIndex && "no call index in getCallFrameAndDepth");
968       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
969       // be null in this loop.
970       unsigned Depth = CallStackDepth;
971       CallStackFrame *Frame = CurrentCall;
972       while (Frame->Index > CallIndex) {
973         Frame = Frame->Caller;
974         --Depth;
975       }
976       if (Frame->Index == CallIndex)
977         return {Frame, Depth};
978       return {nullptr, 0};
979     }
980 
981     bool nextStep(const Stmt *S) {
982       if (!StepsLeft) {
983         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
984         return false;
985       }
986       --StepsLeft;
987       return true;
988     }
989 
990     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
991 
992     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
993       Optional<DynAlloc*> Result;
994       auto It = HeapAllocs.find(DA);
995       if (It != HeapAllocs.end())
996         Result = &It->second;
997       return Result;
998     }
999 
1000     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1001     struct StdAllocatorCaller {
1002       unsigned FrameIndex;
1003       QualType ElemType;
1004       explicit operator bool() const { return FrameIndex != 0; };
1005     };
1006 
1007     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1008       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1009            Call = Call->Caller) {
1010         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1011         if (!MD)
1012           continue;
1013         const IdentifierInfo *FnII = MD->getIdentifier();
1014         if (!FnII || !FnII->isStr(FnName))
1015           continue;
1016 
1017         const auto *CTSD =
1018             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1019         if (!CTSD)
1020           continue;
1021 
1022         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1023         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1024         if (CTSD->isInStdNamespace() && ClassII &&
1025             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1026             TAL[0].getKind() == TemplateArgument::Type)
1027           return {Call->Index, TAL[0].getAsType()};
1028       }
1029 
1030       return {};
1031     }
1032 
1033     void performLifetimeExtension() {
1034       // Disable the cleanups for lifetime-extended temporaries.
1035       CleanupStack.erase(
1036           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1037                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1038           CleanupStack.end());
1039      }
1040 
1041     /// Throw away any remaining cleanups at the end of evaluation. If any
1042     /// cleanups would have had a side-effect, note that as an unmodeled
1043     /// side-effect and return false. Otherwise, return true.
1044     bool discardCleanups() {
1045       for (Cleanup &C : CleanupStack) {
1046         if (C.hasSideEffect() && !noteSideEffect()) {
1047           CleanupStack.clear();
1048           return false;
1049         }
1050       }
1051       CleanupStack.clear();
1052       return true;
1053     }
1054 
1055   private:
1056     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1057     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1058 
1059     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1060     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1061 
1062     void setFoldFailureDiagnostic(bool Flag) override {
1063       HasFoldFailureDiagnostic = Flag;
1064     }
1065 
1066     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1067 
1068     ASTContext &getCtx() const override { return Ctx; }
1069 
1070     // If we have a prior diagnostic, it will be noting that the expression
1071     // isn't a constant expression. This diagnostic is more important,
1072     // unless we require this evaluation to produce a constant expression.
1073     //
1074     // FIXME: We might want to show both diagnostics to the user in
1075     // EM_ConstantFold mode.
1076     bool hasPriorDiagnostic() override {
1077       if (!EvalStatus.Diag->empty()) {
1078         switch (EvalMode) {
1079         case EM_ConstantFold:
1080         case EM_IgnoreSideEffects:
1081           if (!HasFoldFailureDiagnostic)
1082             break;
1083           // We've already failed to fold something. Keep that diagnostic.
1084           LLVM_FALLTHROUGH;
1085         case EM_ConstantExpression:
1086         case EM_ConstantExpressionUnevaluated:
1087           setActiveDiagnostic(false);
1088           return true;
1089         }
1090       }
1091       return false;
1092     }
1093 
1094     unsigned getCallStackDepth() override { return CallStackDepth; }
1095 
1096   public:
1097     /// Should we continue evaluation after encountering a side-effect that we
1098     /// couldn't model?
1099     bool keepEvaluatingAfterSideEffect() {
1100       switch (EvalMode) {
1101       case EM_IgnoreSideEffects:
1102         return true;
1103 
1104       case EM_ConstantExpression:
1105       case EM_ConstantExpressionUnevaluated:
1106       case EM_ConstantFold:
1107         // By default, assume any side effect might be valid in some other
1108         // evaluation of this expression from a different context.
1109         return checkingPotentialConstantExpression() ||
1110                checkingForUndefinedBehavior();
1111       }
1112       llvm_unreachable("Missed EvalMode case");
1113     }
1114 
1115     /// Note that we have had a side-effect, and determine whether we should
1116     /// keep evaluating.
1117     bool noteSideEffect() {
1118       EvalStatus.HasSideEffects = true;
1119       return keepEvaluatingAfterSideEffect();
1120     }
1121 
1122     /// Should we continue evaluation after encountering undefined behavior?
1123     bool keepEvaluatingAfterUndefinedBehavior() {
1124       switch (EvalMode) {
1125       case EM_IgnoreSideEffects:
1126       case EM_ConstantFold:
1127         return true;
1128 
1129       case EM_ConstantExpression:
1130       case EM_ConstantExpressionUnevaluated:
1131         return checkingForUndefinedBehavior();
1132       }
1133       llvm_unreachable("Missed EvalMode case");
1134     }
1135 
1136     /// Note that we hit something that was technically undefined behavior, but
1137     /// that we can evaluate past it (such as signed overflow or floating-point
1138     /// division by zero.)
1139     bool noteUndefinedBehavior() override {
1140       EvalStatus.HasUndefinedBehavior = true;
1141       return keepEvaluatingAfterUndefinedBehavior();
1142     }
1143 
1144     /// Should we continue evaluation as much as possible after encountering a
1145     /// construct which can't be reduced to a value?
1146     bool keepEvaluatingAfterFailure() const override {
1147       if (!StepsLeft)
1148         return false;
1149 
1150       switch (EvalMode) {
1151       case EM_ConstantExpression:
1152       case EM_ConstantExpressionUnevaluated:
1153       case EM_ConstantFold:
1154       case EM_IgnoreSideEffects:
1155         return checkingPotentialConstantExpression() ||
1156                checkingForUndefinedBehavior();
1157       }
1158       llvm_unreachable("Missed EvalMode case");
1159     }
1160 
1161     /// Notes that we failed to evaluate an expression that other expressions
1162     /// directly depend on, and determine if we should keep evaluating. This
1163     /// should only be called if we actually intend to keep evaluating.
1164     ///
1165     /// Call noteSideEffect() instead if we may be able to ignore the value that
1166     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1167     ///
1168     /// (Foo(), 1)      // use noteSideEffect
1169     /// (Foo() || true) // use noteSideEffect
1170     /// Foo() + 1       // use noteFailure
1171     LLVM_NODISCARD bool noteFailure() {
1172       // Failure when evaluating some expression often means there is some
1173       // subexpression whose evaluation was skipped. Therefore, (because we
1174       // don't track whether we skipped an expression when unwinding after an
1175       // evaluation failure) every evaluation failure that bubbles up from a
1176       // subexpression implies that a side-effect has potentially happened. We
1177       // skip setting the HasSideEffects flag to true until we decide to
1178       // continue evaluating after that point, which happens here.
1179       bool KeepGoing = keepEvaluatingAfterFailure();
1180       EvalStatus.HasSideEffects |= KeepGoing;
1181       return KeepGoing;
1182     }
1183 
1184     class ArrayInitLoopIndex {
1185       EvalInfo &Info;
1186       uint64_t OuterIndex;
1187 
1188     public:
1189       ArrayInitLoopIndex(EvalInfo &Info)
1190           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1191         Info.ArrayInitIndex = 0;
1192       }
1193       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1194 
1195       operator uint64_t&() { return Info.ArrayInitIndex; }
1196     };
1197   };
1198 
1199   /// Object used to treat all foldable expressions as constant expressions.
1200   struct FoldConstant {
1201     EvalInfo &Info;
1202     bool Enabled;
1203     bool HadNoPriorDiags;
1204     EvalInfo::EvaluationMode OldMode;
1205 
1206     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1207       : Info(Info),
1208         Enabled(Enabled),
1209         HadNoPriorDiags(Info.EvalStatus.Diag &&
1210                         Info.EvalStatus.Diag->empty() &&
1211                         !Info.EvalStatus.HasSideEffects),
1212         OldMode(Info.EvalMode) {
1213       if (Enabled)
1214         Info.EvalMode = EvalInfo::EM_ConstantFold;
1215     }
1216     void keepDiagnostics() { Enabled = false; }
1217     ~FoldConstant() {
1218       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1219           !Info.EvalStatus.HasSideEffects)
1220         Info.EvalStatus.Diag->clear();
1221       Info.EvalMode = OldMode;
1222     }
1223   };
1224 
1225   /// RAII object used to set the current evaluation mode to ignore
1226   /// side-effects.
1227   struct IgnoreSideEffectsRAII {
1228     EvalInfo &Info;
1229     EvalInfo::EvaluationMode OldMode;
1230     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1231         : Info(Info), OldMode(Info.EvalMode) {
1232       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1233     }
1234 
1235     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1236   };
1237 
1238   /// RAII object used to optionally suppress diagnostics and side-effects from
1239   /// a speculative evaluation.
1240   class SpeculativeEvaluationRAII {
1241     EvalInfo *Info = nullptr;
1242     Expr::EvalStatus OldStatus;
1243     unsigned OldSpeculativeEvaluationDepth;
1244 
1245     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1246       Info = Other.Info;
1247       OldStatus = Other.OldStatus;
1248       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1249       Other.Info = nullptr;
1250     }
1251 
1252     void maybeRestoreState() {
1253       if (!Info)
1254         return;
1255 
1256       Info->EvalStatus = OldStatus;
1257       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1258     }
1259 
1260   public:
1261     SpeculativeEvaluationRAII() = default;
1262 
1263     SpeculativeEvaluationRAII(
1264         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1265         : Info(&Info), OldStatus(Info.EvalStatus),
1266           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1267       Info.EvalStatus.Diag = NewDiag;
1268       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1269     }
1270 
1271     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1272     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1273       moveFromAndCancel(std::move(Other));
1274     }
1275 
1276     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1277       maybeRestoreState();
1278       moveFromAndCancel(std::move(Other));
1279       return *this;
1280     }
1281 
1282     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1283   };
1284 
1285   /// RAII object wrapping a full-expression or block scope, and handling
1286   /// the ending of the lifetime of temporaries created within it.
1287   template<bool IsFullExpression>
1288   class ScopeRAII {
1289     EvalInfo &Info;
1290     unsigned OldStackSize;
1291   public:
1292     ScopeRAII(EvalInfo &Info)
1293         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1294       // Push a new temporary version. This is needed to distinguish between
1295       // temporaries created in different iterations of a loop.
1296       Info.CurrentCall->pushTempVersion();
1297     }
1298     bool destroy(bool RunDestructors = true) {
1299       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1300       OldStackSize = -1U;
1301       return OK;
1302     }
1303     ~ScopeRAII() {
1304       if (OldStackSize != -1U)
1305         destroy(false);
1306       // Body moved to a static method to encourage the compiler to inline away
1307       // instances of this class.
1308       Info.CurrentCall->popTempVersion();
1309     }
1310   private:
1311     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1312                         unsigned OldStackSize) {
1313       assert(OldStackSize <= Info.CleanupStack.size() &&
1314              "running cleanups out of order?");
1315 
1316       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1317       // for a full-expression scope.
1318       bool Success = true;
1319       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1320         if (!(IsFullExpression &&
1321               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1322           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1323             Success = false;
1324             break;
1325           }
1326         }
1327       }
1328 
1329       // Compact lifetime-extended cleanups.
1330       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1331       if (IsFullExpression)
1332         NewEnd =
1333             std::remove_if(NewEnd, Info.CleanupStack.end(),
1334                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1335       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1336       return Success;
1337     }
1338   };
1339   typedef ScopeRAII<false> BlockScopeRAII;
1340   typedef ScopeRAII<true> FullExpressionRAII;
1341 }
1342 
1343 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1344                                          CheckSubobjectKind CSK) {
1345   if (Invalid)
1346     return false;
1347   if (isOnePastTheEnd()) {
1348     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1349       << CSK;
1350     setInvalid();
1351     return false;
1352   }
1353   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1354   // must actually be at least one array element; even a VLA cannot have a
1355   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1356   return true;
1357 }
1358 
1359 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1360                                                                 const Expr *E) {
1361   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1362   // Do not set the designator as invalid: we can represent this situation,
1363   // and correct handling of __builtin_object_size requires us to do so.
1364 }
1365 
1366 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1367                                                     const Expr *E,
1368                                                     const APSInt &N) {
1369   // If we're complaining, we must be able to statically determine the size of
1370   // the most derived array.
1371   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1372     Info.CCEDiag(E, diag::note_constexpr_array_index)
1373       << N << /*array*/ 0
1374       << static_cast<unsigned>(getMostDerivedArraySize());
1375   else
1376     Info.CCEDiag(E, diag::note_constexpr_array_index)
1377       << N << /*non-array*/ 1;
1378   setInvalid();
1379 }
1380 
1381 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1382                                const FunctionDecl *Callee, const LValue *This,
1383                                APValue *Arguments)
1384     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1385       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1386   Info.CurrentCall = this;
1387   ++Info.CallStackDepth;
1388 }
1389 
1390 CallStackFrame::~CallStackFrame() {
1391   assert(Info.CurrentCall == this && "calls retired out of order");
1392   --Info.CallStackDepth;
1393   Info.CurrentCall = Caller;
1394 }
1395 
1396 static bool isRead(AccessKinds AK) {
1397   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1398 }
1399 
1400 static bool isModification(AccessKinds AK) {
1401   switch (AK) {
1402   case AK_Read:
1403   case AK_ReadObjectRepresentation:
1404   case AK_MemberCall:
1405   case AK_DynamicCast:
1406   case AK_TypeId:
1407     return false;
1408   case AK_Assign:
1409   case AK_Increment:
1410   case AK_Decrement:
1411   case AK_Construct:
1412   case AK_Destroy:
1413     return true;
1414   }
1415   llvm_unreachable("unknown access kind");
1416 }
1417 
1418 static bool isAnyAccess(AccessKinds AK) {
1419   return isRead(AK) || isModification(AK);
1420 }
1421 
1422 /// Is this an access per the C++ definition?
1423 static bool isFormalAccess(AccessKinds AK) {
1424   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1425 }
1426 
1427 /// Is this kind of axcess valid on an indeterminate object value?
1428 static bool isValidIndeterminateAccess(AccessKinds AK) {
1429   switch (AK) {
1430   case AK_Read:
1431   case AK_Increment:
1432   case AK_Decrement:
1433     // These need the object's value.
1434     return false;
1435 
1436   case AK_ReadObjectRepresentation:
1437   case AK_Assign:
1438   case AK_Construct:
1439   case AK_Destroy:
1440     // Construction and destruction don't need the value.
1441     return true;
1442 
1443   case AK_MemberCall:
1444   case AK_DynamicCast:
1445   case AK_TypeId:
1446     // These aren't really meaningful on scalars.
1447     return true;
1448   }
1449   llvm_unreachable("unknown access kind");
1450 }
1451 
1452 namespace {
1453   struct ComplexValue {
1454   private:
1455     bool IsInt;
1456 
1457   public:
1458     APSInt IntReal, IntImag;
1459     APFloat FloatReal, FloatImag;
1460 
1461     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1462 
1463     void makeComplexFloat() { IsInt = false; }
1464     bool isComplexFloat() const { return !IsInt; }
1465     APFloat &getComplexFloatReal() { return FloatReal; }
1466     APFloat &getComplexFloatImag() { return FloatImag; }
1467 
1468     void makeComplexInt() { IsInt = true; }
1469     bool isComplexInt() const { return IsInt; }
1470     APSInt &getComplexIntReal() { return IntReal; }
1471     APSInt &getComplexIntImag() { return IntImag; }
1472 
1473     void moveInto(APValue &v) const {
1474       if (isComplexFloat())
1475         v = APValue(FloatReal, FloatImag);
1476       else
1477         v = APValue(IntReal, IntImag);
1478     }
1479     void setFrom(const APValue &v) {
1480       assert(v.isComplexFloat() || v.isComplexInt());
1481       if (v.isComplexFloat()) {
1482         makeComplexFloat();
1483         FloatReal = v.getComplexFloatReal();
1484         FloatImag = v.getComplexFloatImag();
1485       } else {
1486         makeComplexInt();
1487         IntReal = v.getComplexIntReal();
1488         IntImag = v.getComplexIntImag();
1489       }
1490     }
1491   };
1492 
1493   struct LValue {
1494     APValue::LValueBase Base;
1495     CharUnits Offset;
1496     SubobjectDesignator Designator;
1497     bool IsNullPtr : 1;
1498     bool InvalidBase : 1;
1499 
1500     const APValue::LValueBase getLValueBase() const { return Base; }
1501     CharUnits &getLValueOffset() { return Offset; }
1502     const CharUnits &getLValueOffset() const { return Offset; }
1503     SubobjectDesignator &getLValueDesignator() { return Designator; }
1504     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1505     bool isNullPointer() const { return IsNullPtr;}
1506 
1507     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1508     unsigned getLValueVersion() const { return Base.getVersion(); }
1509 
1510     void moveInto(APValue &V) const {
1511       if (Designator.Invalid)
1512         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1513       else {
1514         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1515         V = APValue(Base, Offset, Designator.Entries,
1516                     Designator.IsOnePastTheEnd, IsNullPtr);
1517       }
1518     }
1519     void setFrom(ASTContext &Ctx, const APValue &V) {
1520       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1521       Base = V.getLValueBase();
1522       Offset = V.getLValueOffset();
1523       InvalidBase = false;
1524       Designator = SubobjectDesignator(Ctx, V);
1525       IsNullPtr = V.isNullPointer();
1526     }
1527 
1528     void set(APValue::LValueBase B, bool BInvalid = false) {
1529 #ifndef NDEBUG
1530       // We only allow a few types of invalid bases. Enforce that here.
1531       if (BInvalid) {
1532         const auto *E = B.get<const Expr *>();
1533         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1534                "Unexpected type of invalid base");
1535       }
1536 #endif
1537 
1538       Base = B;
1539       Offset = CharUnits::fromQuantity(0);
1540       InvalidBase = BInvalid;
1541       Designator = SubobjectDesignator(getType(B));
1542       IsNullPtr = false;
1543     }
1544 
1545     void setNull(ASTContext &Ctx, QualType PointerTy) {
1546       Base = (Expr *)nullptr;
1547       Offset =
1548           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1549       InvalidBase = false;
1550       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1551       IsNullPtr = true;
1552     }
1553 
1554     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1555       set(B, true);
1556     }
1557 
1558     std::string toString(ASTContext &Ctx, QualType T) const {
1559       APValue Printable;
1560       moveInto(Printable);
1561       return Printable.getAsString(Ctx, T);
1562     }
1563 
1564   private:
1565     // Check that this LValue is not based on a null pointer. If it is, produce
1566     // a diagnostic and mark the designator as invalid.
1567     template <typename GenDiagType>
1568     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1569       if (Designator.Invalid)
1570         return false;
1571       if (IsNullPtr) {
1572         GenDiag();
1573         Designator.setInvalid();
1574         return false;
1575       }
1576       return true;
1577     }
1578 
1579   public:
1580     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1581                           CheckSubobjectKind CSK) {
1582       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1583         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1584       });
1585     }
1586 
1587     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1588                                        AccessKinds AK) {
1589       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1590         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1591       });
1592     }
1593 
1594     // Check this LValue refers to an object. If not, set the designator to be
1595     // invalid and emit a diagnostic.
1596     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1597       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1598              Designator.checkSubobject(Info, E, CSK);
1599     }
1600 
1601     void addDecl(EvalInfo &Info, const Expr *E,
1602                  const Decl *D, bool Virtual = false) {
1603       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1604         Designator.addDeclUnchecked(D, Virtual);
1605     }
1606     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1607       if (!Designator.Entries.empty()) {
1608         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1609         Designator.setInvalid();
1610         return;
1611       }
1612       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1613         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1614         Designator.FirstEntryIsAnUnsizedArray = true;
1615         Designator.addUnsizedArrayUnchecked(ElemTy);
1616       }
1617     }
1618     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1619       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1620         Designator.addArrayUnchecked(CAT);
1621     }
1622     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1623       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1624         Designator.addComplexUnchecked(EltTy, Imag);
1625     }
1626     void clearIsNullPointer() {
1627       IsNullPtr = false;
1628     }
1629     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1630                               const APSInt &Index, CharUnits ElementSize) {
1631       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1632       // but we're not required to diagnose it and it's valid in C++.)
1633       if (!Index)
1634         return;
1635 
1636       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1637       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1638       // offsets.
1639       uint64_t Offset64 = Offset.getQuantity();
1640       uint64_t ElemSize64 = ElementSize.getQuantity();
1641       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1642       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1643 
1644       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1645         Designator.adjustIndex(Info, E, Index);
1646       clearIsNullPointer();
1647     }
1648     void adjustOffset(CharUnits N) {
1649       Offset += N;
1650       if (N.getQuantity())
1651         clearIsNullPointer();
1652     }
1653   };
1654 
1655   struct MemberPtr {
1656     MemberPtr() {}
1657     explicit MemberPtr(const ValueDecl *Decl) :
1658       DeclAndIsDerivedMember(Decl, false), Path() {}
1659 
1660     /// The member or (direct or indirect) field referred to by this member
1661     /// pointer, or 0 if this is a null member pointer.
1662     const ValueDecl *getDecl() const {
1663       return DeclAndIsDerivedMember.getPointer();
1664     }
1665     /// Is this actually a member of some type derived from the relevant class?
1666     bool isDerivedMember() const {
1667       return DeclAndIsDerivedMember.getInt();
1668     }
1669     /// Get the class which the declaration actually lives in.
1670     const CXXRecordDecl *getContainingRecord() const {
1671       return cast<CXXRecordDecl>(
1672           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1673     }
1674 
1675     void moveInto(APValue &V) const {
1676       V = APValue(getDecl(), isDerivedMember(), Path);
1677     }
1678     void setFrom(const APValue &V) {
1679       assert(V.isMemberPointer());
1680       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1681       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1682       Path.clear();
1683       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1684       Path.insert(Path.end(), P.begin(), P.end());
1685     }
1686 
1687     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1688     /// whether the member is a member of some class derived from the class type
1689     /// of the member pointer.
1690     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1691     /// Path - The path of base/derived classes from the member declaration's
1692     /// class (exclusive) to the class type of the member pointer (inclusive).
1693     SmallVector<const CXXRecordDecl*, 4> Path;
1694 
1695     /// Perform a cast towards the class of the Decl (either up or down the
1696     /// hierarchy).
1697     bool castBack(const CXXRecordDecl *Class) {
1698       assert(!Path.empty());
1699       const CXXRecordDecl *Expected;
1700       if (Path.size() >= 2)
1701         Expected = Path[Path.size() - 2];
1702       else
1703         Expected = getContainingRecord();
1704       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1705         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1706         // if B does not contain the original member and is not a base or
1707         // derived class of the class containing the original member, the result
1708         // of the cast is undefined.
1709         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1710         // (D::*). We consider that to be a language defect.
1711         return false;
1712       }
1713       Path.pop_back();
1714       return true;
1715     }
1716     /// Perform a base-to-derived member pointer cast.
1717     bool castToDerived(const CXXRecordDecl *Derived) {
1718       if (!getDecl())
1719         return true;
1720       if (!isDerivedMember()) {
1721         Path.push_back(Derived);
1722         return true;
1723       }
1724       if (!castBack(Derived))
1725         return false;
1726       if (Path.empty())
1727         DeclAndIsDerivedMember.setInt(false);
1728       return true;
1729     }
1730     /// Perform a derived-to-base member pointer cast.
1731     bool castToBase(const CXXRecordDecl *Base) {
1732       if (!getDecl())
1733         return true;
1734       if (Path.empty())
1735         DeclAndIsDerivedMember.setInt(true);
1736       if (isDerivedMember()) {
1737         Path.push_back(Base);
1738         return true;
1739       }
1740       return castBack(Base);
1741     }
1742   };
1743 
1744   /// Compare two member pointers, which are assumed to be of the same type.
1745   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1746     if (!LHS.getDecl() || !RHS.getDecl())
1747       return !LHS.getDecl() && !RHS.getDecl();
1748     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1749       return false;
1750     return LHS.Path == RHS.Path;
1751   }
1752 }
1753 
1754 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1755 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1756                             const LValue &This, const Expr *E,
1757                             bool AllowNonLiteralTypes = false);
1758 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1759                            bool InvalidBaseOK = false);
1760 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1761                             bool InvalidBaseOK = false);
1762 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1763                                   EvalInfo &Info);
1764 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1765 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1766 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1767                                     EvalInfo &Info);
1768 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1769 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1770 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1771                            EvalInfo &Info);
1772 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1773 
1774 /// Evaluate an integer or fixed point expression into an APResult.
1775 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1776                                         EvalInfo &Info);
1777 
1778 /// Evaluate only a fixed point expression into an APResult.
1779 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1780                                EvalInfo &Info);
1781 
1782 //===----------------------------------------------------------------------===//
1783 // Misc utilities
1784 //===----------------------------------------------------------------------===//
1785 
1786 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1787 /// preserving its value (by extending by up to one bit as needed).
1788 static void negateAsSigned(APSInt &Int) {
1789   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1790     Int = Int.extend(Int.getBitWidth() + 1);
1791     Int.setIsSigned(true);
1792   }
1793   Int = -Int;
1794 }
1795 
1796 template<typename KeyT>
1797 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1798                                          bool IsLifetimeExtended, LValue &LV) {
1799   unsigned Version = getTempVersion();
1800   APValue::LValueBase Base(Key, Index, Version);
1801   LV.set(Base);
1802   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1803   assert(Result.isAbsent() && "temporary created multiple times");
1804 
1805   // If we're creating a temporary immediately in the operand of a speculative
1806   // evaluation, don't register a cleanup to be run outside the speculative
1807   // evaluation context, since we won't actually be able to initialize this
1808   // object.
1809   if (Index <= Info.SpeculativeEvaluationDepth) {
1810     if (T.isDestructedType())
1811       Info.noteSideEffect();
1812   } else {
1813     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1814   }
1815   return Result;
1816 }
1817 
1818 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1819   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1820     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1821     return nullptr;
1822   }
1823 
1824   DynamicAllocLValue DA(NumHeapAllocs++);
1825   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1826   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1827                                    std::forward_as_tuple(DA), std::tuple<>());
1828   assert(Result.second && "reused a heap alloc index?");
1829   Result.first->second.AllocExpr = E;
1830   return &Result.first->second.Value;
1831 }
1832 
1833 /// Produce a string describing the given constexpr call.
1834 void CallStackFrame::describe(raw_ostream &Out) {
1835   unsigned ArgIndex = 0;
1836   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1837                       !isa<CXXConstructorDecl>(Callee) &&
1838                       cast<CXXMethodDecl>(Callee)->isInstance();
1839 
1840   if (!IsMemberCall)
1841     Out << *Callee << '(';
1842 
1843   if (This && IsMemberCall) {
1844     APValue Val;
1845     This->moveInto(Val);
1846     Val.printPretty(Out, Info.Ctx,
1847                     This->Designator.MostDerivedType);
1848     // FIXME: Add parens around Val if needed.
1849     Out << "->" << *Callee << '(';
1850     IsMemberCall = false;
1851   }
1852 
1853   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1854        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1855     if (ArgIndex > (unsigned)IsMemberCall)
1856       Out << ", ";
1857 
1858     const ParmVarDecl *Param = *I;
1859     const APValue &Arg = Arguments[ArgIndex];
1860     Arg.printPretty(Out, Info.Ctx, Param->getType());
1861 
1862     if (ArgIndex == 0 && IsMemberCall)
1863       Out << "->" << *Callee << '(';
1864   }
1865 
1866   Out << ')';
1867 }
1868 
1869 /// Evaluate an expression to see if it had side-effects, and discard its
1870 /// result.
1871 /// \return \c true if the caller should keep evaluating.
1872 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1873   APValue Scratch;
1874   if (!Evaluate(Scratch, Info, E))
1875     // We don't need the value, but we might have skipped a side effect here.
1876     return Info.noteSideEffect();
1877   return true;
1878 }
1879 
1880 /// Should this call expression be treated as a string literal?
1881 static bool IsStringLiteralCall(const CallExpr *E) {
1882   unsigned Builtin = E->getBuiltinCallee();
1883   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1884           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1885 }
1886 
1887 static bool IsGlobalLValue(APValue::LValueBase B) {
1888   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1889   // constant expression of pointer type that evaluates to...
1890 
1891   // ... a null pointer value, or a prvalue core constant expression of type
1892   // std::nullptr_t.
1893   if (!B) return true;
1894 
1895   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1896     // ... the address of an object with static storage duration,
1897     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1898       return VD->hasGlobalStorage();
1899     // ... the address of a function,
1900     // ... the address of a GUID [MS extension],
1901     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1902   }
1903 
1904   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1905     return true;
1906 
1907   const Expr *E = B.get<const Expr*>();
1908   switch (E->getStmtClass()) {
1909   default:
1910     return false;
1911   case Expr::CompoundLiteralExprClass: {
1912     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1913     return CLE->isFileScope() && CLE->isLValue();
1914   }
1915   case Expr::MaterializeTemporaryExprClass:
1916     // A materialized temporary might have been lifetime-extended to static
1917     // storage duration.
1918     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1919   // A string literal has static storage duration.
1920   case Expr::StringLiteralClass:
1921   case Expr::PredefinedExprClass:
1922   case Expr::ObjCStringLiteralClass:
1923   case Expr::ObjCEncodeExprClass:
1924     return true;
1925   case Expr::ObjCBoxedExprClass:
1926     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1927   case Expr::CallExprClass:
1928     return IsStringLiteralCall(cast<CallExpr>(E));
1929   // For GCC compatibility, &&label has static storage duration.
1930   case Expr::AddrLabelExprClass:
1931     return true;
1932   // A Block literal expression may be used as the initialization value for
1933   // Block variables at global or local static scope.
1934   case Expr::BlockExprClass:
1935     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1936   case Expr::ImplicitValueInitExprClass:
1937     // FIXME:
1938     // We can never form an lvalue with an implicit value initialization as its
1939     // base through expression evaluation, so these only appear in one case: the
1940     // implicit variable declaration we invent when checking whether a constexpr
1941     // constructor can produce a constant expression. We must assume that such
1942     // an expression might be a global lvalue.
1943     return true;
1944   }
1945 }
1946 
1947 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1948   return LVal.Base.dyn_cast<const ValueDecl*>();
1949 }
1950 
1951 static bool IsLiteralLValue(const LValue &Value) {
1952   if (Value.getLValueCallIndex())
1953     return false;
1954   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1955   return E && !isa<MaterializeTemporaryExpr>(E);
1956 }
1957 
1958 static bool IsWeakLValue(const LValue &Value) {
1959   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1960   return Decl && Decl->isWeak();
1961 }
1962 
1963 static bool isZeroSized(const LValue &Value) {
1964   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1965   if (Decl && isa<VarDecl>(Decl)) {
1966     QualType Ty = Decl->getType();
1967     if (Ty->isArrayType())
1968       return Ty->isIncompleteType() ||
1969              Decl->getASTContext().getTypeSize(Ty) == 0;
1970   }
1971   return false;
1972 }
1973 
1974 static bool HasSameBase(const LValue &A, const LValue &B) {
1975   if (!A.getLValueBase())
1976     return !B.getLValueBase();
1977   if (!B.getLValueBase())
1978     return false;
1979 
1980   if (A.getLValueBase().getOpaqueValue() !=
1981       B.getLValueBase().getOpaqueValue())
1982     return false;
1983 
1984   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
1985          A.getLValueVersion() == B.getLValueVersion();
1986 }
1987 
1988 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1989   assert(Base && "no location for a null lvalue");
1990   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1991   if (VD)
1992     Info.Note(VD->getLocation(), diag::note_declared_at);
1993   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1994     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1995   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1996     // FIXME: Produce a note for dangling pointers too.
1997     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
1998       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1999                 diag::note_constexpr_dynamic_alloc_here);
2000   }
2001   // We have no information to show for a typeid(T) object.
2002 }
2003 
2004 enum class CheckEvaluationResultKind {
2005   ConstantExpression,
2006   FullyInitialized,
2007 };
2008 
2009 /// Materialized temporaries that we've already checked to determine if they're
2010 /// initializsed by a constant expression.
2011 using CheckedTemporaries =
2012     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2013 
2014 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2015                                   EvalInfo &Info, SourceLocation DiagLoc,
2016                                   QualType Type, const APValue &Value,
2017                                   Expr::ConstExprUsage Usage,
2018                                   SourceLocation SubobjectLoc,
2019                                   CheckedTemporaries &CheckedTemps);
2020 
2021 /// Check that this reference or pointer core constant expression is a valid
2022 /// value for an address or reference constant expression. Return true if we
2023 /// can fold this expression, whether or not it's a constant expression.
2024 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2025                                           QualType Type, const LValue &LVal,
2026                                           Expr::ConstExprUsage Usage,
2027                                           CheckedTemporaries &CheckedTemps) {
2028   bool IsReferenceType = Type->isReferenceType();
2029 
2030   APValue::LValueBase Base = LVal.getLValueBase();
2031   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2032 
2033   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2034     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2035       if (FD->isConsteval()) {
2036         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2037             << !Type->isAnyPointerType();
2038         Info.Note(FD->getLocation(), diag::note_declared_at);
2039         return false;
2040       }
2041     }
2042   }
2043 
2044   // Check that the object is a global. Note that the fake 'this' object we
2045   // manufacture when checking potential constant expressions is conservatively
2046   // assumed to be global here.
2047   if (!IsGlobalLValue(Base)) {
2048     if (Info.getLangOpts().CPlusPlus11) {
2049       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2050       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2051         << IsReferenceType << !Designator.Entries.empty()
2052         << !!VD << VD;
2053 
2054       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2055       if (VarD && VarD->isConstexpr()) {
2056         // Non-static local constexpr variables have unintuitive semantics:
2057         //   constexpr int a = 1;
2058         //   constexpr const int *p = &a;
2059         // ... is invalid because the address of 'a' is not constant. Suggest
2060         // adding a 'static' in this case.
2061         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2062             << VarD
2063             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2064       } else {
2065         NoteLValueLocation(Info, Base);
2066       }
2067     } else {
2068       Info.FFDiag(Loc);
2069     }
2070     // Don't allow references to temporaries to escape.
2071     return false;
2072   }
2073   assert((Info.checkingPotentialConstantExpression() ||
2074           LVal.getLValueCallIndex() == 0) &&
2075          "have call index for global lvalue");
2076 
2077   if (Base.is<DynamicAllocLValue>()) {
2078     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2079         << IsReferenceType << !Designator.Entries.empty();
2080     NoteLValueLocation(Info, Base);
2081     return false;
2082   }
2083 
2084   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2085     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2086       // Check if this is a thread-local variable.
2087       if (Var->getTLSKind())
2088         // FIXME: Diagnostic!
2089         return false;
2090 
2091       // A dllimport variable never acts like a constant.
2092       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2093         // FIXME: Diagnostic!
2094         return false;
2095     }
2096     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2097       // __declspec(dllimport) must be handled very carefully:
2098       // We must never initialize an expression with the thunk in C++.
2099       // Doing otherwise would allow the same id-expression to yield
2100       // different addresses for the same function in different translation
2101       // units.  However, this means that we must dynamically initialize the
2102       // expression with the contents of the import address table at runtime.
2103       //
2104       // The C language has no notion of ODR; furthermore, it has no notion of
2105       // dynamic initialization.  This means that we are permitted to
2106       // perform initialization with the address of the thunk.
2107       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2108           FD->hasAttr<DLLImportAttr>())
2109         // FIXME: Diagnostic!
2110         return false;
2111     }
2112   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2113                  Base.dyn_cast<const Expr *>())) {
2114     if (CheckedTemps.insert(MTE).second) {
2115       QualType TempType = getType(Base);
2116       if (TempType.isDestructedType()) {
2117         Info.FFDiag(MTE->getExprLoc(),
2118                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2119             << TempType;
2120         return false;
2121       }
2122 
2123       APValue *V = MTE->getOrCreateValue(false);
2124       assert(V && "evasluation result refers to uninitialised temporary");
2125       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2126                                  Info, MTE->getExprLoc(), TempType, *V,
2127                                  Usage, SourceLocation(), CheckedTemps))
2128         return false;
2129     }
2130   }
2131 
2132   // Allow address constant expressions to be past-the-end pointers. This is
2133   // an extension: the standard requires them to point to an object.
2134   if (!IsReferenceType)
2135     return true;
2136 
2137   // A reference constant expression must refer to an object.
2138   if (!Base) {
2139     // FIXME: diagnostic
2140     Info.CCEDiag(Loc);
2141     return true;
2142   }
2143 
2144   // Does this refer one past the end of some object?
2145   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2146     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2147     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2148       << !Designator.Entries.empty() << !!VD << VD;
2149     NoteLValueLocation(Info, Base);
2150   }
2151 
2152   return true;
2153 }
2154 
2155 /// Member pointers are constant expressions unless they point to a
2156 /// non-virtual dllimport member function.
2157 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2158                                                  SourceLocation Loc,
2159                                                  QualType Type,
2160                                                  const APValue &Value,
2161                                                  Expr::ConstExprUsage Usage) {
2162   const ValueDecl *Member = Value.getMemberPointerDecl();
2163   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2164   if (!FD)
2165     return true;
2166   if (FD->isConsteval()) {
2167     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2168     Info.Note(FD->getLocation(), diag::note_declared_at);
2169     return false;
2170   }
2171   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2172          !FD->hasAttr<DLLImportAttr>();
2173 }
2174 
2175 /// Check that this core constant expression is of literal type, and if not,
2176 /// produce an appropriate diagnostic.
2177 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2178                              const LValue *This = nullptr) {
2179   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2180     return true;
2181 
2182   // C++1y: A constant initializer for an object o [...] may also invoke
2183   // constexpr constructors for o and its subobjects even if those objects
2184   // are of non-literal class types.
2185   //
2186   // C++11 missed this detail for aggregates, so classes like this:
2187   //   struct foo_t { union { int i; volatile int j; } u; };
2188   // are not (obviously) initializable like so:
2189   //   __attribute__((__require_constant_initialization__))
2190   //   static const foo_t x = {{0}};
2191   // because "i" is a subobject with non-literal initialization (due to the
2192   // volatile member of the union). See:
2193   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2194   // Therefore, we use the C++1y behavior.
2195   if (This && Info.EvaluatingDecl == This->getLValueBase())
2196     return true;
2197 
2198   // Prvalue constant expressions must be of literal types.
2199   if (Info.getLangOpts().CPlusPlus11)
2200     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2201       << E->getType();
2202   else
2203     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2204   return false;
2205 }
2206 
2207 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2208                                   EvalInfo &Info, SourceLocation DiagLoc,
2209                                   QualType Type, const APValue &Value,
2210                                   Expr::ConstExprUsage Usage,
2211                                   SourceLocation SubobjectLoc,
2212                                   CheckedTemporaries &CheckedTemps) {
2213   if (!Value.hasValue()) {
2214     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2215       << true << Type;
2216     if (SubobjectLoc.isValid())
2217       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2218     return false;
2219   }
2220 
2221   // We allow _Atomic(T) to be initialized from anything that T can be
2222   // initialized from.
2223   if (const AtomicType *AT = Type->getAs<AtomicType>())
2224     Type = AT->getValueType();
2225 
2226   // Core issue 1454: For a literal constant expression of array or class type,
2227   // each subobject of its value shall have been initialized by a constant
2228   // expression.
2229   if (Value.isArray()) {
2230     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2231     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2232       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2233                                  Value.getArrayInitializedElt(I), Usage,
2234                                  SubobjectLoc, CheckedTemps))
2235         return false;
2236     }
2237     if (!Value.hasArrayFiller())
2238       return true;
2239     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2240                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2241                                  CheckedTemps);
2242   }
2243   if (Value.isUnion() && Value.getUnionField()) {
2244     return CheckEvaluationResult(
2245         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2246         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2247         CheckedTemps);
2248   }
2249   if (Value.isStruct()) {
2250     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2251     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2252       unsigned BaseIndex = 0;
2253       for (const CXXBaseSpecifier &BS : CD->bases()) {
2254         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2255                                    Value.getStructBase(BaseIndex), Usage,
2256                                    BS.getBeginLoc(), CheckedTemps))
2257           return false;
2258         ++BaseIndex;
2259       }
2260     }
2261     for (const auto *I : RD->fields()) {
2262       if (I->isUnnamedBitfield())
2263         continue;
2264 
2265       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2266                                  Value.getStructField(I->getFieldIndex()),
2267                                  Usage, I->getLocation(), CheckedTemps))
2268         return false;
2269     }
2270   }
2271 
2272   if (Value.isLValue() &&
2273       CERK == CheckEvaluationResultKind::ConstantExpression) {
2274     LValue LVal;
2275     LVal.setFrom(Info.Ctx, Value);
2276     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2277                                          CheckedTemps);
2278   }
2279 
2280   if (Value.isMemberPointer() &&
2281       CERK == CheckEvaluationResultKind::ConstantExpression)
2282     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2283 
2284   // Everything else is fine.
2285   return true;
2286 }
2287 
2288 /// Check that this core constant expression value is a valid value for a
2289 /// constant expression. If not, report an appropriate diagnostic. Does not
2290 /// check that the expression is of literal type.
2291 static bool
2292 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2293                         const APValue &Value,
2294                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2295   // Nothing to check for a constant expression of type 'cv void'.
2296   if (Type->isVoidType())
2297     return true;
2298 
2299   CheckedTemporaries CheckedTemps;
2300   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2301                                Info, DiagLoc, Type, Value, Usage,
2302                                SourceLocation(), CheckedTemps);
2303 }
2304 
2305 /// Check that this evaluated value is fully-initialized and can be loaded by
2306 /// an lvalue-to-rvalue conversion.
2307 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2308                                   QualType Type, const APValue &Value) {
2309   CheckedTemporaries CheckedTemps;
2310   return CheckEvaluationResult(
2311       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2312       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2313 }
2314 
2315 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2316 /// "the allocated storage is deallocated within the evaluation".
2317 static bool CheckMemoryLeaks(EvalInfo &Info) {
2318   if (!Info.HeapAllocs.empty()) {
2319     // We can still fold to a constant despite a compile-time memory leak,
2320     // so long as the heap allocation isn't referenced in the result (we check
2321     // that in CheckConstantExpression).
2322     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2323                  diag::note_constexpr_memory_leak)
2324         << unsigned(Info.HeapAllocs.size() - 1);
2325   }
2326   return true;
2327 }
2328 
2329 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2330   // A null base expression indicates a null pointer.  These are always
2331   // evaluatable, and they are false unless the offset is zero.
2332   if (!Value.getLValueBase()) {
2333     Result = !Value.getLValueOffset().isZero();
2334     return true;
2335   }
2336 
2337   // We have a non-null base.  These are generally known to be true, but if it's
2338   // a weak declaration it can be null at runtime.
2339   Result = true;
2340   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2341   return !Decl || !Decl->isWeak();
2342 }
2343 
2344 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2345   switch (Val.getKind()) {
2346   case APValue::None:
2347   case APValue::Indeterminate:
2348     return false;
2349   case APValue::Int:
2350     Result = Val.getInt().getBoolValue();
2351     return true;
2352   case APValue::FixedPoint:
2353     Result = Val.getFixedPoint().getBoolValue();
2354     return true;
2355   case APValue::Float:
2356     Result = !Val.getFloat().isZero();
2357     return true;
2358   case APValue::ComplexInt:
2359     Result = Val.getComplexIntReal().getBoolValue() ||
2360              Val.getComplexIntImag().getBoolValue();
2361     return true;
2362   case APValue::ComplexFloat:
2363     Result = !Val.getComplexFloatReal().isZero() ||
2364              !Val.getComplexFloatImag().isZero();
2365     return true;
2366   case APValue::LValue:
2367     return EvalPointerValueAsBool(Val, Result);
2368   case APValue::MemberPointer:
2369     Result = Val.getMemberPointerDecl();
2370     return true;
2371   case APValue::Vector:
2372   case APValue::Array:
2373   case APValue::Struct:
2374   case APValue::Union:
2375   case APValue::AddrLabelDiff:
2376     return false;
2377   }
2378 
2379   llvm_unreachable("unknown APValue kind");
2380 }
2381 
2382 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2383                                        EvalInfo &Info) {
2384   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2385   APValue Val;
2386   if (!Evaluate(Val, Info, E))
2387     return false;
2388   return HandleConversionToBool(Val, Result);
2389 }
2390 
2391 template<typename T>
2392 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2393                            const T &SrcValue, QualType DestType) {
2394   Info.CCEDiag(E, diag::note_constexpr_overflow)
2395     << SrcValue << DestType;
2396   return Info.noteUndefinedBehavior();
2397 }
2398 
2399 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2400                                  QualType SrcType, const APFloat &Value,
2401                                  QualType DestType, APSInt &Result) {
2402   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2403   // Determine whether we are converting to unsigned or signed.
2404   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2405 
2406   Result = APSInt(DestWidth, !DestSigned);
2407   bool ignored;
2408   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2409       & APFloat::opInvalidOp)
2410     return HandleOverflow(Info, E, Value, DestType);
2411   return true;
2412 }
2413 
2414 /// Get rounding mode used for evaluation of the specified expression.
2415 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2416 ///                       dynamic.
2417 /// If rounding mode is unknown at compile time, still try to evaluate the
2418 /// expression. If the result is exact, it does not depend on rounding mode.
2419 /// So return "tonearest" mode instead of "dynamic".
2420 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2421                                                 bool &DynamicRM) {
2422   llvm::RoundingMode RM =
2423       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2424   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2425   if (DynamicRM)
2426     RM = llvm::RoundingMode::NearestTiesToEven;
2427   return RM;
2428 }
2429 
2430 /// Check if the given evaluation result is allowed for constant evaluation.
2431 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2432                                      APFloat::opStatus St) {
2433   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2434   if ((St & APFloat::opInexact) &&
2435       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2436     // Inexact result means that it depends on rounding mode. If the requested
2437     // mode is dynamic, the evaluation cannot be made in compile time.
2438     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2439     return false;
2440   }
2441 
2442   if ((St & APFloat::opStatus::opInvalidOp) &&
2443       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2444     // There is no usefully definable result.
2445     Info.FFDiag(E);
2446     return false;
2447   }
2448 
2449   // FIXME: if:
2450   // - evaluation triggered other FP exception, and
2451   // - exception mode is not "ignore", and
2452   // - the expression being evaluated is not a part of global variable
2453   //   initializer,
2454   // the evaluation probably need to be rejected.
2455   return true;
2456 }
2457 
2458 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2459                                    QualType SrcType, QualType DestType,
2460                                    APFloat &Result) {
2461   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2462   bool DynamicRM;
2463   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2464   APFloat::opStatus St;
2465   APFloat Value = Result;
2466   bool ignored;
2467   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2468   return checkFloatingPointResult(Info, E, St);
2469 }
2470 
2471 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2472                                  QualType DestType, QualType SrcType,
2473                                  const APSInt &Value) {
2474   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2475   // Figure out if this is a truncate, extend or noop cast.
2476   // If the input is signed, do a sign extend, noop, or truncate.
2477   APSInt Result = Value.extOrTrunc(DestWidth);
2478   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2479   if (DestType->isBooleanType())
2480     Result = Value.getBoolValue();
2481   return Result;
2482 }
2483 
2484 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2485                                  QualType SrcType, const APSInt &Value,
2486                                  QualType DestType, APFloat &Result) {
2487   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2488   Result.convertFromAPInt(Value, Value.isSigned(),
2489                           APFloat::rmNearestTiesToEven);
2490   return true;
2491 }
2492 
2493 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2494                                   APValue &Value, const FieldDecl *FD) {
2495   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2496 
2497   if (!Value.isInt()) {
2498     // Trying to store a pointer-cast-to-integer into a bitfield.
2499     // FIXME: In this case, we should provide the diagnostic for casting
2500     // a pointer to an integer.
2501     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2502     Info.FFDiag(E);
2503     return false;
2504   }
2505 
2506   APSInt &Int = Value.getInt();
2507   unsigned OldBitWidth = Int.getBitWidth();
2508   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2509   if (NewBitWidth < OldBitWidth)
2510     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2511   return true;
2512 }
2513 
2514 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2515                                   llvm::APInt &Res) {
2516   APValue SVal;
2517   if (!Evaluate(SVal, Info, E))
2518     return false;
2519   if (SVal.isInt()) {
2520     Res = SVal.getInt();
2521     return true;
2522   }
2523   if (SVal.isFloat()) {
2524     Res = SVal.getFloat().bitcastToAPInt();
2525     return true;
2526   }
2527   if (SVal.isVector()) {
2528     QualType VecTy = E->getType();
2529     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2530     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2531     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2532     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2533     Res = llvm::APInt::getNullValue(VecSize);
2534     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2535       APValue &Elt = SVal.getVectorElt(i);
2536       llvm::APInt EltAsInt;
2537       if (Elt.isInt()) {
2538         EltAsInt = Elt.getInt();
2539       } else if (Elt.isFloat()) {
2540         EltAsInt = Elt.getFloat().bitcastToAPInt();
2541       } else {
2542         // Don't try to handle vectors of anything other than int or float
2543         // (not sure if it's possible to hit this case).
2544         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2545         return false;
2546       }
2547       unsigned BaseEltSize = EltAsInt.getBitWidth();
2548       if (BigEndian)
2549         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2550       else
2551         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2552     }
2553     return true;
2554   }
2555   // Give up if the input isn't an int, float, or vector.  For example, we
2556   // reject "(v4i16)(intptr_t)&a".
2557   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2558   return false;
2559 }
2560 
2561 /// Perform the given integer operation, which is known to need at most BitWidth
2562 /// bits, and check for overflow in the original type (if that type was not an
2563 /// unsigned type).
2564 template<typename Operation>
2565 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2566                                  const APSInt &LHS, const APSInt &RHS,
2567                                  unsigned BitWidth, Operation Op,
2568                                  APSInt &Result) {
2569   if (LHS.isUnsigned()) {
2570     Result = Op(LHS, RHS);
2571     return true;
2572   }
2573 
2574   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2575   Result = Value.trunc(LHS.getBitWidth());
2576   if (Result.extend(BitWidth) != Value) {
2577     if (Info.checkingForUndefinedBehavior())
2578       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2579                                        diag::warn_integer_constant_overflow)
2580           << Result.toString(10) << E->getType();
2581     else
2582       return HandleOverflow(Info, E, Value, E->getType());
2583   }
2584   return true;
2585 }
2586 
2587 /// Perform the given binary integer operation.
2588 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2589                               BinaryOperatorKind Opcode, APSInt RHS,
2590                               APSInt &Result) {
2591   switch (Opcode) {
2592   default:
2593     Info.FFDiag(E);
2594     return false;
2595   case BO_Mul:
2596     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2597                                 std::multiplies<APSInt>(), Result);
2598   case BO_Add:
2599     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2600                                 std::plus<APSInt>(), Result);
2601   case BO_Sub:
2602     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2603                                 std::minus<APSInt>(), Result);
2604   case BO_And: Result = LHS & RHS; return true;
2605   case BO_Xor: Result = LHS ^ RHS; return true;
2606   case BO_Or:  Result = LHS | RHS; return true;
2607   case BO_Div:
2608   case BO_Rem:
2609     if (RHS == 0) {
2610       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2611       return false;
2612     }
2613     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2614     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2615     // this operation and gives the two's complement result.
2616     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2617         LHS.isSigned() && LHS.isMinSignedValue())
2618       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2619                             E->getType());
2620     return true;
2621   case BO_Shl: {
2622     if (Info.getLangOpts().OpenCL)
2623       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2624       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2625                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2626                     RHS.isUnsigned());
2627     else if (RHS.isSigned() && RHS.isNegative()) {
2628       // During constant-folding, a negative shift is an opposite shift. Such
2629       // a shift is not a constant expression.
2630       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2631       RHS = -RHS;
2632       goto shift_right;
2633     }
2634   shift_left:
2635     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2636     // the shifted type.
2637     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2638     if (SA != RHS) {
2639       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2640         << RHS << E->getType() << LHS.getBitWidth();
2641     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2642       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2643       // operand, and must not overflow the corresponding unsigned type.
2644       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2645       // E1 x 2^E2 module 2^N.
2646       if (LHS.isNegative())
2647         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2648       else if (LHS.countLeadingZeros() < SA)
2649         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2650     }
2651     Result = LHS << SA;
2652     return true;
2653   }
2654   case BO_Shr: {
2655     if (Info.getLangOpts().OpenCL)
2656       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2657       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2658                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2659                     RHS.isUnsigned());
2660     else if (RHS.isSigned() && RHS.isNegative()) {
2661       // During constant-folding, a negative shift is an opposite shift. Such a
2662       // shift is not a constant expression.
2663       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2664       RHS = -RHS;
2665       goto shift_left;
2666     }
2667   shift_right:
2668     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2669     // shifted type.
2670     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2671     if (SA != RHS)
2672       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2673         << RHS << E->getType() << LHS.getBitWidth();
2674     Result = LHS >> SA;
2675     return true;
2676   }
2677 
2678   case BO_LT: Result = LHS < RHS; return true;
2679   case BO_GT: Result = LHS > RHS; return true;
2680   case BO_LE: Result = LHS <= RHS; return true;
2681   case BO_GE: Result = LHS >= RHS; return true;
2682   case BO_EQ: Result = LHS == RHS; return true;
2683   case BO_NE: Result = LHS != RHS; return true;
2684   case BO_Cmp:
2685     llvm_unreachable("BO_Cmp should be handled elsewhere");
2686   }
2687 }
2688 
2689 /// Perform the given binary floating-point operation, in-place, on LHS.
2690 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2691                                   APFloat &LHS, BinaryOperatorKind Opcode,
2692                                   const APFloat &RHS) {
2693   bool DynamicRM;
2694   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2695   APFloat::opStatus St;
2696   switch (Opcode) {
2697   default:
2698     Info.FFDiag(E);
2699     return false;
2700   case BO_Mul:
2701     St = LHS.multiply(RHS, RM);
2702     break;
2703   case BO_Add:
2704     St = LHS.add(RHS, RM);
2705     break;
2706   case BO_Sub:
2707     St = LHS.subtract(RHS, RM);
2708     break;
2709   case BO_Div:
2710     // [expr.mul]p4:
2711     //   If the second operand of / or % is zero the behavior is undefined.
2712     if (RHS.isZero())
2713       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2714     St = LHS.divide(RHS, RM);
2715     break;
2716   }
2717 
2718   // [expr.pre]p4:
2719   //   If during the evaluation of an expression, the result is not
2720   //   mathematically defined [...], the behavior is undefined.
2721   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2722   if (LHS.isNaN()) {
2723     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2724     return Info.noteUndefinedBehavior();
2725   }
2726 
2727   return checkFloatingPointResult(Info, E, St);
2728 }
2729 
2730 static bool handleLogicalOpForVector(const APInt &LHSValue,
2731                                      BinaryOperatorKind Opcode,
2732                                      const APInt &RHSValue, APInt &Result) {
2733   bool LHS = (LHSValue != 0);
2734   bool RHS = (RHSValue != 0);
2735 
2736   if (Opcode == BO_LAnd)
2737     Result = LHS && RHS;
2738   else
2739     Result = LHS || RHS;
2740   return true;
2741 }
2742 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2743                                      BinaryOperatorKind Opcode,
2744                                      const APFloat &RHSValue, APInt &Result) {
2745   bool LHS = !LHSValue.isZero();
2746   bool RHS = !RHSValue.isZero();
2747 
2748   if (Opcode == BO_LAnd)
2749     Result = LHS && RHS;
2750   else
2751     Result = LHS || RHS;
2752   return true;
2753 }
2754 
2755 static bool handleLogicalOpForVector(const APValue &LHSValue,
2756                                      BinaryOperatorKind Opcode,
2757                                      const APValue &RHSValue, APInt &Result) {
2758   // The result is always an int type, however operands match the first.
2759   if (LHSValue.getKind() == APValue::Int)
2760     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2761                                     RHSValue.getInt(), Result);
2762   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2763   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2764                                   RHSValue.getFloat(), Result);
2765 }
2766 
2767 template <typename APTy>
2768 static bool
2769 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2770                                const APTy &RHSValue, APInt &Result) {
2771   switch (Opcode) {
2772   default:
2773     llvm_unreachable("unsupported binary operator");
2774   case BO_EQ:
2775     Result = (LHSValue == RHSValue);
2776     break;
2777   case BO_NE:
2778     Result = (LHSValue != RHSValue);
2779     break;
2780   case BO_LT:
2781     Result = (LHSValue < RHSValue);
2782     break;
2783   case BO_GT:
2784     Result = (LHSValue > RHSValue);
2785     break;
2786   case BO_LE:
2787     Result = (LHSValue <= RHSValue);
2788     break;
2789   case BO_GE:
2790     Result = (LHSValue >= RHSValue);
2791     break;
2792   }
2793 
2794   return true;
2795 }
2796 
2797 static bool handleCompareOpForVector(const APValue &LHSValue,
2798                                      BinaryOperatorKind Opcode,
2799                                      const APValue &RHSValue, APInt &Result) {
2800   // The result is always an int type, however operands match the first.
2801   if (LHSValue.getKind() == APValue::Int)
2802     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2803                                           RHSValue.getInt(), Result);
2804   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2805   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2806                                         RHSValue.getFloat(), Result);
2807 }
2808 
2809 // Perform binary operations for vector types, in place on the LHS.
2810 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2811                                     BinaryOperatorKind Opcode,
2812                                     APValue &LHSValue,
2813                                     const APValue &RHSValue) {
2814   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2815          "Operation not supported on vector types");
2816 
2817   const auto *VT = E->getType()->castAs<VectorType>();
2818   unsigned NumElements = VT->getNumElements();
2819   QualType EltTy = VT->getElementType();
2820 
2821   // In the cases (typically C as I've observed) where we aren't evaluating
2822   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2823   // just give up.
2824   if (!LHSValue.isVector()) {
2825     assert(LHSValue.isLValue() &&
2826            "A vector result that isn't a vector OR uncalculated LValue");
2827     Info.FFDiag(E);
2828     return false;
2829   }
2830 
2831   assert(LHSValue.getVectorLength() == NumElements &&
2832          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2833 
2834   SmallVector<APValue, 4> ResultElements;
2835 
2836   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2837     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2838     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2839 
2840     if (EltTy->isIntegerType()) {
2841       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2842                        EltTy->isUnsignedIntegerType()};
2843       bool Success = true;
2844 
2845       if (BinaryOperator::isLogicalOp(Opcode))
2846         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2847       else if (BinaryOperator::isComparisonOp(Opcode))
2848         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2849       else
2850         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2851                                     RHSElt.getInt(), EltResult);
2852 
2853       if (!Success) {
2854         Info.FFDiag(E);
2855         return false;
2856       }
2857       ResultElements.emplace_back(EltResult);
2858 
2859     } else if (EltTy->isFloatingType()) {
2860       assert(LHSElt.getKind() == APValue::Float &&
2861              RHSElt.getKind() == APValue::Float &&
2862              "Mismatched LHS/RHS/Result Type");
2863       APFloat LHSFloat = LHSElt.getFloat();
2864 
2865       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
2866                                  RHSElt.getFloat())) {
2867         Info.FFDiag(E);
2868         return false;
2869       }
2870 
2871       ResultElements.emplace_back(LHSFloat);
2872     }
2873   }
2874 
2875   LHSValue = APValue(ResultElements.data(), ResultElements.size());
2876   return true;
2877 }
2878 
2879 /// Cast an lvalue referring to a base subobject to a derived class, by
2880 /// truncating the lvalue's path to the given length.
2881 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2882                                const RecordDecl *TruncatedType,
2883                                unsigned TruncatedElements) {
2884   SubobjectDesignator &D = Result.Designator;
2885 
2886   // Check we actually point to a derived class object.
2887   if (TruncatedElements == D.Entries.size())
2888     return true;
2889   assert(TruncatedElements >= D.MostDerivedPathLength &&
2890          "not casting to a derived class");
2891   if (!Result.checkSubobject(Info, E, CSK_Derived))
2892     return false;
2893 
2894   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2895   const RecordDecl *RD = TruncatedType;
2896   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2897     if (RD->isInvalidDecl()) return false;
2898     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2899     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2900     if (isVirtualBaseClass(D.Entries[I]))
2901       Result.Offset -= Layout.getVBaseClassOffset(Base);
2902     else
2903       Result.Offset -= Layout.getBaseClassOffset(Base);
2904     RD = Base;
2905   }
2906   D.Entries.resize(TruncatedElements);
2907   return true;
2908 }
2909 
2910 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2911                                    const CXXRecordDecl *Derived,
2912                                    const CXXRecordDecl *Base,
2913                                    const ASTRecordLayout *RL = nullptr) {
2914   if (!RL) {
2915     if (Derived->isInvalidDecl()) return false;
2916     RL = &Info.Ctx.getASTRecordLayout(Derived);
2917   }
2918 
2919   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2920   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2921   return true;
2922 }
2923 
2924 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2925                              const CXXRecordDecl *DerivedDecl,
2926                              const CXXBaseSpecifier *Base) {
2927   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2928 
2929   if (!Base->isVirtual())
2930     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2931 
2932   SubobjectDesignator &D = Obj.Designator;
2933   if (D.Invalid)
2934     return false;
2935 
2936   // Extract most-derived object and corresponding type.
2937   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2938   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2939     return false;
2940 
2941   // Find the virtual base class.
2942   if (DerivedDecl->isInvalidDecl()) return false;
2943   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2944   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2945   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2946   return true;
2947 }
2948 
2949 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2950                                  QualType Type, LValue &Result) {
2951   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2952                                      PathE = E->path_end();
2953        PathI != PathE; ++PathI) {
2954     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2955                           *PathI))
2956       return false;
2957     Type = (*PathI)->getType();
2958   }
2959   return true;
2960 }
2961 
2962 /// Cast an lvalue referring to a derived class to a known base subobject.
2963 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2964                             const CXXRecordDecl *DerivedRD,
2965                             const CXXRecordDecl *BaseRD) {
2966   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2967                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2968   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2969     llvm_unreachable("Class must be derived from the passed in base class!");
2970 
2971   for (CXXBasePathElement &Elem : Paths.front())
2972     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2973       return false;
2974   return true;
2975 }
2976 
2977 /// Update LVal to refer to the given field, which must be a member of the type
2978 /// currently described by LVal.
2979 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2980                                const FieldDecl *FD,
2981                                const ASTRecordLayout *RL = nullptr) {
2982   if (!RL) {
2983     if (FD->getParent()->isInvalidDecl()) return false;
2984     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2985   }
2986 
2987   unsigned I = FD->getFieldIndex();
2988   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2989   LVal.addDecl(Info, E, FD);
2990   return true;
2991 }
2992 
2993 /// Update LVal to refer to the given indirect field.
2994 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2995                                        LValue &LVal,
2996                                        const IndirectFieldDecl *IFD) {
2997   for (const auto *C : IFD->chain())
2998     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2999       return false;
3000   return true;
3001 }
3002 
3003 /// Get the size of the given type in char units.
3004 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3005                          QualType Type, CharUnits &Size) {
3006   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3007   // extension.
3008   if (Type->isVoidType() || Type->isFunctionType()) {
3009     Size = CharUnits::One();
3010     return true;
3011   }
3012 
3013   if (Type->isDependentType()) {
3014     Info.FFDiag(Loc);
3015     return false;
3016   }
3017 
3018   if (!Type->isConstantSizeType()) {
3019     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3020     // FIXME: Better diagnostic.
3021     Info.FFDiag(Loc);
3022     return false;
3023   }
3024 
3025   Size = Info.Ctx.getTypeSizeInChars(Type);
3026   return true;
3027 }
3028 
3029 /// Update a pointer value to model pointer arithmetic.
3030 /// \param Info - Information about the ongoing evaluation.
3031 /// \param E - The expression being evaluated, for diagnostic purposes.
3032 /// \param LVal - The pointer value to be updated.
3033 /// \param EltTy - The pointee type represented by LVal.
3034 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3035 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3036                                         LValue &LVal, QualType EltTy,
3037                                         APSInt Adjustment) {
3038   CharUnits SizeOfPointee;
3039   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3040     return false;
3041 
3042   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3043   return true;
3044 }
3045 
3046 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3047                                         LValue &LVal, QualType EltTy,
3048                                         int64_t Adjustment) {
3049   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3050                                      APSInt::get(Adjustment));
3051 }
3052 
3053 /// Update an lvalue to refer to a component of a complex number.
3054 /// \param Info - Information about the ongoing evaluation.
3055 /// \param LVal - The lvalue to be updated.
3056 /// \param EltTy - The complex number's component type.
3057 /// \param Imag - False for the real component, true for the imaginary.
3058 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3059                                        LValue &LVal, QualType EltTy,
3060                                        bool Imag) {
3061   if (Imag) {
3062     CharUnits SizeOfComponent;
3063     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3064       return false;
3065     LVal.Offset += SizeOfComponent;
3066   }
3067   LVal.addComplex(Info, E, EltTy, Imag);
3068   return true;
3069 }
3070 
3071 /// Try to evaluate the initializer for a variable declaration.
3072 ///
3073 /// \param Info   Information about the ongoing evaluation.
3074 /// \param E      An expression to be used when printing diagnostics.
3075 /// \param VD     The variable whose initializer should be obtained.
3076 /// \param Frame  The frame in which the variable was created. Must be null
3077 ///               if this variable is not local to the evaluation.
3078 /// \param Result Filled in with a pointer to the value of the variable.
3079 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3080                                 const VarDecl *VD, CallStackFrame *Frame,
3081                                 APValue *&Result, const LValue *LVal) {
3082 
3083   // If this is a parameter to an active constexpr function call, perform
3084   // argument substitution.
3085   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
3086     // Assume arguments of a potential constant expression are unknown
3087     // constant expressions.
3088     if (Info.checkingPotentialConstantExpression())
3089       return false;
3090     if (!Frame || !Frame->Arguments) {
3091       Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD;
3092       return false;
3093     }
3094     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
3095     return true;
3096   }
3097 
3098   // If this is a local variable, dig out its value.
3099   if (Frame) {
3100     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
3101                   : Frame->getCurrentTemporary(VD);
3102     if (!Result) {
3103       // Assume variables referenced within a lambda's call operator that were
3104       // not declared within the call operator are captures and during checking
3105       // of a potential constant expression, assume they are unknown constant
3106       // expressions.
3107       assert(isLambdaCallOperator(Frame->Callee) &&
3108              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3109              "missing value for local variable");
3110       if (Info.checkingPotentialConstantExpression())
3111         return false;
3112       // FIXME: implement capture evaluation during constant expr evaluation.
3113       Info.FFDiag(E->getBeginLoc(),
3114                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3115           << "captures not currently allowed";
3116       return false;
3117     }
3118     return true;
3119   }
3120 
3121   // Dig out the initializer, and use the declaration which it's attached to.
3122   // FIXME: We should eventually check whether the variable has a reachable
3123   // initializing declaration.
3124   const Expr *Init = VD->getAnyInitializer(VD);
3125   if (!Init) {
3126     // Don't diagnose during potential constant expression checking; an
3127     // initializer might be added later.
3128     if (!Info.checkingPotentialConstantExpression()) {
3129       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3130         << VD;
3131       Info.Note(VD->getLocation(), diag::note_declared_at);
3132     }
3133     return false;
3134   }
3135 
3136   if (Init->isValueDependent()) {
3137     // The DeclRefExpr is not value-dependent, but the variable it refers to
3138     // has a value-dependent initializer. This should only happen in
3139     // constant-folding cases, where the variable is not actually of a suitable
3140     // type for use in a constant expression (otherwise the DeclRefExpr would
3141     // have been value-dependent too), so diagnose that.
3142     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3143     if (!Info.checkingPotentialConstantExpression()) {
3144       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3145                          ? diag::note_constexpr_ltor_non_constexpr
3146                          : diag::note_constexpr_ltor_non_integral, 1)
3147           << VD << VD->getType();
3148       Info.Note(VD->getLocation(), diag::note_declared_at);
3149     }
3150     return false;
3151   }
3152 
3153   // If we're currently evaluating the initializer of this declaration, use that
3154   // in-flight value.
3155   if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(),
3156                          VD)) {
3157     Result = Info.EvaluatingDeclValue;
3158     return true;
3159   }
3160 
3161   // Check that we can fold the initializer. In C++, we will have already done
3162   // this in the cases where it matters for conformance.
3163   SmallVector<PartialDiagnosticAt, 8> Notes;
3164   if (!VD->evaluateValue(Notes)) {
3165     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3166               Notes.size() + 1) << VD;
3167     Info.Note(VD->getLocation(), diag::note_declared_at);
3168     Info.addNotes(Notes);
3169     return false;
3170   }
3171 
3172   // Check that the variable is actually usable in constant expressions.
3173   if (!VD->checkInitIsICE()) {
3174     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
3175                  Notes.size() + 1) << VD;
3176     Info.Note(VD->getLocation(), diag::note_declared_at);
3177     Info.addNotes(Notes);
3178   }
3179 
3180   // Never use the initializer of a weak variable, not even for constant
3181   // folding. We can't be sure that this is the definition that will be used.
3182   if (VD->isWeak()) {
3183     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3184     Info.Note(VD->getLocation(), diag::note_declared_at);
3185     return false;
3186   }
3187 
3188   Result = VD->getEvaluatedValue();
3189   return true;
3190 }
3191 
3192 static bool IsConstNonVolatile(QualType T) {
3193   Qualifiers Quals = T.getQualifiers();
3194   return Quals.hasConst() && !Quals.hasVolatile();
3195 }
3196 
3197 /// Get the base index of the given base class within an APValue representing
3198 /// the given derived class.
3199 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3200                              const CXXRecordDecl *Base) {
3201   Base = Base->getCanonicalDecl();
3202   unsigned Index = 0;
3203   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3204          E = Derived->bases_end(); I != E; ++I, ++Index) {
3205     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3206       return Index;
3207   }
3208 
3209   llvm_unreachable("base class missing from derived class's bases list");
3210 }
3211 
3212 /// Extract the value of a character from a string literal.
3213 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3214                                             uint64_t Index) {
3215   assert(!isa<SourceLocExpr>(Lit) &&
3216          "SourceLocExpr should have already been converted to a StringLiteral");
3217 
3218   // FIXME: Support MakeStringConstant
3219   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3220     std::string Str;
3221     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3222     assert(Index <= Str.size() && "Index too large");
3223     return APSInt::getUnsigned(Str.c_str()[Index]);
3224   }
3225 
3226   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3227     Lit = PE->getFunctionName();
3228   const StringLiteral *S = cast<StringLiteral>(Lit);
3229   const ConstantArrayType *CAT =
3230       Info.Ctx.getAsConstantArrayType(S->getType());
3231   assert(CAT && "string literal isn't an array");
3232   QualType CharType = CAT->getElementType();
3233   assert(CharType->isIntegerType() && "unexpected character type");
3234 
3235   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3236                CharType->isUnsignedIntegerType());
3237   if (Index < S->getLength())
3238     Value = S->getCodeUnit(Index);
3239   return Value;
3240 }
3241 
3242 // Expand a string literal into an array of characters.
3243 //
3244 // FIXME: This is inefficient; we should probably introduce something similar
3245 // to the LLVM ConstantDataArray to make this cheaper.
3246 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3247                                 APValue &Result,
3248                                 QualType AllocType = QualType()) {
3249   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3250       AllocType.isNull() ? S->getType() : AllocType);
3251   assert(CAT && "string literal isn't an array");
3252   QualType CharType = CAT->getElementType();
3253   assert(CharType->isIntegerType() && "unexpected character type");
3254 
3255   unsigned Elts = CAT->getSize().getZExtValue();
3256   Result = APValue(APValue::UninitArray(),
3257                    std::min(S->getLength(), Elts), Elts);
3258   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3259                CharType->isUnsignedIntegerType());
3260   if (Result.hasArrayFiller())
3261     Result.getArrayFiller() = APValue(Value);
3262   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3263     Value = S->getCodeUnit(I);
3264     Result.getArrayInitializedElt(I) = APValue(Value);
3265   }
3266 }
3267 
3268 // Expand an array so that it has more than Index filled elements.
3269 static void expandArray(APValue &Array, unsigned Index) {
3270   unsigned Size = Array.getArraySize();
3271   assert(Index < Size);
3272 
3273   // Always at least double the number of elements for which we store a value.
3274   unsigned OldElts = Array.getArrayInitializedElts();
3275   unsigned NewElts = std::max(Index+1, OldElts * 2);
3276   NewElts = std::min(Size, std::max(NewElts, 8u));
3277 
3278   // Copy the data across.
3279   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3280   for (unsigned I = 0; I != OldElts; ++I)
3281     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3282   for (unsigned I = OldElts; I != NewElts; ++I)
3283     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3284   if (NewValue.hasArrayFiller())
3285     NewValue.getArrayFiller() = Array.getArrayFiller();
3286   Array.swap(NewValue);
3287 }
3288 
3289 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3290 /// conversion. If it's of class type, we may assume that the copy operation
3291 /// is trivial. Note that this is never true for a union type with fields
3292 /// (because the copy always "reads" the active member) and always true for
3293 /// a non-class type.
3294 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3295 static bool isReadByLvalueToRvalueConversion(QualType T) {
3296   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3297   return !RD || isReadByLvalueToRvalueConversion(RD);
3298 }
3299 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3300   // FIXME: A trivial copy of a union copies the object representation, even if
3301   // the union is empty.
3302   if (RD->isUnion())
3303     return !RD->field_empty();
3304   if (RD->isEmpty())
3305     return false;
3306 
3307   for (auto *Field : RD->fields())
3308     if (!Field->isUnnamedBitfield() &&
3309         isReadByLvalueToRvalueConversion(Field->getType()))
3310       return true;
3311 
3312   for (auto &BaseSpec : RD->bases())
3313     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3314       return true;
3315 
3316   return false;
3317 }
3318 
3319 /// Diagnose an attempt to read from any unreadable field within the specified
3320 /// type, which might be a class type.
3321 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3322                                   QualType T) {
3323   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3324   if (!RD)
3325     return false;
3326 
3327   if (!RD->hasMutableFields())
3328     return false;
3329 
3330   for (auto *Field : RD->fields()) {
3331     // If we're actually going to read this field in some way, then it can't
3332     // be mutable. If we're in a union, then assigning to a mutable field
3333     // (even an empty one) can change the active member, so that's not OK.
3334     // FIXME: Add core issue number for the union case.
3335     if (Field->isMutable() &&
3336         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3337       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3338       Info.Note(Field->getLocation(), diag::note_declared_at);
3339       return true;
3340     }
3341 
3342     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3343       return true;
3344   }
3345 
3346   for (auto &BaseSpec : RD->bases())
3347     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3348       return true;
3349 
3350   // All mutable fields were empty, and thus not actually read.
3351   return false;
3352 }
3353 
3354 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3355                                         APValue::LValueBase Base,
3356                                         bool MutableSubobject = false) {
3357   // A temporary we created.
3358   if (Base.getCallIndex())
3359     return true;
3360 
3361   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3362   if (!Evaluating)
3363     return false;
3364 
3365   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3366 
3367   switch (Info.IsEvaluatingDecl) {
3368   case EvalInfo::EvaluatingDeclKind::None:
3369     return false;
3370 
3371   case EvalInfo::EvaluatingDeclKind::Ctor:
3372     // The variable whose initializer we're evaluating.
3373     if (BaseD)
3374       return declaresSameEntity(Evaluating, BaseD);
3375 
3376     // A temporary lifetime-extended by the variable whose initializer we're
3377     // evaluating.
3378     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3379       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3380         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3381     return false;
3382 
3383   case EvalInfo::EvaluatingDeclKind::Dtor:
3384     // C++2a [expr.const]p6:
3385     //   [during constant destruction] the lifetime of a and its non-mutable
3386     //   subobjects (but not its mutable subobjects) [are] considered to start
3387     //   within e.
3388     //
3389     // FIXME: We can meaningfully extend this to cover non-const objects, but
3390     // we will need special handling: we should be able to access only
3391     // subobjects of such objects that are themselves declared const.
3392     if (!BaseD ||
3393         !(BaseD->getType().isConstQualified() ||
3394           BaseD->getType()->isReferenceType()) ||
3395         MutableSubobject)
3396       return false;
3397     return declaresSameEntity(Evaluating, BaseD);
3398   }
3399 
3400   llvm_unreachable("unknown evaluating decl kind");
3401 }
3402 
3403 namespace {
3404 /// A handle to a complete object (an object that is not a subobject of
3405 /// another object).
3406 struct CompleteObject {
3407   /// The identity of the object.
3408   APValue::LValueBase Base;
3409   /// The value of the complete object.
3410   APValue *Value;
3411   /// The type of the complete object.
3412   QualType Type;
3413 
3414   CompleteObject() : Value(nullptr) {}
3415   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3416       : Base(Base), Value(Value), Type(Type) {}
3417 
3418   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3419     // If this isn't a "real" access (eg, if it's just accessing the type
3420     // info), allow it. We assume the type doesn't change dynamically for
3421     // subobjects of constexpr objects (even though we'd hit UB here if it
3422     // did). FIXME: Is this right?
3423     if (!isAnyAccess(AK))
3424       return true;
3425 
3426     // In C++14 onwards, it is permitted to read a mutable member whose
3427     // lifetime began within the evaluation.
3428     // FIXME: Should we also allow this in C++11?
3429     if (!Info.getLangOpts().CPlusPlus14)
3430       return false;
3431     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3432   }
3433 
3434   explicit operator bool() const { return !Type.isNull(); }
3435 };
3436 } // end anonymous namespace
3437 
3438 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3439                                  bool IsMutable = false) {
3440   // C++ [basic.type.qualifier]p1:
3441   // - A const object is an object of type const T or a non-mutable subobject
3442   //   of a const object.
3443   if (ObjType.isConstQualified() && !IsMutable)
3444     SubobjType.addConst();
3445   // - A volatile object is an object of type const T or a subobject of a
3446   //   volatile object.
3447   if (ObjType.isVolatileQualified())
3448     SubobjType.addVolatile();
3449   return SubobjType;
3450 }
3451 
3452 /// Find the designated sub-object of an rvalue.
3453 template<typename SubobjectHandler>
3454 typename SubobjectHandler::result_type
3455 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3456               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3457   if (Sub.Invalid)
3458     // A diagnostic will have already been produced.
3459     return handler.failed();
3460   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3461     if (Info.getLangOpts().CPlusPlus11)
3462       Info.FFDiag(E, Sub.isOnePastTheEnd()
3463                          ? diag::note_constexpr_access_past_end
3464                          : diag::note_constexpr_access_unsized_array)
3465           << handler.AccessKind;
3466     else
3467       Info.FFDiag(E);
3468     return handler.failed();
3469   }
3470 
3471   APValue *O = Obj.Value;
3472   QualType ObjType = Obj.Type;
3473   const FieldDecl *LastField = nullptr;
3474   const FieldDecl *VolatileField = nullptr;
3475 
3476   // Walk the designator's path to find the subobject.
3477   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3478     // Reading an indeterminate value is undefined, but assigning over one is OK.
3479     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3480         (O->isIndeterminate() &&
3481          !isValidIndeterminateAccess(handler.AccessKind))) {
3482       if (!Info.checkingPotentialConstantExpression())
3483         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3484             << handler.AccessKind << O->isIndeterminate();
3485       return handler.failed();
3486     }
3487 
3488     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3489     //    const and volatile semantics are not applied on an object under
3490     //    {con,de}struction.
3491     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3492         ObjType->isRecordType() &&
3493         Info.isEvaluatingCtorDtor(
3494             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3495                                          Sub.Entries.begin() + I)) !=
3496                           ConstructionPhase::None) {
3497       ObjType = Info.Ctx.getCanonicalType(ObjType);
3498       ObjType.removeLocalConst();
3499       ObjType.removeLocalVolatile();
3500     }
3501 
3502     // If this is our last pass, check that the final object type is OK.
3503     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3504       // Accesses to volatile objects are prohibited.
3505       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3506         if (Info.getLangOpts().CPlusPlus) {
3507           int DiagKind;
3508           SourceLocation Loc;
3509           const NamedDecl *Decl = nullptr;
3510           if (VolatileField) {
3511             DiagKind = 2;
3512             Loc = VolatileField->getLocation();
3513             Decl = VolatileField;
3514           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3515             DiagKind = 1;
3516             Loc = VD->getLocation();
3517             Decl = VD;
3518           } else {
3519             DiagKind = 0;
3520             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3521               Loc = E->getExprLoc();
3522           }
3523           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3524               << handler.AccessKind << DiagKind << Decl;
3525           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3526         } else {
3527           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3528         }
3529         return handler.failed();
3530       }
3531 
3532       // If we are reading an object of class type, there may still be more
3533       // things we need to check: if there are any mutable subobjects, we
3534       // cannot perform this read. (This only happens when performing a trivial
3535       // copy or assignment.)
3536       if (ObjType->isRecordType() &&
3537           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3538           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3539         return handler.failed();
3540     }
3541 
3542     if (I == N) {
3543       if (!handler.found(*O, ObjType))
3544         return false;
3545 
3546       // If we modified a bit-field, truncate it to the right width.
3547       if (isModification(handler.AccessKind) &&
3548           LastField && LastField->isBitField() &&
3549           !truncateBitfieldValue(Info, E, *O, LastField))
3550         return false;
3551 
3552       return true;
3553     }
3554 
3555     LastField = nullptr;
3556     if (ObjType->isArrayType()) {
3557       // Next subobject is an array element.
3558       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3559       assert(CAT && "vla in literal type?");
3560       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3561       if (CAT->getSize().ule(Index)) {
3562         // Note, it should not be possible to form a pointer with a valid
3563         // designator which points more than one past the end of the array.
3564         if (Info.getLangOpts().CPlusPlus11)
3565           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3566             << handler.AccessKind;
3567         else
3568           Info.FFDiag(E);
3569         return handler.failed();
3570       }
3571 
3572       ObjType = CAT->getElementType();
3573 
3574       if (O->getArrayInitializedElts() > Index)
3575         O = &O->getArrayInitializedElt(Index);
3576       else if (!isRead(handler.AccessKind)) {
3577         expandArray(*O, Index);
3578         O = &O->getArrayInitializedElt(Index);
3579       } else
3580         O = &O->getArrayFiller();
3581     } else if (ObjType->isAnyComplexType()) {
3582       // Next subobject is a complex number.
3583       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3584       if (Index > 1) {
3585         if (Info.getLangOpts().CPlusPlus11)
3586           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3587             << handler.AccessKind;
3588         else
3589           Info.FFDiag(E);
3590         return handler.failed();
3591       }
3592 
3593       ObjType = getSubobjectType(
3594           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3595 
3596       assert(I == N - 1 && "extracting subobject of scalar?");
3597       if (O->isComplexInt()) {
3598         return handler.found(Index ? O->getComplexIntImag()
3599                                    : O->getComplexIntReal(), ObjType);
3600       } else {
3601         assert(O->isComplexFloat());
3602         return handler.found(Index ? O->getComplexFloatImag()
3603                                    : O->getComplexFloatReal(), ObjType);
3604       }
3605     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3606       if (Field->isMutable() &&
3607           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3608         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3609           << handler.AccessKind << Field;
3610         Info.Note(Field->getLocation(), diag::note_declared_at);
3611         return handler.failed();
3612       }
3613 
3614       // Next subobject is a class, struct or union field.
3615       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3616       if (RD->isUnion()) {
3617         const FieldDecl *UnionField = O->getUnionField();
3618         if (!UnionField ||
3619             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3620           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3621             // Placement new onto an inactive union member makes it active.
3622             O->setUnion(Field, APValue());
3623           } else {
3624             // FIXME: If O->getUnionValue() is absent, report that there's no
3625             // active union member rather than reporting the prior active union
3626             // member. We'll need to fix nullptr_t to not use APValue() as its
3627             // representation first.
3628             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3629                 << handler.AccessKind << Field << !UnionField << UnionField;
3630             return handler.failed();
3631           }
3632         }
3633         O = &O->getUnionValue();
3634       } else
3635         O = &O->getStructField(Field->getFieldIndex());
3636 
3637       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3638       LastField = Field;
3639       if (Field->getType().isVolatileQualified())
3640         VolatileField = Field;
3641     } else {
3642       // Next subobject is a base class.
3643       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3644       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3645       O = &O->getStructBase(getBaseIndex(Derived, Base));
3646 
3647       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3648     }
3649   }
3650 }
3651 
3652 namespace {
3653 struct ExtractSubobjectHandler {
3654   EvalInfo &Info;
3655   const Expr *E;
3656   APValue &Result;
3657   const AccessKinds AccessKind;
3658 
3659   typedef bool result_type;
3660   bool failed() { return false; }
3661   bool found(APValue &Subobj, QualType SubobjType) {
3662     Result = Subobj;
3663     if (AccessKind == AK_ReadObjectRepresentation)
3664       return true;
3665     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3666   }
3667   bool found(APSInt &Value, QualType SubobjType) {
3668     Result = APValue(Value);
3669     return true;
3670   }
3671   bool found(APFloat &Value, QualType SubobjType) {
3672     Result = APValue(Value);
3673     return true;
3674   }
3675 };
3676 } // end anonymous namespace
3677 
3678 /// Extract the designated sub-object of an rvalue.
3679 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3680                              const CompleteObject &Obj,
3681                              const SubobjectDesignator &Sub, APValue &Result,
3682                              AccessKinds AK = AK_Read) {
3683   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3684   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3685   return findSubobject(Info, E, Obj, Sub, Handler);
3686 }
3687 
3688 namespace {
3689 struct ModifySubobjectHandler {
3690   EvalInfo &Info;
3691   APValue &NewVal;
3692   const Expr *E;
3693 
3694   typedef bool result_type;
3695   static const AccessKinds AccessKind = AK_Assign;
3696 
3697   bool checkConst(QualType QT) {
3698     // Assigning to a const object has undefined behavior.
3699     if (QT.isConstQualified()) {
3700       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3701       return false;
3702     }
3703     return true;
3704   }
3705 
3706   bool failed() { return false; }
3707   bool found(APValue &Subobj, QualType SubobjType) {
3708     if (!checkConst(SubobjType))
3709       return false;
3710     // We've been given ownership of NewVal, so just swap it in.
3711     Subobj.swap(NewVal);
3712     return true;
3713   }
3714   bool found(APSInt &Value, QualType SubobjType) {
3715     if (!checkConst(SubobjType))
3716       return false;
3717     if (!NewVal.isInt()) {
3718       // Maybe trying to write a cast pointer value into a complex?
3719       Info.FFDiag(E);
3720       return false;
3721     }
3722     Value = NewVal.getInt();
3723     return true;
3724   }
3725   bool found(APFloat &Value, QualType SubobjType) {
3726     if (!checkConst(SubobjType))
3727       return false;
3728     Value = NewVal.getFloat();
3729     return true;
3730   }
3731 };
3732 } // end anonymous namespace
3733 
3734 const AccessKinds ModifySubobjectHandler::AccessKind;
3735 
3736 /// Update the designated sub-object of an rvalue to the given value.
3737 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3738                             const CompleteObject &Obj,
3739                             const SubobjectDesignator &Sub,
3740                             APValue &NewVal) {
3741   ModifySubobjectHandler Handler = { Info, NewVal, E };
3742   return findSubobject(Info, E, Obj, Sub, Handler);
3743 }
3744 
3745 /// Find the position where two subobject designators diverge, or equivalently
3746 /// the length of the common initial subsequence.
3747 static unsigned FindDesignatorMismatch(QualType ObjType,
3748                                        const SubobjectDesignator &A,
3749                                        const SubobjectDesignator &B,
3750                                        bool &WasArrayIndex) {
3751   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3752   for (/**/; I != N; ++I) {
3753     if (!ObjType.isNull() &&
3754         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3755       // Next subobject is an array element.
3756       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3757         WasArrayIndex = true;
3758         return I;
3759       }
3760       if (ObjType->isAnyComplexType())
3761         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3762       else
3763         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3764     } else {
3765       if (A.Entries[I].getAsBaseOrMember() !=
3766           B.Entries[I].getAsBaseOrMember()) {
3767         WasArrayIndex = false;
3768         return I;
3769       }
3770       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3771         // Next subobject is a field.
3772         ObjType = FD->getType();
3773       else
3774         // Next subobject is a base class.
3775         ObjType = QualType();
3776     }
3777   }
3778   WasArrayIndex = false;
3779   return I;
3780 }
3781 
3782 /// Determine whether the given subobject designators refer to elements of the
3783 /// same array object.
3784 static bool AreElementsOfSameArray(QualType ObjType,
3785                                    const SubobjectDesignator &A,
3786                                    const SubobjectDesignator &B) {
3787   if (A.Entries.size() != B.Entries.size())
3788     return false;
3789 
3790   bool IsArray = A.MostDerivedIsArrayElement;
3791   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3792     // A is a subobject of the array element.
3793     return false;
3794 
3795   // If A (and B) designates an array element, the last entry will be the array
3796   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3797   // of length 1' case, and the entire path must match.
3798   bool WasArrayIndex;
3799   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3800   return CommonLength >= A.Entries.size() - IsArray;
3801 }
3802 
3803 /// Find the complete object to which an LValue refers.
3804 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3805                                          AccessKinds AK, const LValue &LVal,
3806                                          QualType LValType) {
3807   if (LVal.InvalidBase) {
3808     Info.FFDiag(E);
3809     return CompleteObject();
3810   }
3811 
3812   if (!LVal.Base) {
3813     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3814     return CompleteObject();
3815   }
3816 
3817   CallStackFrame *Frame = nullptr;
3818   unsigned Depth = 0;
3819   if (LVal.getLValueCallIndex()) {
3820     std::tie(Frame, Depth) =
3821         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3822     if (!Frame) {
3823       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3824         << AK << LVal.Base.is<const ValueDecl*>();
3825       NoteLValueLocation(Info, LVal.Base);
3826       return CompleteObject();
3827     }
3828   }
3829 
3830   bool IsAccess = isAnyAccess(AK);
3831 
3832   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3833   // is not a constant expression (even if the object is non-volatile). We also
3834   // apply this rule to C++98, in order to conform to the expected 'volatile'
3835   // semantics.
3836   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3837     if (Info.getLangOpts().CPlusPlus)
3838       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3839         << AK << LValType;
3840     else
3841       Info.FFDiag(E);
3842     return CompleteObject();
3843   }
3844 
3845   // Compute value storage location and type of base object.
3846   APValue *BaseVal = nullptr;
3847   QualType BaseType = getType(LVal.Base);
3848 
3849   if (const ConstantExpr *CE =
3850           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3851     /// Nested immediate invocation have been previously removed so if we found
3852     /// a ConstantExpr it can only be the EvaluatingDecl.
3853     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3854     (void)CE;
3855     BaseVal = Info.EvaluatingDeclValue;
3856   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3857     // Allow reading from a GUID declaration.
3858     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3859       if (isModification(AK)) {
3860         // All the remaining cases do not permit modification of the object.
3861         Info.FFDiag(E, diag::note_constexpr_modify_global);
3862         return CompleteObject();
3863       }
3864       APValue &V = GD->getAsAPValue();
3865       if (V.isAbsent()) {
3866         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3867             << GD->getType();
3868         return CompleteObject();
3869       }
3870       return CompleteObject(LVal.Base, &V, GD->getType());
3871     }
3872 
3873     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3874     // In C++11, constexpr, non-volatile variables initialized with constant
3875     // expressions are constant expressions too. Inside constexpr functions,
3876     // parameters are constant expressions even if they're non-const.
3877     // In C++1y, objects local to a constant expression (those with a Frame) are
3878     // both readable and writable inside constant expressions.
3879     // In C, such things can also be folded, although they are not ICEs.
3880     const VarDecl *VD = dyn_cast<VarDecl>(D);
3881     if (VD) {
3882       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3883         VD = VDef;
3884     }
3885     if (!VD || VD->isInvalidDecl()) {
3886       Info.FFDiag(E);
3887       return CompleteObject();
3888     }
3889 
3890     // In OpenCL if a variable is in constant address space it is a const value.
3891     bool IsConstant = BaseType.isConstQualified() ||
3892                       (Info.getLangOpts().OpenCL &&
3893                        BaseType.getAddressSpace() == LangAS::opencl_constant);
3894 
3895     // Unless we're looking at a local variable or argument in a constexpr call,
3896     // the variable we're reading must be const.
3897     if (!Frame) {
3898       if (Info.getLangOpts().CPlusPlus14 &&
3899           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3900         // OK, we can read and modify an object if we're in the process of
3901         // evaluating its initializer, because its lifetime began in this
3902         // evaluation.
3903       } else if (isModification(AK)) {
3904         // All the remaining cases do not permit modification of the object.
3905         Info.FFDiag(E, diag::note_constexpr_modify_global);
3906         return CompleteObject();
3907       } else if (VD->isConstexpr()) {
3908         // OK, we can read this variable.
3909       } else if (BaseType->isIntegralOrEnumerationType()) {
3910         // In OpenCL if a variable is in constant address space it is a const
3911         // value.
3912         if (!IsConstant) {
3913           if (!IsAccess)
3914             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3915           if (Info.getLangOpts().CPlusPlus) {
3916             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3917             Info.Note(VD->getLocation(), diag::note_declared_at);
3918           } else {
3919             Info.FFDiag(E);
3920           }
3921           return CompleteObject();
3922         }
3923       } else if (!IsAccess) {
3924         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3925       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
3926                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
3927         // This variable might end up being constexpr. Don't diagnose it yet.
3928       } else if (IsConstant) {
3929         // Keep evaluating to see what we can do. In particular, we support
3930         // folding of const floating-point types, in order to make static const
3931         // data members of such types (supported as an extension) more useful.
3932         if (Info.getLangOpts().CPlusPlus) {
3933           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
3934                               ? diag::note_constexpr_ltor_non_constexpr
3935                               : diag::note_constexpr_ltor_non_integral, 1)
3936               << VD << BaseType;
3937           Info.Note(VD->getLocation(), diag::note_declared_at);
3938         } else {
3939           Info.CCEDiag(E);
3940         }
3941       } else {
3942         // Never allow reading a non-const value.
3943         if (Info.getLangOpts().CPlusPlus) {
3944           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3945                              ? diag::note_constexpr_ltor_non_constexpr
3946                              : diag::note_constexpr_ltor_non_integral, 1)
3947               << VD << BaseType;
3948           Info.Note(VD->getLocation(), diag::note_declared_at);
3949         } else {
3950           Info.FFDiag(E);
3951         }
3952         return CompleteObject();
3953       }
3954     }
3955 
3956     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3957       return CompleteObject();
3958   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3959     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3960     if (!Alloc) {
3961       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3962       return CompleteObject();
3963     }
3964     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3965                           LVal.Base.getDynamicAllocType());
3966   } else {
3967     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3968 
3969     if (!Frame) {
3970       if (const MaterializeTemporaryExpr *MTE =
3971               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3972         assert(MTE->getStorageDuration() == SD_Static &&
3973                "should have a frame for a non-global materialized temporary");
3974 
3975         // Per C++1y [expr.const]p2:
3976         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3977         //   - a [...] glvalue of integral or enumeration type that refers to
3978         //     a non-volatile const object [...]
3979         //   [...]
3980         //   - a [...] glvalue of literal type that refers to a non-volatile
3981         //     object whose lifetime began within the evaluation of e.
3982         //
3983         // C++11 misses the 'began within the evaluation of e' check and
3984         // instead allows all temporaries, including things like:
3985         //   int &&r = 1;
3986         //   int x = ++r;
3987         //   constexpr int k = r;
3988         // Therefore we use the C++14 rules in C++11 too.
3989         //
3990         // Note that temporaries whose lifetimes began while evaluating a
3991         // variable's constructor are not usable while evaluating the
3992         // corresponding destructor, not even if they're of const-qualified
3993         // types.
3994         if (!(BaseType.isConstQualified() &&
3995               BaseType->isIntegralOrEnumerationType()) &&
3996             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3997           if (!IsAccess)
3998             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3999           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4000           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4001           return CompleteObject();
4002         }
4003 
4004         BaseVal = MTE->getOrCreateValue(false);
4005         assert(BaseVal && "got reference to unevaluated temporary");
4006       } else {
4007         if (!IsAccess)
4008           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4009         APValue Val;
4010         LVal.moveInto(Val);
4011         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4012             << AK
4013             << Val.getAsString(Info.Ctx,
4014                                Info.Ctx.getLValueReferenceType(LValType));
4015         NoteLValueLocation(Info, LVal.Base);
4016         return CompleteObject();
4017       }
4018     } else {
4019       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4020       assert(BaseVal && "missing value for temporary");
4021     }
4022   }
4023 
4024   // In C++14, we can't safely access any mutable state when we might be
4025   // evaluating after an unmodeled side effect.
4026   //
4027   // FIXME: Not all local state is mutable. Allow local constant subobjects
4028   // to be read here (but take care with 'mutable' fields).
4029   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4030        Info.EvalStatus.HasSideEffects) ||
4031       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
4032     return CompleteObject();
4033 
4034   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4035 }
4036 
4037 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4038 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4039 /// glvalue referred to by an entity of reference type.
4040 ///
4041 /// \param Info - Information about the ongoing evaluation.
4042 /// \param Conv - The expression for which we are performing the conversion.
4043 ///               Used for diagnostics.
4044 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4045 ///               case of a non-class type).
4046 /// \param LVal - The glvalue on which we are attempting to perform this action.
4047 /// \param RVal - The produced value will be placed here.
4048 /// \param WantObjectRepresentation - If true, we're looking for the object
4049 ///               representation rather than the value, and in particular,
4050 ///               there is no requirement that the result be fully initialized.
4051 static bool
4052 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4053                                const LValue &LVal, APValue &RVal,
4054                                bool WantObjectRepresentation = false) {
4055   if (LVal.Designator.Invalid)
4056     return false;
4057 
4058   // Check for special cases where there is no existing APValue to look at.
4059   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4060 
4061   AccessKinds AK =
4062       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4063 
4064   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4065     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4066       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4067       // initializer until now for such expressions. Such an expression can't be
4068       // an ICE in C, so this only matters for fold.
4069       if (Type.isVolatileQualified()) {
4070         Info.FFDiag(Conv);
4071         return false;
4072       }
4073       APValue Lit;
4074       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4075         return false;
4076       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4077       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4078     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4079       // Special-case character extraction so we don't have to construct an
4080       // APValue for the whole string.
4081       assert(LVal.Designator.Entries.size() <= 1 &&
4082              "Can only read characters from string literals");
4083       if (LVal.Designator.Entries.empty()) {
4084         // Fail for now for LValue to RValue conversion of an array.
4085         // (This shouldn't show up in C/C++, but it could be triggered by a
4086         // weird EvaluateAsRValue call from a tool.)
4087         Info.FFDiag(Conv);
4088         return false;
4089       }
4090       if (LVal.Designator.isOnePastTheEnd()) {
4091         if (Info.getLangOpts().CPlusPlus11)
4092           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4093         else
4094           Info.FFDiag(Conv);
4095         return false;
4096       }
4097       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4098       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4099       return true;
4100     }
4101   }
4102 
4103   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4104   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4105 }
4106 
4107 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4108 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4109                              QualType LValType, APValue &Val) {
4110   if (LVal.Designator.Invalid)
4111     return false;
4112 
4113   if (!Info.getLangOpts().CPlusPlus14) {
4114     Info.FFDiag(E);
4115     return false;
4116   }
4117 
4118   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4119   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4120 }
4121 
4122 namespace {
4123 struct CompoundAssignSubobjectHandler {
4124   EvalInfo &Info;
4125   const CompoundAssignOperator *E;
4126   QualType PromotedLHSType;
4127   BinaryOperatorKind Opcode;
4128   const APValue &RHS;
4129 
4130   static const AccessKinds AccessKind = AK_Assign;
4131 
4132   typedef bool result_type;
4133 
4134   bool checkConst(QualType QT) {
4135     // Assigning to a const object has undefined behavior.
4136     if (QT.isConstQualified()) {
4137       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4138       return false;
4139     }
4140     return true;
4141   }
4142 
4143   bool failed() { return false; }
4144   bool found(APValue &Subobj, QualType SubobjType) {
4145     switch (Subobj.getKind()) {
4146     case APValue::Int:
4147       return found(Subobj.getInt(), SubobjType);
4148     case APValue::Float:
4149       return found(Subobj.getFloat(), SubobjType);
4150     case APValue::ComplexInt:
4151     case APValue::ComplexFloat:
4152       // FIXME: Implement complex compound assignment.
4153       Info.FFDiag(E);
4154       return false;
4155     case APValue::LValue:
4156       return foundPointer(Subobj, SubobjType);
4157     case APValue::Vector:
4158       return foundVector(Subobj, SubobjType);
4159     default:
4160       // FIXME: can this happen?
4161       Info.FFDiag(E);
4162       return false;
4163     }
4164   }
4165 
4166   bool foundVector(APValue &Value, QualType SubobjType) {
4167     if (!checkConst(SubobjType))
4168       return false;
4169 
4170     if (!SubobjType->isVectorType()) {
4171       Info.FFDiag(E);
4172       return false;
4173     }
4174     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4175   }
4176 
4177   bool found(APSInt &Value, QualType SubobjType) {
4178     if (!checkConst(SubobjType))
4179       return false;
4180 
4181     if (!SubobjType->isIntegerType()) {
4182       // We don't support compound assignment on integer-cast-to-pointer
4183       // values.
4184       Info.FFDiag(E);
4185       return false;
4186     }
4187 
4188     if (RHS.isInt()) {
4189       APSInt LHS =
4190           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4191       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4192         return false;
4193       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4194       return true;
4195     } else if (RHS.isFloat()) {
4196       APFloat FValue(0.0);
4197       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
4198                                   FValue) &&
4199              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4200              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4201                                   Value);
4202     }
4203 
4204     Info.FFDiag(E);
4205     return false;
4206   }
4207   bool found(APFloat &Value, QualType SubobjType) {
4208     return checkConst(SubobjType) &&
4209            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4210                                   Value) &&
4211            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4212            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4213   }
4214   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4215     if (!checkConst(SubobjType))
4216       return false;
4217 
4218     QualType PointeeType;
4219     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4220       PointeeType = PT->getPointeeType();
4221 
4222     if (PointeeType.isNull() || !RHS.isInt() ||
4223         (Opcode != BO_Add && Opcode != BO_Sub)) {
4224       Info.FFDiag(E);
4225       return false;
4226     }
4227 
4228     APSInt Offset = RHS.getInt();
4229     if (Opcode == BO_Sub)
4230       negateAsSigned(Offset);
4231 
4232     LValue LVal;
4233     LVal.setFrom(Info.Ctx, Subobj);
4234     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4235       return false;
4236     LVal.moveInto(Subobj);
4237     return true;
4238   }
4239 };
4240 } // end anonymous namespace
4241 
4242 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4243 
4244 /// Perform a compound assignment of LVal <op>= RVal.
4245 static bool handleCompoundAssignment(EvalInfo &Info,
4246                                      const CompoundAssignOperator *E,
4247                                      const LValue &LVal, QualType LValType,
4248                                      QualType PromotedLValType,
4249                                      BinaryOperatorKind Opcode,
4250                                      const APValue &RVal) {
4251   if (LVal.Designator.Invalid)
4252     return false;
4253 
4254   if (!Info.getLangOpts().CPlusPlus14) {
4255     Info.FFDiag(E);
4256     return false;
4257   }
4258 
4259   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4260   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4261                                              RVal };
4262   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4263 }
4264 
4265 namespace {
4266 struct IncDecSubobjectHandler {
4267   EvalInfo &Info;
4268   const UnaryOperator *E;
4269   AccessKinds AccessKind;
4270   APValue *Old;
4271 
4272   typedef bool result_type;
4273 
4274   bool checkConst(QualType QT) {
4275     // Assigning to a const object has undefined behavior.
4276     if (QT.isConstQualified()) {
4277       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4278       return false;
4279     }
4280     return true;
4281   }
4282 
4283   bool failed() { return false; }
4284   bool found(APValue &Subobj, QualType SubobjType) {
4285     // Stash the old value. Also clear Old, so we don't clobber it later
4286     // if we're post-incrementing a complex.
4287     if (Old) {
4288       *Old = Subobj;
4289       Old = nullptr;
4290     }
4291 
4292     switch (Subobj.getKind()) {
4293     case APValue::Int:
4294       return found(Subobj.getInt(), SubobjType);
4295     case APValue::Float:
4296       return found(Subobj.getFloat(), SubobjType);
4297     case APValue::ComplexInt:
4298       return found(Subobj.getComplexIntReal(),
4299                    SubobjType->castAs<ComplexType>()->getElementType()
4300                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4301     case APValue::ComplexFloat:
4302       return found(Subobj.getComplexFloatReal(),
4303                    SubobjType->castAs<ComplexType>()->getElementType()
4304                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4305     case APValue::LValue:
4306       return foundPointer(Subobj, SubobjType);
4307     default:
4308       // FIXME: can this happen?
4309       Info.FFDiag(E);
4310       return false;
4311     }
4312   }
4313   bool found(APSInt &Value, QualType SubobjType) {
4314     if (!checkConst(SubobjType))
4315       return false;
4316 
4317     if (!SubobjType->isIntegerType()) {
4318       // We don't support increment / decrement on integer-cast-to-pointer
4319       // values.
4320       Info.FFDiag(E);
4321       return false;
4322     }
4323 
4324     if (Old) *Old = APValue(Value);
4325 
4326     // bool arithmetic promotes to int, and the conversion back to bool
4327     // doesn't reduce mod 2^n, so special-case it.
4328     if (SubobjType->isBooleanType()) {
4329       if (AccessKind == AK_Increment)
4330         Value = 1;
4331       else
4332         Value = !Value;
4333       return true;
4334     }
4335 
4336     bool WasNegative = Value.isNegative();
4337     if (AccessKind == AK_Increment) {
4338       ++Value;
4339 
4340       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4341         APSInt ActualValue(Value, /*IsUnsigned*/true);
4342         return HandleOverflow(Info, E, ActualValue, SubobjType);
4343       }
4344     } else {
4345       --Value;
4346 
4347       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4348         unsigned BitWidth = Value.getBitWidth();
4349         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4350         ActualValue.setBit(BitWidth);
4351         return HandleOverflow(Info, E, ActualValue, SubobjType);
4352       }
4353     }
4354     return true;
4355   }
4356   bool found(APFloat &Value, QualType SubobjType) {
4357     if (!checkConst(SubobjType))
4358       return false;
4359 
4360     if (Old) *Old = APValue(Value);
4361 
4362     APFloat One(Value.getSemantics(), 1);
4363     if (AccessKind == AK_Increment)
4364       Value.add(One, APFloat::rmNearestTiesToEven);
4365     else
4366       Value.subtract(One, APFloat::rmNearestTiesToEven);
4367     return true;
4368   }
4369   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4370     if (!checkConst(SubobjType))
4371       return false;
4372 
4373     QualType PointeeType;
4374     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4375       PointeeType = PT->getPointeeType();
4376     else {
4377       Info.FFDiag(E);
4378       return false;
4379     }
4380 
4381     LValue LVal;
4382     LVal.setFrom(Info.Ctx, Subobj);
4383     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4384                                      AccessKind == AK_Increment ? 1 : -1))
4385       return false;
4386     LVal.moveInto(Subobj);
4387     return true;
4388   }
4389 };
4390 } // end anonymous namespace
4391 
4392 /// Perform an increment or decrement on LVal.
4393 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4394                          QualType LValType, bool IsIncrement, APValue *Old) {
4395   if (LVal.Designator.Invalid)
4396     return false;
4397 
4398   if (!Info.getLangOpts().CPlusPlus14) {
4399     Info.FFDiag(E);
4400     return false;
4401   }
4402 
4403   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4404   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4405   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4406   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4407 }
4408 
4409 /// Build an lvalue for the object argument of a member function call.
4410 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4411                                    LValue &This) {
4412   if (Object->getType()->isPointerType() && Object->isRValue())
4413     return EvaluatePointer(Object, This, Info);
4414 
4415   if (Object->isGLValue())
4416     return EvaluateLValue(Object, This, Info);
4417 
4418   if (Object->getType()->isLiteralType(Info.Ctx))
4419     return EvaluateTemporary(Object, This, Info);
4420 
4421   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4422   return false;
4423 }
4424 
4425 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4426 /// lvalue referring to the result.
4427 ///
4428 /// \param Info - Information about the ongoing evaluation.
4429 /// \param LV - An lvalue referring to the base of the member pointer.
4430 /// \param RHS - The member pointer expression.
4431 /// \param IncludeMember - Specifies whether the member itself is included in
4432 ///        the resulting LValue subobject designator. This is not possible when
4433 ///        creating a bound member function.
4434 /// \return The field or method declaration to which the member pointer refers,
4435 ///         or 0 if evaluation fails.
4436 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4437                                                   QualType LVType,
4438                                                   LValue &LV,
4439                                                   const Expr *RHS,
4440                                                   bool IncludeMember = true) {
4441   MemberPtr MemPtr;
4442   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4443     return nullptr;
4444 
4445   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4446   // member value, the behavior is undefined.
4447   if (!MemPtr.getDecl()) {
4448     // FIXME: Specific diagnostic.
4449     Info.FFDiag(RHS);
4450     return nullptr;
4451   }
4452 
4453   if (MemPtr.isDerivedMember()) {
4454     // This is a member of some derived class. Truncate LV appropriately.
4455     // The end of the derived-to-base path for the base object must match the
4456     // derived-to-base path for the member pointer.
4457     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4458         LV.Designator.Entries.size()) {
4459       Info.FFDiag(RHS);
4460       return nullptr;
4461     }
4462     unsigned PathLengthToMember =
4463         LV.Designator.Entries.size() - MemPtr.Path.size();
4464     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4465       const CXXRecordDecl *LVDecl = getAsBaseClass(
4466           LV.Designator.Entries[PathLengthToMember + I]);
4467       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4468       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4469         Info.FFDiag(RHS);
4470         return nullptr;
4471       }
4472     }
4473 
4474     // Truncate the lvalue to the appropriate derived class.
4475     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4476                             PathLengthToMember))
4477       return nullptr;
4478   } else if (!MemPtr.Path.empty()) {
4479     // Extend the LValue path with the member pointer's path.
4480     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4481                                   MemPtr.Path.size() + IncludeMember);
4482 
4483     // Walk down to the appropriate base class.
4484     if (const PointerType *PT = LVType->getAs<PointerType>())
4485       LVType = PT->getPointeeType();
4486     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4487     assert(RD && "member pointer access on non-class-type expression");
4488     // The first class in the path is that of the lvalue.
4489     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4490       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4491       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4492         return nullptr;
4493       RD = Base;
4494     }
4495     // Finally cast to the class containing the member.
4496     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4497                                 MemPtr.getContainingRecord()))
4498       return nullptr;
4499   }
4500 
4501   // Add the member. Note that we cannot build bound member functions here.
4502   if (IncludeMember) {
4503     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4504       if (!HandleLValueMember(Info, RHS, LV, FD))
4505         return nullptr;
4506     } else if (const IndirectFieldDecl *IFD =
4507                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4508       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4509         return nullptr;
4510     } else {
4511       llvm_unreachable("can't construct reference to bound member function");
4512     }
4513   }
4514 
4515   return MemPtr.getDecl();
4516 }
4517 
4518 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4519                                                   const BinaryOperator *BO,
4520                                                   LValue &LV,
4521                                                   bool IncludeMember = true) {
4522   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4523 
4524   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4525     if (Info.noteFailure()) {
4526       MemberPtr MemPtr;
4527       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4528     }
4529     return nullptr;
4530   }
4531 
4532   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4533                                    BO->getRHS(), IncludeMember);
4534 }
4535 
4536 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4537 /// the provided lvalue, which currently refers to the base object.
4538 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4539                                     LValue &Result) {
4540   SubobjectDesignator &D = Result.Designator;
4541   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4542     return false;
4543 
4544   QualType TargetQT = E->getType();
4545   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4546     TargetQT = PT->getPointeeType();
4547 
4548   // Check this cast lands within the final derived-to-base subobject path.
4549   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4550     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4551       << D.MostDerivedType << TargetQT;
4552     return false;
4553   }
4554 
4555   // Check the type of the final cast. We don't need to check the path,
4556   // since a cast can only be formed if the path is unique.
4557   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4558   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4559   const CXXRecordDecl *FinalType;
4560   if (NewEntriesSize == D.MostDerivedPathLength)
4561     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4562   else
4563     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4564   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4565     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4566       << D.MostDerivedType << TargetQT;
4567     return false;
4568   }
4569 
4570   // Truncate the lvalue to the appropriate derived class.
4571   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4572 }
4573 
4574 /// Get the value to use for a default-initialized object of type T.
4575 /// Return false if it encounters something invalid.
4576 static bool getDefaultInitValue(QualType T, APValue &Result) {
4577   bool Success = true;
4578   if (auto *RD = T->getAsCXXRecordDecl()) {
4579     if (RD->isInvalidDecl()) {
4580       Result = APValue();
4581       return false;
4582     }
4583     if (RD->isUnion()) {
4584       Result = APValue((const FieldDecl *)nullptr);
4585       return true;
4586     }
4587     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4588                      std::distance(RD->field_begin(), RD->field_end()));
4589 
4590     unsigned Index = 0;
4591     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4592                                                   End = RD->bases_end();
4593          I != End; ++I, ++Index)
4594       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4595 
4596     for (const auto *I : RD->fields()) {
4597       if (I->isUnnamedBitfield())
4598         continue;
4599       Success &= getDefaultInitValue(I->getType(),
4600                                      Result.getStructField(I->getFieldIndex()));
4601     }
4602     return Success;
4603   }
4604 
4605   if (auto *AT =
4606           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4607     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4608     if (Result.hasArrayFiller())
4609       Success &=
4610           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4611 
4612     return Success;
4613   }
4614 
4615   Result = APValue::IndeterminateValue();
4616   return true;
4617 }
4618 
4619 namespace {
4620 enum EvalStmtResult {
4621   /// Evaluation failed.
4622   ESR_Failed,
4623   /// Hit a 'return' statement.
4624   ESR_Returned,
4625   /// Evaluation succeeded.
4626   ESR_Succeeded,
4627   /// Hit a 'continue' statement.
4628   ESR_Continue,
4629   /// Hit a 'break' statement.
4630   ESR_Break,
4631   /// Still scanning for 'case' or 'default' statement.
4632   ESR_CaseNotFound
4633 };
4634 }
4635 
4636 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4637   // We don't need to evaluate the initializer for a static local.
4638   if (!VD->hasLocalStorage())
4639     return true;
4640 
4641   LValue Result;
4642   APValue &Val =
4643       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4644 
4645   const Expr *InitE = VD->getInit();
4646   if (!InitE)
4647     return getDefaultInitValue(VD->getType(), Val);
4648 
4649   if (InitE->isValueDependent())
4650     return false;
4651 
4652   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4653     // Wipe out any partially-computed value, to allow tracking that this
4654     // evaluation failed.
4655     Val = APValue();
4656     return false;
4657   }
4658 
4659   return true;
4660 }
4661 
4662 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4663   bool OK = true;
4664 
4665   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4666     OK &= EvaluateVarDecl(Info, VD);
4667 
4668   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4669     for (auto *BD : DD->bindings())
4670       if (auto *VD = BD->getHoldingVar())
4671         OK &= EvaluateDecl(Info, VD);
4672 
4673   return OK;
4674 }
4675 
4676 
4677 /// Evaluate a condition (either a variable declaration or an expression).
4678 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4679                          const Expr *Cond, bool &Result) {
4680   FullExpressionRAII Scope(Info);
4681   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4682     return false;
4683   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4684     return false;
4685   return Scope.destroy();
4686 }
4687 
4688 namespace {
4689 /// A location where the result (returned value) of evaluating a
4690 /// statement should be stored.
4691 struct StmtResult {
4692   /// The APValue that should be filled in with the returned value.
4693   APValue &Value;
4694   /// The location containing the result, if any (used to support RVO).
4695   const LValue *Slot;
4696 };
4697 
4698 struct TempVersionRAII {
4699   CallStackFrame &Frame;
4700 
4701   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4702     Frame.pushTempVersion();
4703   }
4704 
4705   ~TempVersionRAII() {
4706     Frame.popTempVersion();
4707   }
4708 };
4709 
4710 }
4711 
4712 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4713                                    const Stmt *S,
4714                                    const SwitchCase *SC = nullptr);
4715 
4716 /// Evaluate the body of a loop, and translate the result as appropriate.
4717 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4718                                        const Stmt *Body,
4719                                        const SwitchCase *Case = nullptr) {
4720   BlockScopeRAII Scope(Info);
4721 
4722   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4723   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4724     ESR = ESR_Failed;
4725 
4726   switch (ESR) {
4727   case ESR_Break:
4728     return ESR_Succeeded;
4729   case ESR_Succeeded:
4730   case ESR_Continue:
4731     return ESR_Continue;
4732   case ESR_Failed:
4733   case ESR_Returned:
4734   case ESR_CaseNotFound:
4735     return ESR;
4736   }
4737   llvm_unreachable("Invalid EvalStmtResult!");
4738 }
4739 
4740 /// Evaluate a switch statement.
4741 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4742                                      const SwitchStmt *SS) {
4743   BlockScopeRAII Scope(Info);
4744 
4745   // Evaluate the switch condition.
4746   APSInt Value;
4747   {
4748     if (const Stmt *Init = SS->getInit()) {
4749       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4750       if (ESR != ESR_Succeeded) {
4751         if (ESR != ESR_Failed && !Scope.destroy())
4752           ESR = ESR_Failed;
4753         return ESR;
4754       }
4755     }
4756 
4757     FullExpressionRAII CondScope(Info);
4758     if (SS->getConditionVariable() &&
4759         !EvaluateDecl(Info, SS->getConditionVariable()))
4760       return ESR_Failed;
4761     if (!EvaluateInteger(SS->getCond(), Value, Info))
4762       return ESR_Failed;
4763     if (!CondScope.destroy())
4764       return ESR_Failed;
4765   }
4766 
4767   // Find the switch case corresponding to the value of the condition.
4768   // FIXME: Cache this lookup.
4769   const SwitchCase *Found = nullptr;
4770   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4771        SC = SC->getNextSwitchCase()) {
4772     if (isa<DefaultStmt>(SC)) {
4773       Found = SC;
4774       continue;
4775     }
4776 
4777     const CaseStmt *CS = cast<CaseStmt>(SC);
4778     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4779     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4780                               : LHS;
4781     if (LHS <= Value && Value <= RHS) {
4782       Found = SC;
4783       break;
4784     }
4785   }
4786 
4787   if (!Found)
4788     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4789 
4790   // Search the switch body for the switch case and evaluate it from there.
4791   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4792   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4793     return ESR_Failed;
4794 
4795   switch (ESR) {
4796   case ESR_Break:
4797     return ESR_Succeeded;
4798   case ESR_Succeeded:
4799   case ESR_Continue:
4800   case ESR_Failed:
4801   case ESR_Returned:
4802     return ESR;
4803   case ESR_CaseNotFound:
4804     // This can only happen if the switch case is nested within a statement
4805     // expression. We have no intention of supporting that.
4806     Info.FFDiag(Found->getBeginLoc(),
4807                 diag::note_constexpr_stmt_expr_unsupported);
4808     return ESR_Failed;
4809   }
4810   llvm_unreachable("Invalid EvalStmtResult!");
4811 }
4812 
4813 // Evaluate a statement.
4814 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4815                                    const Stmt *S, const SwitchCase *Case) {
4816   if (!Info.nextStep(S))
4817     return ESR_Failed;
4818 
4819   // If we're hunting down a 'case' or 'default' label, recurse through
4820   // substatements until we hit the label.
4821   if (Case) {
4822     switch (S->getStmtClass()) {
4823     case Stmt::CompoundStmtClass:
4824       // FIXME: Precompute which substatement of a compound statement we
4825       // would jump to, and go straight there rather than performing a
4826       // linear scan each time.
4827     case Stmt::LabelStmtClass:
4828     case Stmt::AttributedStmtClass:
4829     case Stmt::DoStmtClass:
4830       break;
4831 
4832     case Stmt::CaseStmtClass:
4833     case Stmt::DefaultStmtClass:
4834       if (Case == S)
4835         Case = nullptr;
4836       break;
4837 
4838     case Stmt::IfStmtClass: {
4839       // FIXME: Precompute which side of an 'if' we would jump to, and go
4840       // straight there rather than scanning both sides.
4841       const IfStmt *IS = cast<IfStmt>(S);
4842 
4843       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4844       // preceded by our switch label.
4845       BlockScopeRAII Scope(Info);
4846 
4847       // Step into the init statement in case it brings an (uninitialized)
4848       // variable into scope.
4849       if (const Stmt *Init = IS->getInit()) {
4850         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4851         if (ESR != ESR_CaseNotFound) {
4852           assert(ESR != ESR_Succeeded);
4853           return ESR;
4854         }
4855       }
4856 
4857       // Condition variable must be initialized if it exists.
4858       // FIXME: We can skip evaluating the body if there's a condition
4859       // variable, as there can't be any case labels within it.
4860       // (The same is true for 'for' statements.)
4861 
4862       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4863       if (ESR == ESR_Failed)
4864         return ESR;
4865       if (ESR != ESR_CaseNotFound)
4866         return Scope.destroy() ? ESR : ESR_Failed;
4867       if (!IS->getElse())
4868         return ESR_CaseNotFound;
4869 
4870       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4871       if (ESR == ESR_Failed)
4872         return ESR;
4873       if (ESR != ESR_CaseNotFound)
4874         return Scope.destroy() ? ESR : ESR_Failed;
4875       return ESR_CaseNotFound;
4876     }
4877 
4878     case Stmt::WhileStmtClass: {
4879       EvalStmtResult ESR =
4880           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4881       if (ESR != ESR_Continue)
4882         return ESR;
4883       break;
4884     }
4885 
4886     case Stmt::ForStmtClass: {
4887       const ForStmt *FS = cast<ForStmt>(S);
4888       BlockScopeRAII Scope(Info);
4889 
4890       // Step into the init statement in case it brings an (uninitialized)
4891       // variable into scope.
4892       if (const Stmt *Init = FS->getInit()) {
4893         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4894         if (ESR != ESR_CaseNotFound) {
4895           assert(ESR != ESR_Succeeded);
4896           return ESR;
4897         }
4898       }
4899 
4900       EvalStmtResult ESR =
4901           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4902       if (ESR != ESR_Continue)
4903         return ESR;
4904       if (FS->getInc()) {
4905         FullExpressionRAII IncScope(Info);
4906         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4907           return ESR_Failed;
4908       }
4909       break;
4910     }
4911 
4912     case Stmt::DeclStmtClass: {
4913       // Start the lifetime of any uninitialized variables we encounter. They
4914       // might be used by the selected branch of the switch.
4915       const DeclStmt *DS = cast<DeclStmt>(S);
4916       for (const auto *D : DS->decls()) {
4917         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4918           if (VD->hasLocalStorage() && !VD->getInit())
4919             if (!EvaluateVarDecl(Info, VD))
4920               return ESR_Failed;
4921           // FIXME: If the variable has initialization that can't be jumped
4922           // over, bail out of any immediately-surrounding compound-statement
4923           // too. There can't be any case labels here.
4924         }
4925       }
4926       return ESR_CaseNotFound;
4927     }
4928 
4929     default:
4930       return ESR_CaseNotFound;
4931     }
4932   }
4933 
4934   switch (S->getStmtClass()) {
4935   default:
4936     if (const Expr *E = dyn_cast<Expr>(S)) {
4937       // Don't bother evaluating beyond an expression-statement which couldn't
4938       // be evaluated.
4939       // FIXME: Do we need the FullExpressionRAII object here?
4940       // VisitExprWithCleanups should create one when necessary.
4941       FullExpressionRAII Scope(Info);
4942       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4943         return ESR_Failed;
4944       return ESR_Succeeded;
4945     }
4946 
4947     Info.FFDiag(S->getBeginLoc());
4948     return ESR_Failed;
4949 
4950   case Stmt::NullStmtClass:
4951     return ESR_Succeeded;
4952 
4953   case Stmt::DeclStmtClass: {
4954     const DeclStmt *DS = cast<DeclStmt>(S);
4955     for (const auto *D : DS->decls()) {
4956       // Each declaration initialization is its own full-expression.
4957       FullExpressionRAII Scope(Info);
4958       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4959         return ESR_Failed;
4960       if (!Scope.destroy())
4961         return ESR_Failed;
4962     }
4963     return ESR_Succeeded;
4964   }
4965 
4966   case Stmt::ReturnStmtClass: {
4967     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4968     FullExpressionRAII Scope(Info);
4969     if (RetExpr &&
4970         !(Result.Slot
4971               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4972               : Evaluate(Result.Value, Info, RetExpr)))
4973       return ESR_Failed;
4974     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4975   }
4976 
4977   case Stmt::CompoundStmtClass: {
4978     BlockScopeRAII Scope(Info);
4979 
4980     const CompoundStmt *CS = cast<CompoundStmt>(S);
4981     for (const auto *BI : CS->body()) {
4982       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4983       if (ESR == ESR_Succeeded)
4984         Case = nullptr;
4985       else if (ESR != ESR_CaseNotFound) {
4986         if (ESR != ESR_Failed && !Scope.destroy())
4987           return ESR_Failed;
4988         return ESR;
4989       }
4990     }
4991     if (Case)
4992       return ESR_CaseNotFound;
4993     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4994   }
4995 
4996   case Stmt::IfStmtClass: {
4997     const IfStmt *IS = cast<IfStmt>(S);
4998 
4999     // Evaluate the condition, as either a var decl or as an expression.
5000     BlockScopeRAII Scope(Info);
5001     if (const Stmt *Init = IS->getInit()) {
5002       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5003       if (ESR != ESR_Succeeded) {
5004         if (ESR != ESR_Failed && !Scope.destroy())
5005           return ESR_Failed;
5006         return ESR;
5007       }
5008     }
5009     bool Cond;
5010     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5011       return ESR_Failed;
5012 
5013     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5014       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5015       if (ESR != ESR_Succeeded) {
5016         if (ESR != ESR_Failed && !Scope.destroy())
5017           return ESR_Failed;
5018         return ESR;
5019       }
5020     }
5021     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5022   }
5023 
5024   case Stmt::WhileStmtClass: {
5025     const WhileStmt *WS = cast<WhileStmt>(S);
5026     while (true) {
5027       BlockScopeRAII Scope(Info);
5028       bool Continue;
5029       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5030                         Continue))
5031         return ESR_Failed;
5032       if (!Continue)
5033         break;
5034 
5035       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5036       if (ESR != ESR_Continue) {
5037         if (ESR != ESR_Failed && !Scope.destroy())
5038           return ESR_Failed;
5039         return ESR;
5040       }
5041       if (!Scope.destroy())
5042         return ESR_Failed;
5043     }
5044     return ESR_Succeeded;
5045   }
5046 
5047   case Stmt::DoStmtClass: {
5048     const DoStmt *DS = cast<DoStmt>(S);
5049     bool Continue;
5050     do {
5051       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5052       if (ESR != ESR_Continue)
5053         return ESR;
5054       Case = nullptr;
5055 
5056       FullExpressionRAII CondScope(Info);
5057       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5058           !CondScope.destroy())
5059         return ESR_Failed;
5060     } while (Continue);
5061     return ESR_Succeeded;
5062   }
5063 
5064   case Stmt::ForStmtClass: {
5065     const ForStmt *FS = cast<ForStmt>(S);
5066     BlockScopeRAII ForScope(Info);
5067     if (FS->getInit()) {
5068       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5069       if (ESR != ESR_Succeeded) {
5070         if (ESR != ESR_Failed && !ForScope.destroy())
5071           return ESR_Failed;
5072         return ESR;
5073       }
5074     }
5075     while (true) {
5076       BlockScopeRAII IterScope(Info);
5077       bool Continue = true;
5078       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5079                                          FS->getCond(), Continue))
5080         return ESR_Failed;
5081       if (!Continue)
5082         break;
5083 
5084       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5085       if (ESR != ESR_Continue) {
5086         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5087           return ESR_Failed;
5088         return ESR;
5089       }
5090 
5091       if (FS->getInc()) {
5092         FullExpressionRAII IncScope(Info);
5093         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5094           return ESR_Failed;
5095       }
5096 
5097       if (!IterScope.destroy())
5098         return ESR_Failed;
5099     }
5100     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5101   }
5102 
5103   case Stmt::CXXForRangeStmtClass: {
5104     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5105     BlockScopeRAII Scope(Info);
5106 
5107     // Evaluate the init-statement if present.
5108     if (FS->getInit()) {
5109       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5110       if (ESR != ESR_Succeeded) {
5111         if (ESR != ESR_Failed && !Scope.destroy())
5112           return ESR_Failed;
5113         return ESR;
5114       }
5115     }
5116 
5117     // Initialize the __range variable.
5118     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5119     if (ESR != ESR_Succeeded) {
5120       if (ESR != ESR_Failed && !Scope.destroy())
5121         return ESR_Failed;
5122       return ESR;
5123     }
5124 
5125     // Create the __begin and __end iterators.
5126     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5127     if (ESR != ESR_Succeeded) {
5128       if (ESR != ESR_Failed && !Scope.destroy())
5129         return ESR_Failed;
5130       return ESR;
5131     }
5132     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5133     if (ESR != ESR_Succeeded) {
5134       if (ESR != ESR_Failed && !Scope.destroy())
5135         return ESR_Failed;
5136       return ESR;
5137     }
5138 
5139     while (true) {
5140       // Condition: __begin != __end.
5141       {
5142         bool Continue = true;
5143         FullExpressionRAII CondExpr(Info);
5144         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5145           return ESR_Failed;
5146         if (!Continue)
5147           break;
5148       }
5149 
5150       // User's variable declaration, initialized by *__begin.
5151       BlockScopeRAII InnerScope(Info);
5152       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5153       if (ESR != ESR_Succeeded) {
5154         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5155           return ESR_Failed;
5156         return ESR;
5157       }
5158 
5159       // Loop body.
5160       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5161       if (ESR != ESR_Continue) {
5162         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5163           return ESR_Failed;
5164         return ESR;
5165       }
5166 
5167       // Increment: ++__begin
5168       if (!EvaluateIgnoredValue(Info, FS->getInc()))
5169         return ESR_Failed;
5170 
5171       if (!InnerScope.destroy())
5172         return ESR_Failed;
5173     }
5174 
5175     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5176   }
5177 
5178   case Stmt::SwitchStmtClass:
5179     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5180 
5181   case Stmt::ContinueStmtClass:
5182     return ESR_Continue;
5183 
5184   case Stmt::BreakStmtClass:
5185     return ESR_Break;
5186 
5187   case Stmt::LabelStmtClass:
5188     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5189 
5190   case Stmt::AttributedStmtClass:
5191     // As a general principle, C++11 attributes can be ignored without
5192     // any semantic impact.
5193     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5194                         Case);
5195 
5196   case Stmt::CaseStmtClass:
5197   case Stmt::DefaultStmtClass:
5198     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5199   case Stmt::CXXTryStmtClass:
5200     // Evaluate try blocks by evaluating all sub statements.
5201     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5202   }
5203 }
5204 
5205 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5206 /// default constructor. If so, we'll fold it whether or not it's marked as
5207 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5208 /// so we need special handling.
5209 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5210                                            const CXXConstructorDecl *CD,
5211                                            bool IsValueInitialization) {
5212   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5213     return false;
5214 
5215   // Value-initialization does not call a trivial default constructor, so such a
5216   // call is a core constant expression whether or not the constructor is
5217   // constexpr.
5218   if (!CD->isConstexpr() && !IsValueInitialization) {
5219     if (Info.getLangOpts().CPlusPlus11) {
5220       // FIXME: If DiagDecl is an implicitly-declared special member function,
5221       // we should be much more explicit about why it's not constexpr.
5222       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5223         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5224       Info.Note(CD->getLocation(), diag::note_declared_at);
5225     } else {
5226       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5227     }
5228   }
5229   return true;
5230 }
5231 
5232 /// CheckConstexprFunction - Check that a function can be called in a constant
5233 /// expression.
5234 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5235                                    const FunctionDecl *Declaration,
5236                                    const FunctionDecl *Definition,
5237                                    const Stmt *Body) {
5238   // Potential constant expressions can contain calls to declared, but not yet
5239   // defined, constexpr functions.
5240   if (Info.checkingPotentialConstantExpression() && !Definition &&
5241       Declaration->isConstexpr())
5242     return false;
5243 
5244   // Bail out if the function declaration itself is invalid.  We will
5245   // have produced a relevant diagnostic while parsing it, so just
5246   // note the problematic sub-expression.
5247   if (Declaration->isInvalidDecl()) {
5248     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5249     return false;
5250   }
5251 
5252   // DR1872: An instantiated virtual constexpr function can't be called in a
5253   // constant expression (prior to C++20). We can still constant-fold such a
5254   // call.
5255   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5256       cast<CXXMethodDecl>(Declaration)->isVirtual())
5257     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5258 
5259   if (Definition && Definition->isInvalidDecl()) {
5260     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5261     return false;
5262   }
5263 
5264   if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5265     for (const auto *InitExpr : CtorDecl->inits()) {
5266       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5267         return false;
5268     }
5269   }
5270 
5271   // Can we evaluate this function call?
5272   if (Definition && Definition->isConstexpr() && Body)
5273     return true;
5274 
5275   if (Info.getLangOpts().CPlusPlus11) {
5276     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5277 
5278     // If this function is not constexpr because it is an inherited
5279     // non-constexpr constructor, diagnose that directly.
5280     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5281     if (CD && CD->isInheritingConstructor()) {
5282       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5283       if (!Inherited->isConstexpr())
5284         DiagDecl = CD = Inherited;
5285     }
5286 
5287     // FIXME: If DiagDecl is an implicitly-declared special member function
5288     // or an inheriting constructor, we should be much more explicit about why
5289     // it's not constexpr.
5290     if (CD && CD->isInheritingConstructor())
5291       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5292         << CD->getInheritedConstructor().getConstructor()->getParent();
5293     else
5294       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5295         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5296     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5297   } else {
5298     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5299   }
5300   return false;
5301 }
5302 
5303 namespace {
5304 struct CheckDynamicTypeHandler {
5305   AccessKinds AccessKind;
5306   typedef bool result_type;
5307   bool failed() { return false; }
5308   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5309   bool found(APSInt &Value, QualType SubobjType) { return true; }
5310   bool found(APFloat &Value, QualType SubobjType) { return true; }
5311 };
5312 } // end anonymous namespace
5313 
5314 /// Check that we can access the notional vptr of an object / determine its
5315 /// dynamic type.
5316 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5317                              AccessKinds AK, bool Polymorphic) {
5318   if (This.Designator.Invalid)
5319     return false;
5320 
5321   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5322 
5323   if (!Obj)
5324     return false;
5325 
5326   if (!Obj.Value) {
5327     // The object is not usable in constant expressions, so we can't inspect
5328     // its value to see if it's in-lifetime or what the active union members
5329     // are. We can still check for a one-past-the-end lvalue.
5330     if (This.Designator.isOnePastTheEnd() ||
5331         This.Designator.isMostDerivedAnUnsizedArray()) {
5332       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5333                          ? diag::note_constexpr_access_past_end
5334                          : diag::note_constexpr_access_unsized_array)
5335           << AK;
5336       return false;
5337     } else if (Polymorphic) {
5338       // Conservatively refuse to perform a polymorphic operation if we would
5339       // not be able to read a notional 'vptr' value.
5340       APValue Val;
5341       This.moveInto(Val);
5342       QualType StarThisType =
5343           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5344       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5345           << AK << Val.getAsString(Info.Ctx, StarThisType);
5346       return false;
5347     }
5348     return true;
5349   }
5350 
5351   CheckDynamicTypeHandler Handler{AK};
5352   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5353 }
5354 
5355 /// Check that the pointee of the 'this' pointer in a member function call is
5356 /// either within its lifetime or in its period of construction or destruction.
5357 static bool
5358 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5359                                      const LValue &This,
5360                                      const CXXMethodDecl *NamedMember) {
5361   return checkDynamicType(
5362       Info, E, This,
5363       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5364 }
5365 
5366 struct DynamicType {
5367   /// The dynamic class type of the object.
5368   const CXXRecordDecl *Type;
5369   /// The corresponding path length in the lvalue.
5370   unsigned PathLength;
5371 };
5372 
5373 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5374                                              unsigned PathLength) {
5375   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5376       Designator.Entries.size() && "invalid path length");
5377   return (PathLength == Designator.MostDerivedPathLength)
5378              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5379              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5380 }
5381 
5382 /// Determine the dynamic type of an object.
5383 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5384                                                 LValue &This, AccessKinds AK) {
5385   // If we don't have an lvalue denoting an object of class type, there is no
5386   // meaningful dynamic type. (We consider objects of non-class type to have no
5387   // dynamic type.)
5388   if (!checkDynamicType(Info, E, This, AK, true))
5389     return None;
5390 
5391   // Refuse to compute a dynamic type in the presence of virtual bases. This
5392   // shouldn't happen other than in constant-folding situations, since literal
5393   // types can't have virtual bases.
5394   //
5395   // Note that consumers of DynamicType assume that the type has no virtual
5396   // bases, and will need modifications if this restriction is relaxed.
5397   const CXXRecordDecl *Class =
5398       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5399   if (!Class || Class->getNumVBases()) {
5400     Info.FFDiag(E);
5401     return None;
5402   }
5403 
5404   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5405   // binary search here instead. But the overwhelmingly common case is that
5406   // we're not in the middle of a constructor, so it probably doesn't matter
5407   // in practice.
5408   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5409   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5410        PathLength <= Path.size(); ++PathLength) {
5411     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5412                                       Path.slice(0, PathLength))) {
5413     case ConstructionPhase::Bases:
5414     case ConstructionPhase::DestroyingBases:
5415       // We're constructing or destroying a base class. This is not the dynamic
5416       // type.
5417       break;
5418 
5419     case ConstructionPhase::None:
5420     case ConstructionPhase::AfterBases:
5421     case ConstructionPhase::AfterFields:
5422     case ConstructionPhase::Destroying:
5423       // We've finished constructing the base classes and not yet started
5424       // destroying them again, so this is the dynamic type.
5425       return DynamicType{getBaseClassType(This.Designator, PathLength),
5426                          PathLength};
5427     }
5428   }
5429 
5430   // CWG issue 1517: we're constructing a base class of the object described by
5431   // 'This', so that object has not yet begun its period of construction and
5432   // any polymorphic operation on it results in undefined behavior.
5433   Info.FFDiag(E);
5434   return None;
5435 }
5436 
5437 /// Perform virtual dispatch.
5438 static const CXXMethodDecl *HandleVirtualDispatch(
5439     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5440     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5441   Optional<DynamicType> DynType = ComputeDynamicType(
5442       Info, E, This,
5443       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5444   if (!DynType)
5445     return nullptr;
5446 
5447   // Find the final overrider. It must be declared in one of the classes on the
5448   // path from the dynamic type to the static type.
5449   // FIXME: If we ever allow literal types to have virtual base classes, that
5450   // won't be true.
5451   const CXXMethodDecl *Callee = Found;
5452   unsigned PathLength = DynType->PathLength;
5453   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5454     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5455     const CXXMethodDecl *Overrider =
5456         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5457     if (Overrider) {
5458       Callee = Overrider;
5459       break;
5460     }
5461   }
5462 
5463   // C++2a [class.abstract]p6:
5464   //   the effect of making a virtual call to a pure virtual function [...] is
5465   //   undefined
5466   if (Callee->isPure()) {
5467     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5468     Info.Note(Callee->getLocation(), diag::note_declared_at);
5469     return nullptr;
5470   }
5471 
5472   // If necessary, walk the rest of the path to determine the sequence of
5473   // covariant adjustment steps to apply.
5474   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5475                                        Found->getReturnType())) {
5476     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5477     for (unsigned CovariantPathLength = PathLength + 1;
5478          CovariantPathLength != This.Designator.Entries.size();
5479          ++CovariantPathLength) {
5480       const CXXRecordDecl *NextClass =
5481           getBaseClassType(This.Designator, CovariantPathLength);
5482       const CXXMethodDecl *Next =
5483           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5484       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5485                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5486         CovariantAdjustmentPath.push_back(Next->getReturnType());
5487     }
5488     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5489                                          CovariantAdjustmentPath.back()))
5490       CovariantAdjustmentPath.push_back(Found->getReturnType());
5491   }
5492 
5493   // Perform 'this' adjustment.
5494   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5495     return nullptr;
5496 
5497   return Callee;
5498 }
5499 
5500 /// Perform the adjustment from a value returned by a virtual function to
5501 /// a value of the statically expected type, which may be a pointer or
5502 /// reference to a base class of the returned type.
5503 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5504                                             APValue &Result,
5505                                             ArrayRef<QualType> Path) {
5506   assert(Result.isLValue() &&
5507          "unexpected kind of APValue for covariant return");
5508   if (Result.isNullPointer())
5509     return true;
5510 
5511   LValue LVal;
5512   LVal.setFrom(Info.Ctx, Result);
5513 
5514   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5515   for (unsigned I = 1; I != Path.size(); ++I) {
5516     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5517     assert(OldClass && NewClass && "unexpected kind of covariant return");
5518     if (OldClass != NewClass &&
5519         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5520       return false;
5521     OldClass = NewClass;
5522   }
5523 
5524   LVal.moveInto(Result);
5525   return true;
5526 }
5527 
5528 /// Determine whether \p Base, which is known to be a direct base class of
5529 /// \p Derived, is a public base class.
5530 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5531                               const CXXRecordDecl *Base) {
5532   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5533     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5534     if (BaseClass && declaresSameEntity(BaseClass, Base))
5535       return BaseSpec.getAccessSpecifier() == AS_public;
5536   }
5537   llvm_unreachable("Base is not a direct base of Derived");
5538 }
5539 
5540 /// Apply the given dynamic cast operation on the provided lvalue.
5541 ///
5542 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5543 /// to find a suitable target subobject.
5544 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5545                               LValue &Ptr) {
5546   // We can't do anything with a non-symbolic pointer value.
5547   SubobjectDesignator &D = Ptr.Designator;
5548   if (D.Invalid)
5549     return false;
5550 
5551   // C++ [expr.dynamic.cast]p6:
5552   //   If v is a null pointer value, the result is a null pointer value.
5553   if (Ptr.isNullPointer() && !E->isGLValue())
5554     return true;
5555 
5556   // For all the other cases, we need the pointer to point to an object within
5557   // its lifetime / period of construction / destruction, and we need to know
5558   // its dynamic type.
5559   Optional<DynamicType> DynType =
5560       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5561   if (!DynType)
5562     return false;
5563 
5564   // C++ [expr.dynamic.cast]p7:
5565   //   If T is "pointer to cv void", then the result is a pointer to the most
5566   //   derived object
5567   if (E->getType()->isVoidPointerType())
5568     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5569 
5570   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5571   assert(C && "dynamic_cast target is not void pointer nor class");
5572   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5573 
5574   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5575     // C++ [expr.dynamic.cast]p9:
5576     if (!E->isGLValue()) {
5577       //   The value of a failed cast to pointer type is the null pointer value
5578       //   of the required result type.
5579       Ptr.setNull(Info.Ctx, E->getType());
5580       return true;
5581     }
5582 
5583     //   A failed cast to reference type throws [...] std::bad_cast.
5584     unsigned DiagKind;
5585     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5586                    DynType->Type->isDerivedFrom(C)))
5587       DiagKind = 0;
5588     else if (!Paths || Paths->begin() == Paths->end())
5589       DiagKind = 1;
5590     else if (Paths->isAmbiguous(CQT))
5591       DiagKind = 2;
5592     else {
5593       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5594       DiagKind = 3;
5595     }
5596     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5597         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5598         << Info.Ctx.getRecordType(DynType->Type)
5599         << E->getType().getUnqualifiedType();
5600     return false;
5601   };
5602 
5603   // Runtime check, phase 1:
5604   //   Walk from the base subobject towards the derived object looking for the
5605   //   target type.
5606   for (int PathLength = Ptr.Designator.Entries.size();
5607        PathLength >= (int)DynType->PathLength; --PathLength) {
5608     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5609     if (declaresSameEntity(Class, C))
5610       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5611     // We can only walk across public inheritance edges.
5612     if (PathLength > (int)DynType->PathLength &&
5613         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5614                            Class))
5615       return RuntimeCheckFailed(nullptr);
5616   }
5617 
5618   // Runtime check, phase 2:
5619   //   Search the dynamic type for an unambiguous public base of type C.
5620   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5621                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5622   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5623       Paths.front().Access == AS_public) {
5624     // Downcast to the dynamic type...
5625     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5626       return false;
5627     // ... then upcast to the chosen base class subobject.
5628     for (CXXBasePathElement &Elem : Paths.front())
5629       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5630         return false;
5631     return true;
5632   }
5633 
5634   // Otherwise, the runtime check fails.
5635   return RuntimeCheckFailed(&Paths);
5636 }
5637 
5638 namespace {
5639 struct StartLifetimeOfUnionMemberHandler {
5640   EvalInfo &Info;
5641   const Expr *LHSExpr;
5642   const FieldDecl *Field;
5643   bool DuringInit;
5644   bool Failed = false;
5645   static const AccessKinds AccessKind = AK_Assign;
5646 
5647   typedef bool result_type;
5648   bool failed() { return Failed; }
5649   bool found(APValue &Subobj, QualType SubobjType) {
5650     // We are supposed to perform no initialization but begin the lifetime of
5651     // the object. We interpret that as meaning to do what default
5652     // initialization of the object would do if all constructors involved were
5653     // trivial:
5654     //  * All base, non-variant member, and array element subobjects' lifetimes
5655     //    begin
5656     //  * No variant members' lifetimes begin
5657     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5658     assert(SubobjType->isUnionType());
5659     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5660       // This union member is already active. If it's also in-lifetime, there's
5661       // nothing to do.
5662       if (Subobj.getUnionValue().hasValue())
5663         return true;
5664     } else if (DuringInit) {
5665       // We're currently in the process of initializing a different union
5666       // member.  If we carried on, that initialization would attempt to
5667       // store to an inactive union member, resulting in undefined behavior.
5668       Info.FFDiag(LHSExpr,
5669                   diag::note_constexpr_union_member_change_during_init);
5670       return false;
5671     }
5672     APValue Result;
5673     Failed = !getDefaultInitValue(Field->getType(), Result);
5674     Subobj.setUnion(Field, Result);
5675     return true;
5676   }
5677   bool found(APSInt &Value, QualType SubobjType) {
5678     llvm_unreachable("wrong value kind for union object");
5679   }
5680   bool found(APFloat &Value, QualType SubobjType) {
5681     llvm_unreachable("wrong value kind for union object");
5682   }
5683 };
5684 } // end anonymous namespace
5685 
5686 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5687 
5688 /// Handle a builtin simple-assignment or a call to a trivial assignment
5689 /// operator whose left-hand side might involve a union member access. If it
5690 /// does, implicitly start the lifetime of any accessed union elements per
5691 /// C++20 [class.union]5.
5692 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5693                                           const LValue &LHS) {
5694   if (LHS.InvalidBase || LHS.Designator.Invalid)
5695     return false;
5696 
5697   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5698   // C++ [class.union]p5:
5699   //   define the set S(E) of subexpressions of E as follows:
5700   unsigned PathLength = LHS.Designator.Entries.size();
5701   for (const Expr *E = LHSExpr; E != nullptr;) {
5702     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5703     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5704       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5705       // Note that we can't implicitly start the lifetime of a reference,
5706       // so we don't need to proceed any further if we reach one.
5707       if (!FD || FD->getType()->isReferenceType())
5708         break;
5709 
5710       //    ... and also contains A.B if B names a union member ...
5711       if (FD->getParent()->isUnion()) {
5712         //    ... of a non-class, non-array type, or of a class type with a
5713         //    trivial default constructor that is not deleted, or an array of
5714         //    such types.
5715         auto *RD =
5716             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5717         if (!RD || RD->hasTrivialDefaultConstructor())
5718           UnionPathLengths.push_back({PathLength - 1, FD});
5719       }
5720 
5721       E = ME->getBase();
5722       --PathLength;
5723       assert(declaresSameEntity(FD,
5724                                 LHS.Designator.Entries[PathLength]
5725                                     .getAsBaseOrMember().getPointer()));
5726 
5727       //   -- If E is of the form A[B] and is interpreted as a built-in array
5728       //      subscripting operator, S(E) is [S(the array operand, if any)].
5729     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5730       // Step over an ArrayToPointerDecay implicit cast.
5731       auto *Base = ASE->getBase()->IgnoreImplicit();
5732       if (!Base->getType()->isArrayType())
5733         break;
5734 
5735       E = Base;
5736       --PathLength;
5737 
5738     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5739       // Step over a derived-to-base conversion.
5740       E = ICE->getSubExpr();
5741       if (ICE->getCastKind() == CK_NoOp)
5742         continue;
5743       if (ICE->getCastKind() != CK_DerivedToBase &&
5744           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5745         break;
5746       // Walk path backwards as we walk up from the base to the derived class.
5747       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5748         --PathLength;
5749         (void)Elt;
5750         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5751                                   LHS.Designator.Entries[PathLength]
5752                                       .getAsBaseOrMember().getPointer()));
5753       }
5754 
5755     //   -- Otherwise, S(E) is empty.
5756     } else {
5757       break;
5758     }
5759   }
5760 
5761   // Common case: no unions' lifetimes are started.
5762   if (UnionPathLengths.empty())
5763     return true;
5764 
5765   //   if modification of X [would access an inactive union member], an object
5766   //   of the type of X is implicitly created
5767   CompleteObject Obj =
5768       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5769   if (!Obj)
5770     return false;
5771   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5772            llvm::reverse(UnionPathLengths)) {
5773     // Form a designator for the union object.
5774     SubobjectDesignator D = LHS.Designator;
5775     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5776 
5777     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5778                       ConstructionPhase::AfterBases;
5779     StartLifetimeOfUnionMemberHandler StartLifetime{
5780         Info, LHSExpr, LengthAndField.second, DuringInit};
5781     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5782       return false;
5783   }
5784 
5785   return true;
5786 }
5787 
5788 namespace {
5789 typedef SmallVector<APValue, 8> ArgVector;
5790 }
5791 
5792 /// EvaluateArgs - Evaluate the arguments to a function call.
5793 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5794                          EvalInfo &Info, const FunctionDecl *Callee) {
5795   bool Success = true;
5796   llvm::SmallBitVector ForbiddenNullArgs;
5797   if (Callee->hasAttr<NonNullAttr>()) {
5798     ForbiddenNullArgs.resize(Args.size());
5799     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5800       if (!Attr->args_size()) {
5801         ForbiddenNullArgs.set();
5802         break;
5803       } else
5804         for (auto Idx : Attr->args()) {
5805           unsigned ASTIdx = Idx.getASTIndex();
5806           if (ASTIdx >= Args.size())
5807             continue;
5808           ForbiddenNullArgs[ASTIdx] = 1;
5809         }
5810     }
5811   }
5812   // FIXME: This is the wrong evaluation order for an assignment operator
5813   // called via operator syntax.
5814   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5815     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5816       // If we're checking for a potential constant expression, evaluate all
5817       // initializers even if some of them fail.
5818       if (!Info.noteFailure())
5819         return false;
5820       Success = false;
5821     } else if (!ForbiddenNullArgs.empty() &&
5822                ForbiddenNullArgs[Idx] &&
5823                ArgValues[Idx].isLValue() &&
5824                ArgValues[Idx].isNullPointer()) {
5825       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5826       if (!Info.noteFailure())
5827         return false;
5828       Success = false;
5829     }
5830   }
5831   return Success;
5832 }
5833 
5834 /// Evaluate a function call.
5835 static bool HandleFunctionCall(SourceLocation CallLoc,
5836                                const FunctionDecl *Callee, const LValue *This,
5837                                ArrayRef<const Expr*> Args, const Stmt *Body,
5838                                EvalInfo &Info, APValue &Result,
5839                                const LValue *ResultSlot) {
5840   ArgVector ArgValues(Args.size());
5841   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5842     return false;
5843 
5844   if (!Info.CheckCallLimit(CallLoc))
5845     return false;
5846 
5847   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5848 
5849   // For a trivial copy or move assignment, perform an APValue copy. This is
5850   // essential for unions, where the operations performed by the assignment
5851   // operator cannot be represented as statements.
5852   //
5853   // Skip this for non-union classes with no fields; in that case, the defaulted
5854   // copy/move does not actually read the object.
5855   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5856   if (MD && MD->isDefaulted() &&
5857       (MD->getParent()->isUnion() ||
5858        (MD->isTrivial() &&
5859         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5860     assert(This &&
5861            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5862     LValue RHS;
5863     RHS.setFrom(Info.Ctx, ArgValues[0]);
5864     APValue RHSValue;
5865     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5866                                         RHSValue, MD->getParent()->isUnion()))
5867       return false;
5868     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
5869         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5870       return false;
5871     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5872                           RHSValue))
5873       return false;
5874     This->moveInto(Result);
5875     return true;
5876   } else if (MD && isLambdaCallOperator(MD)) {
5877     // We're in a lambda; determine the lambda capture field maps unless we're
5878     // just constexpr checking a lambda's call operator. constexpr checking is
5879     // done before the captures have been added to the closure object (unless
5880     // we're inferring constexpr-ness), so we don't have access to them in this
5881     // case. But since we don't need the captures to constexpr check, we can
5882     // just ignore them.
5883     if (!Info.checkingPotentialConstantExpression())
5884       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5885                                         Frame.LambdaThisCaptureField);
5886   }
5887 
5888   StmtResult Ret = {Result, ResultSlot};
5889   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5890   if (ESR == ESR_Succeeded) {
5891     if (Callee->getReturnType()->isVoidType())
5892       return true;
5893     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5894   }
5895   return ESR == ESR_Returned;
5896 }
5897 
5898 /// Evaluate a constructor call.
5899 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5900                                   APValue *ArgValues,
5901                                   const CXXConstructorDecl *Definition,
5902                                   EvalInfo &Info, APValue &Result) {
5903   SourceLocation CallLoc = E->getExprLoc();
5904   if (!Info.CheckCallLimit(CallLoc))
5905     return false;
5906 
5907   const CXXRecordDecl *RD = Definition->getParent();
5908   if (RD->getNumVBases()) {
5909     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5910     return false;
5911   }
5912 
5913   EvalInfo::EvaluatingConstructorRAII EvalObj(
5914       Info,
5915       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5916       RD->getNumBases());
5917   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5918 
5919   // FIXME: Creating an APValue just to hold a nonexistent return value is
5920   // wasteful.
5921   APValue RetVal;
5922   StmtResult Ret = {RetVal, nullptr};
5923 
5924   // If it's a delegating constructor, delegate.
5925   if (Definition->isDelegatingConstructor()) {
5926     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5927     {
5928       FullExpressionRAII InitScope(Info);
5929       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5930           !InitScope.destroy())
5931         return false;
5932     }
5933     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5934   }
5935 
5936   // For a trivial copy or move constructor, perform an APValue copy. This is
5937   // essential for unions (or classes with anonymous union members), where the
5938   // operations performed by the constructor cannot be represented by
5939   // ctor-initializers.
5940   //
5941   // Skip this for empty non-union classes; we should not perform an
5942   // lvalue-to-rvalue conversion on them because their copy constructor does not
5943   // actually read them.
5944   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5945       (Definition->getParent()->isUnion() ||
5946        (Definition->isTrivial() &&
5947         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5948     LValue RHS;
5949     RHS.setFrom(Info.Ctx, ArgValues[0]);
5950     return handleLValueToRValueConversion(
5951         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5952         RHS, Result, Definition->getParent()->isUnion());
5953   }
5954 
5955   // Reserve space for the struct members.
5956   if (!Result.hasValue()) {
5957     if (!RD->isUnion())
5958       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5959                        std::distance(RD->field_begin(), RD->field_end()));
5960     else
5961       // A union starts with no active member.
5962       Result = APValue((const FieldDecl*)nullptr);
5963   }
5964 
5965   if (RD->isInvalidDecl()) return false;
5966   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5967 
5968   // A scope for temporaries lifetime-extended by reference members.
5969   BlockScopeRAII LifetimeExtendedScope(Info);
5970 
5971   bool Success = true;
5972   unsigned BasesSeen = 0;
5973 #ifndef NDEBUG
5974   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5975 #endif
5976   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5977   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5978     // We might be initializing the same field again if this is an indirect
5979     // field initialization.
5980     if (FieldIt == RD->field_end() ||
5981         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5982       assert(Indirect && "fields out of order?");
5983       return;
5984     }
5985 
5986     // Default-initialize any fields with no explicit initializer.
5987     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5988       assert(FieldIt != RD->field_end() && "missing field?");
5989       if (!FieldIt->isUnnamedBitfield())
5990         Success &= getDefaultInitValue(
5991             FieldIt->getType(),
5992             Result.getStructField(FieldIt->getFieldIndex()));
5993     }
5994     ++FieldIt;
5995   };
5996   for (const auto *I : Definition->inits()) {
5997     LValue Subobject = This;
5998     LValue SubobjectParent = This;
5999     APValue *Value = &Result;
6000 
6001     // Determine the subobject to initialize.
6002     FieldDecl *FD = nullptr;
6003     if (I->isBaseInitializer()) {
6004       QualType BaseType(I->getBaseClass(), 0);
6005 #ifndef NDEBUG
6006       // Non-virtual base classes are initialized in the order in the class
6007       // definition. We have already checked for virtual base classes.
6008       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6009       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6010              "base class initializers not in expected order");
6011       ++BaseIt;
6012 #endif
6013       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6014                                   BaseType->getAsCXXRecordDecl(), &Layout))
6015         return false;
6016       Value = &Result.getStructBase(BasesSeen++);
6017     } else if ((FD = I->getMember())) {
6018       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6019         return false;
6020       if (RD->isUnion()) {
6021         Result = APValue(FD);
6022         Value = &Result.getUnionValue();
6023       } else {
6024         SkipToField(FD, false);
6025         Value = &Result.getStructField(FD->getFieldIndex());
6026       }
6027     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6028       // Walk the indirect field decl's chain to find the object to initialize,
6029       // and make sure we've initialized every step along it.
6030       auto IndirectFieldChain = IFD->chain();
6031       for (auto *C : IndirectFieldChain) {
6032         FD = cast<FieldDecl>(C);
6033         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6034         // Switch the union field if it differs. This happens if we had
6035         // preceding zero-initialization, and we're now initializing a union
6036         // subobject other than the first.
6037         // FIXME: In this case, the values of the other subobjects are
6038         // specified, since zero-initialization sets all padding bits to zero.
6039         if (!Value->hasValue() ||
6040             (Value->isUnion() && Value->getUnionField() != FD)) {
6041           if (CD->isUnion())
6042             *Value = APValue(FD);
6043           else
6044             // FIXME: This immediately starts the lifetime of all members of
6045             // an anonymous struct. It would be preferable to strictly start
6046             // member lifetime in initialization order.
6047             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6048         }
6049         // Store Subobject as its parent before updating it for the last element
6050         // in the chain.
6051         if (C == IndirectFieldChain.back())
6052           SubobjectParent = Subobject;
6053         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6054           return false;
6055         if (CD->isUnion())
6056           Value = &Value->getUnionValue();
6057         else {
6058           if (C == IndirectFieldChain.front() && !RD->isUnion())
6059             SkipToField(FD, true);
6060           Value = &Value->getStructField(FD->getFieldIndex());
6061         }
6062       }
6063     } else {
6064       llvm_unreachable("unknown base initializer kind");
6065     }
6066 
6067     // Need to override This for implicit field initializers as in this case
6068     // This refers to innermost anonymous struct/union containing initializer,
6069     // not to currently constructed class.
6070     const Expr *Init = I->getInit();
6071     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6072                                   isa<CXXDefaultInitExpr>(Init));
6073     FullExpressionRAII InitScope(Info);
6074     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6075         (FD && FD->isBitField() &&
6076          !truncateBitfieldValue(Info, Init, *Value, FD))) {
6077       // If we're checking for a potential constant expression, evaluate all
6078       // initializers even if some of them fail.
6079       if (!Info.noteFailure())
6080         return false;
6081       Success = false;
6082     }
6083 
6084     // This is the point at which the dynamic type of the object becomes this
6085     // class type.
6086     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6087       EvalObj.finishedConstructingBases();
6088   }
6089 
6090   // Default-initialize any remaining fields.
6091   if (!RD->isUnion()) {
6092     for (; FieldIt != RD->field_end(); ++FieldIt) {
6093       if (!FieldIt->isUnnamedBitfield())
6094         Success &= getDefaultInitValue(
6095             FieldIt->getType(),
6096             Result.getStructField(FieldIt->getFieldIndex()));
6097     }
6098   }
6099 
6100   EvalObj.finishedConstructingFields();
6101 
6102   return Success &&
6103          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6104          LifetimeExtendedScope.destroy();
6105 }
6106 
6107 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6108                                   ArrayRef<const Expr*> Args,
6109                                   const CXXConstructorDecl *Definition,
6110                                   EvalInfo &Info, APValue &Result) {
6111   ArgVector ArgValues(Args.size());
6112   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
6113     return false;
6114 
6115   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
6116                                Info, Result);
6117 }
6118 
6119 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6120                                   const LValue &This, APValue &Value,
6121                                   QualType T) {
6122   // Objects can only be destroyed while they're within their lifetimes.
6123   // FIXME: We have no representation for whether an object of type nullptr_t
6124   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6125   // as indeterminate instead?
6126   if (Value.isAbsent() && !T->isNullPtrType()) {
6127     APValue Printable;
6128     This.moveInto(Printable);
6129     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6130       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6131     return false;
6132   }
6133 
6134   // Invent an expression for location purposes.
6135   // FIXME: We shouldn't need to do this.
6136   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6137 
6138   // For arrays, destroy elements right-to-left.
6139   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6140     uint64_t Size = CAT->getSize().getZExtValue();
6141     QualType ElemT = CAT->getElementType();
6142 
6143     LValue ElemLV = This;
6144     ElemLV.addArray(Info, &LocE, CAT);
6145     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6146       return false;
6147 
6148     // Ensure that we have actual array elements available to destroy; the
6149     // destructors might mutate the value, so we can't run them on the array
6150     // filler.
6151     if (Size && Size > Value.getArrayInitializedElts())
6152       expandArray(Value, Value.getArraySize() - 1);
6153 
6154     for (; Size != 0; --Size) {
6155       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6156       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6157           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6158         return false;
6159     }
6160 
6161     // End the lifetime of this array now.
6162     Value = APValue();
6163     return true;
6164   }
6165 
6166   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6167   if (!RD) {
6168     if (T.isDestructedType()) {
6169       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6170       return false;
6171     }
6172 
6173     Value = APValue();
6174     return true;
6175   }
6176 
6177   if (RD->getNumVBases()) {
6178     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6179     return false;
6180   }
6181 
6182   const CXXDestructorDecl *DD = RD->getDestructor();
6183   if (!DD && !RD->hasTrivialDestructor()) {
6184     Info.FFDiag(CallLoc);
6185     return false;
6186   }
6187 
6188   if (!DD || DD->isTrivial() ||
6189       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6190     // A trivial destructor just ends the lifetime of the object. Check for
6191     // this case before checking for a body, because we might not bother
6192     // building a body for a trivial destructor. Note that it doesn't matter
6193     // whether the destructor is constexpr in this case; all trivial
6194     // destructors are constexpr.
6195     //
6196     // If an anonymous union would be destroyed, some enclosing destructor must
6197     // have been explicitly defined, and the anonymous union destruction should
6198     // have no effect.
6199     Value = APValue();
6200     return true;
6201   }
6202 
6203   if (!Info.CheckCallLimit(CallLoc))
6204     return false;
6205 
6206   const FunctionDecl *Definition = nullptr;
6207   const Stmt *Body = DD->getBody(Definition);
6208 
6209   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6210     return false;
6211 
6212   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
6213 
6214   // We're now in the period of destruction of this object.
6215   unsigned BasesLeft = RD->getNumBases();
6216   EvalInfo::EvaluatingDestructorRAII EvalObj(
6217       Info,
6218       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6219   if (!EvalObj.DidInsert) {
6220     // C++2a [class.dtor]p19:
6221     //   the behavior is undefined if the destructor is invoked for an object
6222     //   whose lifetime has ended
6223     // (Note that formally the lifetime ends when the period of destruction
6224     // begins, even though certain uses of the object remain valid until the
6225     // period of destruction ends.)
6226     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6227     return false;
6228   }
6229 
6230   // FIXME: Creating an APValue just to hold a nonexistent return value is
6231   // wasteful.
6232   APValue RetVal;
6233   StmtResult Ret = {RetVal, nullptr};
6234   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6235     return false;
6236 
6237   // A union destructor does not implicitly destroy its members.
6238   if (RD->isUnion())
6239     return true;
6240 
6241   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6242 
6243   // We don't have a good way to iterate fields in reverse, so collect all the
6244   // fields first and then walk them backwards.
6245   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6246   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6247     if (FD->isUnnamedBitfield())
6248       continue;
6249 
6250     LValue Subobject = This;
6251     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6252       return false;
6253 
6254     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6255     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6256                                FD->getType()))
6257       return false;
6258   }
6259 
6260   if (BasesLeft != 0)
6261     EvalObj.startedDestroyingBases();
6262 
6263   // Destroy base classes in reverse order.
6264   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6265     --BasesLeft;
6266 
6267     QualType BaseType = Base.getType();
6268     LValue Subobject = This;
6269     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6270                                 BaseType->getAsCXXRecordDecl(), &Layout))
6271       return false;
6272 
6273     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6274     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6275                                BaseType))
6276       return false;
6277   }
6278   assert(BasesLeft == 0 && "NumBases was wrong?");
6279 
6280   // The period of destruction ends now. The object is gone.
6281   Value = APValue();
6282   return true;
6283 }
6284 
6285 namespace {
6286 struct DestroyObjectHandler {
6287   EvalInfo &Info;
6288   const Expr *E;
6289   const LValue &This;
6290   const AccessKinds AccessKind;
6291 
6292   typedef bool result_type;
6293   bool failed() { return false; }
6294   bool found(APValue &Subobj, QualType SubobjType) {
6295     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6296                                  SubobjType);
6297   }
6298   bool found(APSInt &Value, QualType SubobjType) {
6299     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6300     return false;
6301   }
6302   bool found(APFloat &Value, QualType SubobjType) {
6303     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6304     return false;
6305   }
6306 };
6307 }
6308 
6309 /// Perform a destructor or pseudo-destructor call on the given object, which
6310 /// might in general not be a complete object.
6311 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6312                               const LValue &This, QualType ThisType) {
6313   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6314   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6315   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6316 }
6317 
6318 /// Destroy and end the lifetime of the given complete object.
6319 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6320                               APValue::LValueBase LVBase, APValue &Value,
6321                               QualType T) {
6322   // If we've had an unmodeled side-effect, we can't rely on mutable state
6323   // (such as the object we're about to destroy) being correct.
6324   if (Info.EvalStatus.HasSideEffects)
6325     return false;
6326 
6327   LValue LV;
6328   LV.set({LVBase});
6329   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6330 }
6331 
6332 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6333 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6334                                   LValue &Result) {
6335   if (Info.checkingPotentialConstantExpression() ||
6336       Info.SpeculativeEvaluationDepth)
6337     return false;
6338 
6339   // This is permitted only within a call to std::allocator<T>::allocate.
6340   auto Caller = Info.getStdAllocatorCaller("allocate");
6341   if (!Caller) {
6342     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6343                                      ? diag::note_constexpr_new_untyped
6344                                      : diag::note_constexpr_new);
6345     return false;
6346   }
6347 
6348   QualType ElemType = Caller.ElemType;
6349   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6350     Info.FFDiag(E->getExprLoc(),
6351                 diag::note_constexpr_new_not_complete_object_type)
6352         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6353     return false;
6354   }
6355 
6356   APSInt ByteSize;
6357   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6358     return false;
6359   bool IsNothrow = false;
6360   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6361     EvaluateIgnoredValue(Info, E->getArg(I));
6362     IsNothrow |= E->getType()->isNothrowT();
6363   }
6364 
6365   CharUnits ElemSize;
6366   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6367     return false;
6368   APInt Size, Remainder;
6369   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6370   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6371   if (Remainder != 0) {
6372     // This likely indicates a bug in the implementation of 'std::allocator'.
6373     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6374         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6375     return false;
6376   }
6377 
6378   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6379     if (IsNothrow) {
6380       Result.setNull(Info.Ctx, E->getType());
6381       return true;
6382     }
6383 
6384     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6385     return false;
6386   }
6387 
6388   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6389                                                      ArrayType::Normal, 0);
6390   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6391   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6392   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6393   return true;
6394 }
6395 
6396 static bool hasVirtualDestructor(QualType T) {
6397   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6398     if (CXXDestructorDecl *DD = RD->getDestructor())
6399       return DD->isVirtual();
6400   return false;
6401 }
6402 
6403 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6404   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6405     if (CXXDestructorDecl *DD = RD->getDestructor())
6406       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6407   return nullptr;
6408 }
6409 
6410 /// Check that the given object is a suitable pointer to a heap allocation that
6411 /// still exists and is of the right kind for the purpose of a deletion.
6412 ///
6413 /// On success, returns the heap allocation to deallocate. On failure, produces
6414 /// a diagnostic and returns None.
6415 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6416                                             const LValue &Pointer,
6417                                             DynAlloc::Kind DeallocKind) {
6418   auto PointerAsString = [&] {
6419     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6420   };
6421 
6422   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6423   if (!DA) {
6424     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6425         << PointerAsString();
6426     if (Pointer.Base)
6427       NoteLValueLocation(Info, Pointer.Base);
6428     return None;
6429   }
6430 
6431   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6432   if (!Alloc) {
6433     Info.FFDiag(E, diag::note_constexpr_double_delete);
6434     return None;
6435   }
6436 
6437   QualType AllocType = Pointer.Base.getDynamicAllocType();
6438   if (DeallocKind != (*Alloc)->getKind()) {
6439     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6440         << DeallocKind << (*Alloc)->getKind() << AllocType;
6441     NoteLValueLocation(Info, Pointer.Base);
6442     return None;
6443   }
6444 
6445   bool Subobject = false;
6446   if (DeallocKind == DynAlloc::New) {
6447     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6448                 Pointer.Designator.isOnePastTheEnd();
6449   } else {
6450     Subobject = Pointer.Designator.Entries.size() != 1 ||
6451                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6452   }
6453   if (Subobject) {
6454     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6455         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6456     return None;
6457   }
6458 
6459   return Alloc;
6460 }
6461 
6462 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6463 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6464   if (Info.checkingPotentialConstantExpression() ||
6465       Info.SpeculativeEvaluationDepth)
6466     return false;
6467 
6468   // This is permitted only within a call to std::allocator<T>::deallocate.
6469   if (!Info.getStdAllocatorCaller("deallocate")) {
6470     Info.FFDiag(E->getExprLoc());
6471     return true;
6472   }
6473 
6474   LValue Pointer;
6475   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6476     return false;
6477   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6478     EvaluateIgnoredValue(Info, E->getArg(I));
6479 
6480   if (Pointer.Designator.Invalid)
6481     return false;
6482 
6483   // Deleting a null pointer has no effect.
6484   if (Pointer.isNullPointer())
6485     return true;
6486 
6487   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6488     return false;
6489 
6490   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6491   return true;
6492 }
6493 
6494 //===----------------------------------------------------------------------===//
6495 // Generic Evaluation
6496 //===----------------------------------------------------------------------===//
6497 namespace {
6498 
6499 class BitCastBuffer {
6500   // FIXME: We're going to need bit-level granularity when we support
6501   // bit-fields.
6502   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6503   // we don't support a host or target where that is the case. Still, we should
6504   // use a more generic type in case we ever do.
6505   SmallVector<Optional<unsigned char>, 32> Bytes;
6506 
6507   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6508                 "Need at least 8 bit unsigned char");
6509 
6510   bool TargetIsLittleEndian;
6511 
6512 public:
6513   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6514       : Bytes(Width.getQuantity()),
6515         TargetIsLittleEndian(TargetIsLittleEndian) {}
6516 
6517   LLVM_NODISCARD
6518   bool readObject(CharUnits Offset, CharUnits Width,
6519                   SmallVectorImpl<unsigned char> &Output) const {
6520     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6521       // If a byte of an integer is uninitialized, then the whole integer is
6522       // uninitalized.
6523       if (!Bytes[I.getQuantity()])
6524         return false;
6525       Output.push_back(*Bytes[I.getQuantity()]);
6526     }
6527     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6528       std::reverse(Output.begin(), Output.end());
6529     return true;
6530   }
6531 
6532   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6533     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6534       std::reverse(Input.begin(), Input.end());
6535 
6536     size_t Index = 0;
6537     for (unsigned char Byte : Input) {
6538       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6539       Bytes[Offset.getQuantity() + Index] = Byte;
6540       ++Index;
6541     }
6542   }
6543 
6544   size_t size() { return Bytes.size(); }
6545 };
6546 
6547 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6548 /// target would represent the value at runtime.
6549 class APValueToBufferConverter {
6550   EvalInfo &Info;
6551   BitCastBuffer Buffer;
6552   const CastExpr *BCE;
6553 
6554   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6555                            const CastExpr *BCE)
6556       : Info(Info),
6557         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6558         BCE(BCE) {}
6559 
6560   bool visit(const APValue &Val, QualType Ty) {
6561     return visit(Val, Ty, CharUnits::fromQuantity(0));
6562   }
6563 
6564   // Write out Val with type Ty into Buffer starting at Offset.
6565   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6566     assert((size_t)Offset.getQuantity() <= Buffer.size());
6567 
6568     // As a special case, nullptr_t has an indeterminate value.
6569     if (Ty->isNullPtrType())
6570       return true;
6571 
6572     // Dig through Src to find the byte at SrcOffset.
6573     switch (Val.getKind()) {
6574     case APValue::Indeterminate:
6575     case APValue::None:
6576       return true;
6577 
6578     case APValue::Int:
6579       return visitInt(Val.getInt(), Ty, Offset);
6580     case APValue::Float:
6581       return visitFloat(Val.getFloat(), Ty, Offset);
6582     case APValue::Array:
6583       return visitArray(Val, Ty, Offset);
6584     case APValue::Struct:
6585       return visitRecord(Val, Ty, Offset);
6586 
6587     case APValue::ComplexInt:
6588     case APValue::ComplexFloat:
6589     case APValue::Vector:
6590     case APValue::FixedPoint:
6591       // FIXME: We should support these.
6592 
6593     case APValue::Union:
6594     case APValue::MemberPointer:
6595     case APValue::AddrLabelDiff: {
6596       Info.FFDiag(BCE->getBeginLoc(),
6597                   diag::note_constexpr_bit_cast_unsupported_type)
6598           << Ty;
6599       return false;
6600     }
6601 
6602     case APValue::LValue:
6603       llvm_unreachable("LValue subobject in bit_cast?");
6604     }
6605     llvm_unreachable("Unhandled APValue::ValueKind");
6606   }
6607 
6608   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6609     const RecordDecl *RD = Ty->getAsRecordDecl();
6610     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6611 
6612     // Visit the base classes.
6613     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6614       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6615         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6616         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6617 
6618         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6619                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6620           return false;
6621       }
6622     }
6623 
6624     // Visit the fields.
6625     unsigned FieldIdx = 0;
6626     for (FieldDecl *FD : RD->fields()) {
6627       if (FD->isBitField()) {
6628         Info.FFDiag(BCE->getBeginLoc(),
6629                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6630         return false;
6631       }
6632 
6633       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6634 
6635       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6636              "only bit-fields can have sub-char alignment");
6637       CharUnits FieldOffset =
6638           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6639       QualType FieldTy = FD->getType();
6640       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6641         return false;
6642       ++FieldIdx;
6643     }
6644 
6645     return true;
6646   }
6647 
6648   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6649     const auto *CAT =
6650         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6651     if (!CAT)
6652       return false;
6653 
6654     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6655     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6656     unsigned ArraySize = Val.getArraySize();
6657     // First, initialize the initialized elements.
6658     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6659       const APValue &SubObj = Val.getArrayInitializedElt(I);
6660       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6661         return false;
6662     }
6663 
6664     // Next, initialize the rest of the array using the filler.
6665     if (Val.hasArrayFiller()) {
6666       const APValue &Filler = Val.getArrayFiller();
6667       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6668         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6669           return false;
6670       }
6671     }
6672 
6673     return true;
6674   }
6675 
6676   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6677     APSInt AdjustedVal = Val;
6678     unsigned Width = AdjustedVal.getBitWidth();
6679     if (Ty->isBooleanType()) {
6680       Width = Info.Ctx.getTypeSize(Ty);
6681       AdjustedVal = AdjustedVal.extend(Width);
6682     }
6683 
6684     SmallVector<unsigned char, 8> Bytes(Width / 8);
6685     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6686     Buffer.writeObject(Offset, Bytes);
6687     return true;
6688   }
6689 
6690   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6691     APSInt AsInt(Val.bitcastToAPInt());
6692     return visitInt(AsInt, Ty, Offset);
6693   }
6694 
6695 public:
6696   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6697                                          const CastExpr *BCE) {
6698     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6699     APValueToBufferConverter Converter(Info, DstSize, BCE);
6700     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6701       return None;
6702     return Converter.Buffer;
6703   }
6704 };
6705 
6706 /// Write an BitCastBuffer into an APValue.
6707 class BufferToAPValueConverter {
6708   EvalInfo &Info;
6709   const BitCastBuffer &Buffer;
6710   const CastExpr *BCE;
6711 
6712   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6713                            const CastExpr *BCE)
6714       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6715 
6716   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6717   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6718   // Ideally this will be unreachable.
6719   llvm::NoneType unsupportedType(QualType Ty) {
6720     Info.FFDiag(BCE->getBeginLoc(),
6721                 diag::note_constexpr_bit_cast_unsupported_type)
6722         << Ty;
6723     return None;
6724   }
6725 
6726   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6727     Info.FFDiag(BCE->getBeginLoc(),
6728                 diag::note_constexpr_bit_cast_unrepresentable_value)
6729         << Ty << Val.toString(/*Radix=*/10);
6730     return None;
6731   }
6732 
6733   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6734                           const EnumType *EnumSugar = nullptr) {
6735     if (T->isNullPtrType()) {
6736       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6737       return APValue((Expr *)nullptr,
6738                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6739                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6740     }
6741 
6742     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6743 
6744     // Work around floating point types that contain unused padding bytes. This
6745     // is really just `long double` on x86, which is the only fundamental type
6746     // with padding bytes.
6747     if (T->isRealFloatingType()) {
6748       const llvm::fltSemantics &Semantics =
6749           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6750       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6751       assert(NumBits % 8 == 0);
6752       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6753       if (NumBytes != SizeOf)
6754         SizeOf = NumBytes;
6755     }
6756 
6757     SmallVector<uint8_t, 8> Bytes;
6758     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6759       // If this is std::byte or unsigned char, then its okay to store an
6760       // indeterminate value.
6761       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6762       bool IsUChar =
6763           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6764                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6765       if (!IsStdByte && !IsUChar) {
6766         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6767         Info.FFDiag(BCE->getExprLoc(),
6768                     diag::note_constexpr_bit_cast_indet_dest)
6769             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6770         return None;
6771       }
6772 
6773       return APValue::IndeterminateValue();
6774     }
6775 
6776     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6777     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6778 
6779     if (T->isIntegralOrEnumerationType()) {
6780       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6781 
6782       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
6783       if (IntWidth != Val.getBitWidth()) {
6784         APSInt Truncated = Val.trunc(IntWidth);
6785         if (Truncated.extend(Val.getBitWidth()) != Val)
6786           return unrepresentableValue(QualType(T, 0), Val);
6787         Val = Truncated;
6788       }
6789 
6790       return APValue(Val);
6791     }
6792 
6793     if (T->isRealFloatingType()) {
6794       const llvm::fltSemantics &Semantics =
6795           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6796       return APValue(APFloat(Semantics, Val));
6797     }
6798 
6799     return unsupportedType(QualType(T, 0));
6800   }
6801 
6802   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6803     const RecordDecl *RD = RTy->getAsRecordDecl();
6804     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6805 
6806     unsigned NumBases = 0;
6807     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6808       NumBases = CXXRD->getNumBases();
6809 
6810     APValue ResultVal(APValue::UninitStruct(), NumBases,
6811                       std::distance(RD->field_begin(), RD->field_end()));
6812 
6813     // Visit the base classes.
6814     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6815       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6816         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6817         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6818         if (BaseDecl->isEmpty() ||
6819             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6820           continue;
6821 
6822         Optional<APValue> SubObj = visitType(
6823             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6824         if (!SubObj)
6825           return None;
6826         ResultVal.getStructBase(I) = *SubObj;
6827       }
6828     }
6829 
6830     // Visit the fields.
6831     unsigned FieldIdx = 0;
6832     for (FieldDecl *FD : RD->fields()) {
6833       // FIXME: We don't currently support bit-fields. A lot of the logic for
6834       // this is in CodeGen, so we need to factor it around.
6835       if (FD->isBitField()) {
6836         Info.FFDiag(BCE->getBeginLoc(),
6837                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6838         return None;
6839       }
6840 
6841       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6842       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6843 
6844       CharUnits FieldOffset =
6845           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6846           Offset;
6847       QualType FieldTy = FD->getType();
6848       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6849       if (!SubObj)
6850         return None;
6851       ResultVal.getStructField(FieldIdx) = *SubObj;
6852       ++FieldIdx;
6853     }
6854 
6855     return ResultVal;
6856   }
6857 
6858   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6859     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6860     assert(!RepresentationType.isNull() &&
6861            "enum forward decl should be caught by Sema");
6862     const auto *AsBuiltin =
6863         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6864     // Recurse into the underlying type. Treat std::byte transparently as
6865     // unsigned char.
6866     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6867   }
6868 
6869   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6870     size_t Size = Ty->getSize().getLimitedValue();
6871     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6872 
6873     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6874     for (size_t I = 0; I != Size; ++I) {
6875       Optional<APValue> ElementValue =
6876           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6877       if (!ElementValue)
6878         return None;
6879       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6880     }
6881 
6882     return ArrayValue;
6883   }
6884 
6885   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6886     return unsupportedType(QualType(Ty, 0));
6887   }
6888 
6889   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6890     QualType Can = Ty.getCanonicalType();
6891 
6892     switch (Can->getTypeClass()) {
6893 #define TYPE(Class, Base)                                                      \
6894   case Type::Class:                                                            \
6895     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6896 #define ABSTRACT_TYPE(Class, Base)
6897 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6898   case Type::Class:                                                            \
6899     llvm_unreachable("non-canonical type should be impossible!");
6900 #define DEPENDENT_TYPE(Class, Base)                                            \
6901   case Type::Class:                                                            \
6902     llvm_unreachable(                                                          \
6903         "dependent types aren't supported in the constant evaluator!");
6904 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6905   case Type::Class:                                                            \
6906     llvm_unreachable("either dependent or not canonical!");
6907 #include "clang/AST/TypeNodes.inc"
6908     }
6909     llvm_unreachable("Unhandled Type::TypeClass");
6910   }
6911 
6912 public:
6913   // Pull out a full value of type DstType.
6914   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6915                                    const CastExpr *BCE) {
6916     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6917     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6918   }
6919 };
6920 
6921 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6922                                                  QualType Ty, EvalInfo *Info,
6923                                                  const ASTContext &Ctx,
6924                                                  bool CheckingDest) {
6925   Ty = Ty.getCanonicalType();
6926 
6927   auto diag = [&](int Reason) {
6928     if (Info)
6929       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6930           << CheckingDest << (Reason == 4) << Reason;
6931     return false;
6932   };
6933   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6934     if (Info)
6935       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6936           << NoteTy << Construct << Ty;
6937     return false;
6938   };
6939 
6940   if (Ty->isUnionType())
6941     return diag(0);
6942   if (Ty->isPointerType())
6943     return diag(1);
6944   if (Ty->isMemberPointerType())
6945     return diag(2);
6946   if (Ty.isVolatileQualified())
6947     return diag(3);
6948 
6949   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6950     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6951       for (CXXBaseSpecifier &BS : CXXRD->bases())
6952         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6953                                                   CheckingDest))
6954           return note(1, BS.getType(), BS.getBeginLoc());
6955     }
6956     for (FieldDecl *FD : Record->fields()) {
6957       if (FD->getType()->isReferenceType())
6958         return diag(4);
6959       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6960                                                 CheckingDest))
6961         return note(0, FD->getType(), FD->getBeginLoc());
6962     }
6963   }
6964 
6965   if (Ty->isArrayType() &&
6966       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6967                                             Info, Ctx, CheckingDest))
6968     return false;
6969 
6970   return true;
6971 }
6972 
6973 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6974                                              const ASTContext &Ctx,
6975                                              const CastExpr *BCE) {
6976   bool DestOK = checkBitCastConstexprEligibilityType(
6977       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6978   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6979                                 BCE->getBeginLoc(),
6980                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6981   return SourceOK;
6982 }
6983 
6984 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6985                                         APValue &SourceValue,
6986                                         const CastExpr *BCE) {
6987   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6988          "no host or target supports non 8-bit chars");
6989   assert(SourceValue.isLValue() &&
6990          "LValueToRValueBitcast requires an lvalue operand!");
6991 
6992   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6993     return false;
6994 
6995   LValue SourceLValue;
6996   APValue SourceRValue;
6997   SourceLValue.setFrom(Info.Ctx, SourceValue);
6998   if (!handleLValueToRValueConversion(
6999           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7000           SourceRValue, /*WantObjectRepresentation=*/true))
7001     return false;
7002 
7003   // Read out SourceValue into a char buffer.
7004   Optional<BitCastBuffer> Buffer =
7005       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7006   if (!Buffer)
7007     return false;
7008 
7009   // Write out the buffer into a new APValue.
7010   Optional<APValue> MaybeDestValue =
7011       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7012   if (!MaybeDestValue)
7013     return false;
7014 
7015   DestValue = std::move(*MaybeDestValue);
7016   return true;
7017 }
7018 
7019 template <class Derived>
7020 class ExprEvaluatorBase
7021   : public ConstStmtVisitor<Derived, bool> {
7022 private:
7023   Derived &getDerived() { return static_cast<Derived&>(*this); }
7024   bool DerivedSuccess(const APValue &V, const Expr *E) {
7025     return getDerived().Success(V, E);
7026   }
7027   bool DerivedZeroInitialization(const Expr *E) {
7028     return getDerived().ZeroInitialization(E);
7029   }
7030 
7031   // Check whether a conditional operator with a non-constant condition is a
7032   // potential constant expression. If neither arm is a potential constant
7033   // expression, then the conditional operator is not either.
7034   template<typename ConditionalOperator>
7035   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7036     assert(Info.checkingPotentialConstantExpression());
7037 
7038     // Speculatively evaluate both arms.
7039     SmallVector<PartialDiagnosticAt, 8> Diag;
7040     {
7041       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7042       StmtVisitorTy::Visit(E->getFalseExpr());
7043       if (Diag.empty())
7044         return;
7045     }
7046 
7047     {
7048       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7049       Diag.clear();
7050       StmtVisitorTy::Visit(E->getTrueExpr());
7051       if (Diag.empty())
7052         return;
7053     }
7054 
7055     Error(E, diag::note_constexpr_conditional_never_const);
7056   }
7057 
7058 
7059   template<typename ConditionalOperator>
7060   bool HandleConditionalOperator(const ConditionalOperator *E) {
7061     bool BoolResult;
7062     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7063       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7064         CheckPotentialConstantConditional(E);
7065         return false;
7066       }
7067       if (Info.noteFailure()) {
7068         StmtVisitorTy::Visit(E->getTrueExpr());
7069         StmtVisitorTy::Visit(E->getFalseExpr());
7070       }
7071       return false;
7072     }
7073 
7074     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7075     return StmtVisitorTy::Visit(EvalExpr);
7076   }
7077 
7078 protected:
7079   EvalInfo &Info;
7080   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7081   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7082 
7083   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7084     return Info.CCEDiag(E, D);
7085   }
7086 
7087   bool ZeroInitialization(const Expr *E) { return Error(E); }
7088 
7089 public:
7090   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7091 
7092   EvalInfo &getEvalInfo() { return Info; }
7093 
7094   /// Report an evaluation error. This should only be called when an error is
7095   /// first discovered. When propagating an error, just return false.
7096   bool Error(const Expr *E, diag::kind D) {
7097     Info.FFDiag(E, D);
7098     return false;
7099   }
7100   bool Error(const Expr *E) {
7101     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7102   }
7103 
7104   bool VisitStmt(const Stmt *) {
7105     llvm_unreachable("Expression evaluator should not be called on stmts");
7106   }
7107   bool VisitExpr(const Expr *E) {
7108     return Error(E);
7109   }
7110 
7111   bool VisitConstantExpr(const ConstantExpr *E) {
7112     if (E->hasAPValueResult())
7113       return DerivedSuccess(E->getAPValueResult(), E);
7114 
7115     return StmtVisitorTy::Visit(E->getSubExpr());
7116   }
7117 
7118   bool VisitParenExpr(const ParenExpr *E)
7119     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7120   bool VisitUnaryExtension(const UnaryOperator *E)
7121     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7122   bool VisitUnaryPlus(const UnaryOperator *E)
7123     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7124   bool VisitChooseExpr(const ChooseExpr *E)
7125     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7126   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7127     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7128   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7129     { return StmtVisitorTy::Visit(E->getReplacement()); }
7130   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7131     TempVersionRAII RAII(*Info.CurrentCall);
7132     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7133     return StmtVisitorTy::Visit(E->getExpr());
7134   }
7135   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7136     TempVersionRAII RAII(*Info.CurrentCall);
7137     // The initializer may not have been parsed yet, or might be erroneous.
7138     if (!E->getExpr())
7139       return Error(E);
7140     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7141     return StmtVisitorTy::Visit(E->getExpr());
7142   }
7143 
7144   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7145     FullExpressionRAII Scope(Info);
7146     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7147   }
7148 
7149   // Temporaries are registered when created, so we don't care about
7150   // CXXBindTemporaryExpr.
7151   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7152     return StmtVisitorTy::Visit(E->getSubExpr());
7153   }
7154 
7155   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7156     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7157     return static_cast<Derived*>(this)->VisitCastExpr(E);
7158   }
7159   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7160     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7161       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7162     return static_cast<Derived*>(this)->VisitCastExpr(E);
7163   }
7164   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7165     return static_cast<Derived*>(this)->VisitCastExpr(E);
7166   }
7167 
7168   bool VisitBinaryOperator(const BinaryOperator *E) {
7169     switch (E->getOpcode()) {
7170     default:
7171       return Error(E);
7172 
7173     case BO_Comma:
7174       VisitIgnoredValue(E->getLHS());
7175       return StmtVisitorTy::Visit(E->getRHS());
7176 
7177     case BO_PtrMemD:
7178     case BO_PtrMemI: {
7179       LValue Obj;
7180       if (!HandleMemberPointerAccess(Info, E, Obj))
7181         return false;
7182       APValue Result;
7183       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7184         return false;
7185       return DerivedSuccess(Result, E);
7186     }
7187     }
7188   }
7189 
7190   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7191     return StmtVisitorTy::Visit(E->getSemanticForm());
7192   }
7193 
7194   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7195     // Evaluate and cache the common expression. We treat it as a temporary,
7196     // even though it's not quite the same thing.
7197     LValue CommonLV;
7198     if (!Evaluate(Info.CurrentCall->createTemporary(
7199                       E->getOpaqueValue(),
7200                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
7201                       CommonLV),
7202                   Info, E->getCommon()))
7203       return false;
7204 
7205     return HandleConditionalOperator(E);
7206   }
7207 
7208   bool VisitConditionalOperator(const ConditionalOperator *E) {
7209     bool IsBcpCall = false;
7210     // If the condition (ignoring parens) is a __builtin_constant_p call,
7211     // the result is a constant expression if it can be folded without
7212     // side-effects. This is an important GNU extension. See GCC PR38377
7213     // for discussion.
7214     if (const CallExpr *CallCE =
7215           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7216       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7217         IsBcpCall = true;
7218 
7219     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7220     // constant expression; we can't check whether it's potentially foldable.
7221     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7222     // it would return 'false' in this mode.
7223     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7224       return false;
7225 
7226     FoldConstant Fold(Info, IsBcpCall);
7227     if (!HandleConditionalOperator(E)) {
7228       Fold.keepDiagnostics();
7229       return false;
7230     }
7231 
7232     return true;
7233   }
7234 
7235   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7236     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7237       return DerivedSuccess(*Value, E);
7238 
7239     const Expr *Source = E->getSourceExpr();
7240     if (!Source)
7241       return Error(E);
7242     if (Source == E) { // sanity checking.
7243       assert(0 && "OpaqueValueExpr recursively refers to itself");
7244       return Error(E);
7245     }
7246     return StmtVisitorTy::Visit(Source);
7247   }
7248 
7249   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7250     for (const Expr *SemE : E->semantics()) {
7251       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7252         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7253         // result expression: there could be two different LValues that would
7254         // refer to the same object in that case, and we can't model that.
7255         if (SemE == E->getResultExpr())
7256           return Error(E);
7257 
7258         // Unique OVEs get evaluated if and when we encounter them when
7259         // emitting the rest of the semantic form, rather than eagerly.
7260         if (OVE->isUnique())
7261           continue;
7262 
7263         LValue LV;
7264         if (!Evaluate(Info.CurrentCall->createTemporary(
7265                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
7266                       Info, OVE->getSourceExpr()))
7267           return false;
7268       } else if (SemE == E->getResultExpr()) {
7269         if (!StmtVisitorTy::Visit(SemE))
7270           return false;
7271       } else {
7272         if (!EvaluateIgnoredValue(Info, SemE))
7273           return false;
7274       }
7275     }
7276     return true;
7277   }
7278 
7279   bool VisitCallExpr(const CallExpr *E) {
7280     APValue Result;
7281     if (!handleCallExpr(E, Result, nullptr))
7282       return false;
7283     return DerivedSuccess(Result, E);
7284   }
7285 
7286   bool handleCallExpr(const CallExpr *E, APValue &Result,
7287                      const LValue *ResultSlot) {
7288     const Expr *Callee = E->getCallee()->IgnoreParens();
7289     QualType CalleeType = Callee->getType();
7290 
7291     const FunctionDecl *FD = nullptr;
7292     LValue *This = nullptr, ThisVal;
7293     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7294     bool HasQualifier = false;
7295 
7296     // Extract function decl and 'this' pointer from the callee.
7297     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7298       const CXXMethodDecl *Member = nullptr;
7299       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7300         // Explicit bound member calls, such as x.f() or p->g();
7301         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7302           return false;
7303         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7304         if (!Member)
7305           return Error(Callee);
7306         This = &ThisVal;
7307         HasQualifier = ME->hasQualifier();
7308       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7309         // Indirect bound member calls ('.*' or '->*').
7310         const ValueDecl *D =
7311             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7312         if (!D)
7313           return false;
7314         Member = dyn_cast<CXXMethodDecl>(D);
7315         if (!Member)
7316           return Error(Callee);
7317         This = &ThisVal;
7318       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7319         if (!Info.getLangOpts().CPlusPlus20)
7320           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7321         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7322                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7323       } else
7324         return Error(Callee);
7325       FD = Member;
7326     } else if (CalleeType->isFunctionPointerType()) {
7327       LValue Call;
7328       if (!EvaluatePointer(Callee, Call, Info))
7329         return false;
7330 
7331       if (!Call.getLValueOffset().isZero())
7332         return Error(Callee);
7333       FD = dyn_cast_or_null<FunctionDecl>(
7334                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
7335       if (!FD)
7336         return Error(Callee);
7337       // Don't call function pointers which have been cast to some other type.
7338       // Per DR (no number yet), the caller and callee can differ in noexcept.
7339       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7340         CalleeType->getPointeeType(), FD->getType())) {
7341         return Error(E);
7342       }
7343 
7344       // Overloaded operator calls to member functions are represented as normal
7345       // calls with '*this' as the first argument.
7346       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7347       if (MD && !MD->isStatic()) {
7348         // FIXME: When selecting an implicit conversion for an overloaded
7349         // operator delete, we sometimes try to evaluate calls to conversion
7350         // operators without a 'this' parameter!
7351         if (Args.empty())
7352           return Error(E);
7353 
7354         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7355           return false;
7356         This = &ThisVal;
7357         Args = Args.slice(1);
7358       } else if (MD && MD->isLambdaStaticInvoker()) {
7359         // Map the static invoker for the lambda back to the call operator.
7360         // Conveniently, we don't have to slice out the 'this' argument (as is
7361         // being done for the non-static case), since a static member function
7362         // doesn't have an implicit argument passed in.
7363         const CXXRecordDecl *ClosureClass = MD->getParent();
7364         assert(
7365             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7366             "Number of captures must be zero for conversion to function-ptr");
7367 
7368         const CXXMethodDecl *LambdaCallOp =
7369             ClosureClass->getLambdaCallOperator();
7370 
7371         // Set 'FD', the function that will be called below, to the call
7372         // operator.  If the closure object represents a generic lambda, find
7373         // the corresponding specialization of the call operator.
7374 
7375         if (ClosureClass->isGenericLambda()) {
7376           assert(MD->isFunctionTemplateSpecialization() &&
7377                  "A generic lambda's static-invoker function must be a "
7378                  "template specialization");
7379           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7380           FunctionTemplateDecl *CallOpTemplate =
7381               LambdaCallOp->getDescribedFunctionTemplate();
7382           void *InsertPos = nullptr;
7383           FunctionDecl *CorrespondingCallOpSpecialization =
7384               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7385           assert(CorrespondingCallOpSpecialization &&
7386                  "We must always have a function call operator specialization "
7387                  "that corresponds to our static invoker specialization");
7388           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7389         } else
7390           FD = LambdaCallOp;
7391       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7392         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7393             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7394           LValue Ptr;
7395           if (!HandleOperatorNewCall(Info, E, Ptr))
7396             return false;
7397           Ptr.moveInto(Result);
7398           return true;
7399         } else {
7400           return HandleOperatorDeleteCall(Info, E);
7401         }
7402       }
7403     } else
7404       return Error(E);
7405 
7406     SmallVector<QualType, 4> CovariantAdjustmentPath;
7407     if (This) {
7408       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7409       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7410         // Perform virtual dispatch, if necessary.
7411         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7412                                    CovariantAdjustmentPath);
7413         if (!FD)
7414           return false;
7415       } else {
7416         // Check that the 'this' pointer points to an object of the right type.
7417         // FIXME: If this is an assignment operator call, we may need to change
7418         // the active union member before we check this.
7419         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7420           return false;
7421       }
7422     }
7423 
7424     // Destructor calls are different enough that they have their own codepath.
7425     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7426       assert(This && "no 'this' pointer for destructor call");
7427       return HandleDestruction(Info, E, *This,
7428                                Info.Ctx.getRecordType(DD->getParent()));
7429     }
7430 
7431     const FunctionDecl *Definition = nullptr;
7432     Stmt *Body = FD->getBody(Definition);
7433 
7434     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7435         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7436                             Result, ResultSlot))
7437       return false;
7438 
7439     if (!CovariantAdjustmentPath.empty() &&
7440         !HandleCovariantReturnAdjustment(Info, E, Result,
7441                                          CovariantAdjustmentPath))
7442       return false;
7443 
7444     return true;
7445   }
7446 
7447   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7448     return StmtVisitorTy::Visit(E->getInitializer());
7449   }
7450   bool VisitInitListExpr(const InitListExpr *E) {
7451     if (E->getNumInits() == 0)
7452       return DerivedZeroInitialization(E);
7453     if (E->getNumInits() == 1)
7454       return StmtVisitorTy::Visit(E->getInit(0));
7455     return Error(E);
7456   }
7457   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7458     return DerivedZeroInitialization(E);
7459   }
7460   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7461     return DerivedZeroInitialization(E);
7462   }
7463   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7464     return DerivedZeroInitialization(E);
7465   }
7466 
7467   /// A member expression where the object is a prvalue is itself a prvalue.
7468   bool VisitMemberExpr(const MemberExpr *E) {
7469     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7470            "missing temporary materialization conversion");
7471     assert(!E->isArrow() && "missing call to bound member function?");
7472 
7473     APValue Val;
7474     if (!Evaluate(Val, Info, E->getBase()))
7475       return false;
7476 
7477     QualType BaseTy = E->getBase()->getType();
7478 
7479     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7480     if (!FD) return Error(E);
7481     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7482     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7483            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7484 
7485     // Note: there is no lvalue base here. But this case should only ever
7486     // happen in C or in C++98, where we cannot be evaluating a constexpr
7487     // constructor, which is the only case the base matters.
7488     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7489     SubobjectDesignator Designator(BaseTy);
7490     Designator.addDeclUnchecked(FD);
7491 
7492     APValue Result;
7493     return extractSubobject(Info, E, Obj, Designator, Result) &&
7494            DerivedSuccess(Result, E);
7495   }
7496 
7497   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7498     APValue Val;
7499     if (!Evaluate(Val, Info, E->getBase()))
7500       return false;
7501 
7502     if (Val.isVector()) {
7503       SmallVector<uint32_t, 4> Indices;
7504       E->getEncodedElementAccess(Indices);
7505       if (Indices.size() == 1) {
7506         // Return scalar.
7507         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7508       } else {
7509         // Construct new APValue vector.
7510         SmallVector<APValue, 4> Elts;
7511         for (unsigned I = 0; I < Indices.size(); ++I) {
7512           Elts.push_back(Val.getVectorElt(Indices[I]));
7513         }
7514         APValue VecResult(Elts.data(), Indices.size());
7515         return DerivedSuccess(VecResult, E);
7516       }
7517     }
7518 
7519     return false;
7520   }
7521 
7522   bool VisitCastExpr(const CastExpr *E) {
7523     switch (E->getCastKind()) {
7524     default:
7525       break;
7526 
7527     case CK_AtomicToNonAtomic: {
7528       APValue AtomicVal;
7529       // This does not need to be done in place even for class/array types:
7530       // atomic-to-non-atomic conversion implies copying the object
7531       // representation.
7532       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7533         return false;
7534       return DerivedSuccess(AtomicVal, E);
7535     }
7536 
7537     case CK_NoOp:
7538     case CK_UserDefinedConversion:
7539       return StmtVisitorTy::Visit(E->getSubExpr());
7540 
7541     case CK_LValueToRValue: {
7542       LValue LVal;
7543       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7544         return false;
7545       APValue RVal;
7546       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7547       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7548                                           LVal, RVal))
7549         return false;
7550       return DerivedSuccess(RVal, E);
7551     }
7552     case CK_LValueToRValueBitCast: {
7553       APValue DestValue, SourceValue;
7554       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7555         return false;
7556       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7557         return false;
7558       return DerivedSuccess(DestValue, E);
7559     }
7560 
7561     case CK_AddressSpaceConversion: {
7562       APValue Value;
7563       if (!Evaluate(Value, Info, E->getSubExpr()))
7564         return false;
7565       return DerivedSuccess(Value, E);
7566     }
7567     }
7568 
7569     return Error(E);
7570   }
7571 
7572   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7573     return VisitUnaryPostIncDec(UO);
7574   }
7575   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7576     return VisitUnaryPostIncDec(UO);
7577   }
7578   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7579     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7580       return Error(UO);
7581 
7582     LValue LVal;
7583     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7584       return false;
7585     APValue RVal;
7586     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7587                       UO->isIncrementOp(), &RVal))
7588       return false;
7589     return DerivedSuccess(RVal, UO);
7590   }
7591 
7592   bool VisitStmtExpr(const StmtExpr *E) {
7593     // We will have checked the full-expressions inside the statement expression
7594     // when they were completed, and don't need to check them again now.
7595     if (Info.checkingForUndefinedBehavior())
7596       return Error(E);
7597 
7598     const CompoundStmt *CS = E->getSubStmt();
7599     if (CS->body_empty())
7600       return true;
7601 
7602     BlockScopeRAII Scope(Info);
7603     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7604                                            BE = CS->body_end();
7605          /**/; ++BI) {
7606       if (BI + 1 == BE) {
7607         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7608         if (!FinalExpr) {
7609           Info.FFDiag((*BI)->getBeginLoc(),
7610                       diag::note_constexpr_stmt_expr_unsupported);
7611           return false;
7612         }
7613         return this->Visit(FinalExpr) && Scope.destroy();
7614       }
7615 
7616       APValue ReturnValue;
7617       StmtResult Result = { ReturnValue, nullptr };
7618       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7619       if (ESR != ESR_Succeeded) {
7620         // FIXME: If the statement-expression terminated due to 'return',
7621         // 'break', or 'continue', it would be nice to propagate that to
7622         // the outer statement evaluation rather than bailing out.
7623         if (ESR != ESR_Failed)
7624           Info.FFDiag((*BI)->getBeginLoc(),
7625                       diag::note_constexpr_stmt_expr_unsupported);
7626         return false;
7627       }
7628     }
7629 
7630     llvm_unreachable("Return from function from the loop above.");
7631   }
7632 
7633   /// Visit a value which is evaluated, but whose value is ignored.
7634   void VisitIgnoredValue(const Expr *E) {
7635     EvaluateIgnoredValue(Info, E);
7636   }
7637 
7638   /// Potentially visit a MemberExpr's base expression.
7639   void VisitIgnoredBaseExpression(const Expr *E) {
7640     // While MSVC doesn't evaluate the base expression, it does diagnose the
7641     // presence of side-effecting behavior.
7642     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7643       return;
7644     VisitIgnoredValue(E);
7645   }
7646 };
7647 
7648 } // namespace
7649 
7650 //===----------------------------------------------------------------------===//
7651 // Common base class for lvalue and temporary evaluation.
7652 //===----------------------------------------------------------------------===//
7653 namespace {
7654 template<class Derived>
7655 class LValueExprEvaluatorBase
7656   : public ExprEvaluatorBase<Derived> {
7657 protected:
7658   LValue &Result;
7659   bool InvalidBaseOK;
7660   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7661   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7662 
7663   bool Success(APValue::LValueBase B) {
7664     Result.set(B);
7665     return true;
7666   }
7667 
7668   bool evaluatePointer(const Expr *E, LValue &Result) {
7669     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7670   }
7671 
7672 public:
7673   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7674       : ExprEvaluatorBaseTy(Info), Result(Result),
7675         InvalidBaseOK(InvalidBaseOK) {}
7676 
7677   bool Success(const APValue &V, const Expr *E) {
7678     Result.setFrom(this->Info.Ctx, V);
7679     return true;
7680   }
7681 
7682   bool VisitMemberExpr(const MemberExpr *E) {
7683     // Handle non-static data members.
7684     QualType BaseTy;
7685     bool EvalOK;
7686     if (E->isArrow()) {
7687       EvalOK = evaluatePointer(E->getBase(), Result);
7688       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7689     } else if (E->getBase()->isRValue()) {
7690       assert(E->getBase()->getType()->isRecordType());
7691       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7692       BaseTy = E->getBase()->getType();
7693     } else {
7694       EvalOK = this->Visit(E->getBase());
7695       BaseTy = E->getBase()->getType();
7696     }
7697     if (!EvalOK) {
7698       if (!InvalidBaseOK)
7699         return false;
7700       Result.setInvalid(E);
7701       return true;
7702     }
7703 
7704     const ValueDecl *MD = E->getMemberDecl();
7705     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7706       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7707              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7708       (void)BaseTy;
7709       if (!HandleLValueMember(this->Info, E, Result, FD))
7710         return false;
7711     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7712       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7713         return false;
7714     } else
7715       return this->Error(E);
7716 
7717     if (MD->getType()->isReferenceType()) {
7718       APValue RefValue;
7719       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7720                                           RefValue))
7721         return false;
7722       return Success(RefValue, E);
7723     }
7724     return true;
7725   }
7726 
7727   bool VisitBinaryOperator(const BinaryOperator *E) {
7728     switch (E->getOpcode()) {
7729     default:
7730       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7731 
7732     case BO_PtrMemD:
7733     case BO_PtrMemI:
7734       return HandleMemberPointerAccess(this->Info, E, Result);
7735     }
7736   }
7737 
7738   bool VisitCastExpr(const CastExpr *E) {
7739     switch (E->getCastKind()) {
7740     default:
7741       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7742 
7743     case CK_DerivedToBase:
7744     case CK_UncheckedDerivedToBase:
7745       if (!this->Visit(E->getSubExpr()))
7746         return false;
7747 
7748       // Now figure out the necessary offset to add to the base LV to get from
7749       // the derived class to the base class.
7750       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7751                                   Result);
7752     }
7753   }
7754 };
7755 }
7756 
7757 //===----------------------------------------------------------------------===//
7758 // LValue Evaluation
7759 //
7760 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7761 // function designators (in C), decl references to void objects (in C), and
7762 // temporaries (if building with -Wno-address-of-temporary).
7763 //
7764 // LValue evaluation produces values comprising a base expression of one of the
7765 // following types:
7766 // - Declarations
7767 //  * VarDecl
7768 //  * FunctionDecl
7769 // - Literals
7770 //  * CompoundLiteralExpr in C (and in global scope in C++)
7771 //  * StringLiteral
7772 //  * PredefinedExpr
7773 //  * ObjCStringLiteralExpr
7774 //  * ObjCEncodeExpr
7775 //  * AddrLabelExpr
7776 //  * BlockExpr
7777 //  * CallExpr for a MakeStringConstant builtin
7778 // - typeid(T) expressions, as TypeInfoLValues
7779 // - Locals and temporaries
7780 //  * MaterializeTemporaryExpr
7781 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7782 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7783 //    from the AST (FIXME).
7784 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7785 //    CallIndex, for a lifetime-extended temporary.
7786 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7787 //    immediate invocation.
7788 // plus an offset in bytes.
7789 //===----------------------------------------------------------------------===//
7790 namespace {
7791 class LValueExprEvaluator
7792   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7793 public:
7794   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7795     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7796 
7797   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7798   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7799 
7800   bool VisitDeclRefExpr(const DeclRefExpr *E);
7801   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7802   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7803   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7804   bool VisitMemberExpr(const MemberExpr *E);
7805   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7806   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7807   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7808   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7809   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7810   bool VisitUnaryDeref(const UnaryOperator *E);
7811   bool VisitUnaryReal(const UnaryOperator *E);
7812   bool VisitUnaryImag(const UnaryOperator *E);
7813   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7814     return VisitUnaryPreIncDec(UO);
7815   }
7816   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7817     return VisitUnaryPreIncDec(UO);
7818   }
7819   bool VisitBinAssign(const BinaryOperator *BO);
7820   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7821 
7822   bool VisitCastExpr(const CastExpr *E) {
7823     switch (E->getCastKind()) {
7824     default:
7825       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7826 
7827     case CK_LValueBitCast:
7828       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7829       if (!Visit(E->getSubExpr()))
7830         return false;
7831       Result.Designator.setInvalid();
7832       return true;
7833 
7834     case CK_BaseToDerived:
7835       if (!Visit(E->getSubExpr()))
7836         return false;
7837       return HandleBaseToDerivedCast(Info, E, Result);
7838 
7839     case CK_Dynamic:
7840       if (!Visit(E->getSubExpr()))
7841         return false;
7842       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7843     }
7844   }
7845 };
7846 } // end anonymous namespace
7847 
7848 /// Evaluate an expression as an lvalue. This can be legitimately called on
7849 /// expressions which are not glvalues, in three cases:
7850 ///  * function designators in C, and
7851 ///  * "extern void" objects
7852 ///  * @selector() expressions in Objective-C
7853 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7854                            bool InvalidBaseOK) {
7855   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7856          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7857   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7858 }
7859 
7860 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7861   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7862     return Success(FD);
7863   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7864     return VisitVarDecl(E, VD);
7865   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7866     return Visit(BD->getBinding());
7867   if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl()))
7868     return Success(GD);
7869   return Error(E);
7870 }
7871 
7872 
7873 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7874 
7875   // If we are within a lambda's call operator, check whether the 'VD' referred
7876   // to within 'E' actually represents a lambda-capture that maps to a
7877   // data-member/field within the closure object, and if so, evaluate to the
7878   // field or what the field refers to.
7879   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7880       isa<DeclRefExpr>(E) &&
7881       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7882     // We don't always have a complete capture-map when checking or inferring if
7883     // the function call operator meets the requirements of a constexpr function
7884     // - but we don't need to evaluate the captures to determine constexprness
7885     // (dcl.constexpr C++17).
7886     if (Info.checkingPotentialConstantExpression())
7887       return false;
7888 
7889     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7890       // Start with 'Result' referring to the complete closure object...
7891       Result = *Info.CurrentCall->This;
7892       // ... then update it to refer to the field of the closure object
7893       // that represents the capture.
7894       if (!HandleLValueMember(Info, E, Result, FD))
7895         return false;
7896       // And if the field is of reference type, update 'Result' to refer to what
7897       // the field refers to.
7898       if (FD->getType()->isReferenceType()) {
7899         APValue RVal;
7900         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7901                                             RVal))
7902           return false;
7903         Result.setFrom(Info.Ctx, RVal);
7904       }
7905       return true;
7906     }
7907   }
7908   CallStackFrame *Frame = nullptr;
7909   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7910     // Only if a local variable was declared in the function currently being
7911     // evaluated, do we expect to be able to find its value in the current
7912     // frame. (Otherwise it was likely declared in an enclosing context and
7913     // could either have a valid evaluatable value (for e.g. a constexpr
7914     // variable) or be ill-formed (and trigger an appropriate evaluation
7915     // diagnostic)).
7916     if (Info.CurrentCall->Callee &&
7917         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7918       Frame = Info.CurrentCall;
7919     }
7920   }
7921 
7922   if (!VD->getType()->isReferenceType()) {
7923     if (Frame) {
7924       Result.set({VD, Frame->Index,
7925                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7926       return true;
7927     }
7928     return Success(VD);
7929   }
7930 
7931   APValue *V;
7932   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7933     return false;
7934   if (!V->hasValue()) {
7935     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7936     // adjust the diagnostic to say that.
7937     if (!Info.checkingPotentialConstantExpression())
7938       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7939     return false;
7940   }
7941   return Success(*V, E);
7942 }
7943 
7944 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7945     const MaterializeTemporaryExpr *E) {
7946   // Walk through the expression to find the materialized temporary itself.
7947   SmallVector<const Expr *, 2> CommaLHSs;
7948   SmallVector<SubobjectAdjustment, 2> Adjustments;
7949   const Expr *Inner =
7950       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7951 
7952   // If we passed any comma operators, evaluate their LHSs.
7953   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7954     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7955       return false;
7956 
7957   // A materialized temporary with static storage duration can appear within the
7958   // result of a constant expression evaluation, so we need to preserve its
7959   // value for use outside this evaluation.
7960   APValue *Value;
7961   if (E->getStorageDuration() == SD_Static) {
7962     Value = E->getOrCreateValue(true);
7963     *Value = APValue();
7964     Result.set(E);
7965   } else {
7966     Value = &Info.CurrentCall->createTemporary(
7967         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7968   }
7969 
7970   QualType Type = Inner->getType();
7971 
7972   // Materialize the temporary itself.
7973   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7974     *Value = APValue();
7975     return false;
7976   }
7977 
7978   // Adjust our lvalue to refer to the desired subobject.
7979   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7980     --I;
7981     switch (Adjustments[I].Kind) {
7982     case SubobjectAdjustment::DerivedToBaseAdjustment:
7983       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7984                                 Type, Result))
7985         return false;
7986       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7987       break;
7988 
7989     case SubobjectAdjustment::FieldAdjustment:
7990       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7991         return false;
7992       Type = Adjustments[I].Field->getType();
7993       break;
7994 
7995     case SubobjectAdjustment::MemberPointerAdjustment:
7996       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7997                                      Adjustments[I].Ptr.RHS))
7998         return false;
7999       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8000       break;
8001     }
8002   }
8003 
8004   return true;
8005 }
8006 
8007 bool
8008 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8009   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8010          "lvalue compound literal in c++?");
8011   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8012   // only see this when folding in C, so there's no standard to follow here.
8013   return Success(E);
8014 }
8015 
8016 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8017   TypeInfoLValue TypeInfo;
8018 
8019   if (!E->isPotentiallyEvaluated()) {
8020     if (E->isTypeOperand())
8021       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8022     else
8023       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8024   } else {
8025     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8026       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8027         << E->getExprOperand()->getType()
8028         << E->getExprOperand()->getSourceRange();
8029     }
8030 
8031     if (!Visit(E->getExprOperand()))
8032       return false;
8033 
8034     Optional<DynamicType> DynType =
8035         ComputeDynamicType(Info, E, Result, AK_TypeId);
8036     if (!DynType)
8037       return false;
8038 
8039     TypeInfo =
8040         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8041   }
8042 
8043   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8044 }
8045 
8046 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8047   return Success(E->getGuidDecl());
8048 }
8049 
8050 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8051   // Handle static data members.
8052   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8053     VisitIgnoredBaseExpression(E->getBase());
8054     return VisitVarDecl(E, VD);
8055   }
8056 
8057   // Handle static member functions.
8058   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8059     if (MD->isStatic()) {
8060       VisitIgnoredBaseExpression(E->getBase());
8061       return Success(MD);
8062     }
8063   }
8064 
8065   // Handle non-static data members.
8066   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8067 }
8068 
8069 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8070   // FIXME: Deal with vectors as array subscript bases.
8071   if (E->getBase()->getType()->isVectorType())
8072     return Error(E);
8073 
8074   bool Success = true;
8075   if (!evaluatePointer(E->getBase(), Result)) {
8076     if (!Info.noteFailure())
8077       return false;
8078     Success = false;
8079   }
8080 
8081   APSInt Index;
8082   if (!EvaluateInteger(E->getIdx(), Index, Info))
8083     return false;
8084 
8085   return Success &&
8086          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8087 }
8088 
8089 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8090   return evaluatePointer(E->getSubExpr(), Result);
8091 }
8092 
8093 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8094   if (!Visit(E->getSubExpr()))
8095     return false;
8096   // __real is a no-op on scalar lvalues.
8097   if (E->getSubExpr()->getType()->isAnyComplexType())
8098     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8099   return true;
8100 }
8101 
8102 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8103   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8104          "lvalue __imag__ on scalar?");
8105   if (!Visit(E->getSubExpr()))
8106     return false;
8107   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8108   return true;
8109 }
8110 
8111 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8112   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8113     return Error(UO);
8114 
8115   if (!this->Visit(UO->getSubExpr()))
8116     return false;
8117 
8118   return handleIncDec(
8119       this->Info, UO, Result, UO->getSubExpr()->getType(),
8120       UO->isIncrementOp(), nullptr);
8121 }
8122 
8123 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8124     const CompoundAssignOperator *CAO) {
8125   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8126     return Error(CAO);
8127 
8128   APValue RHS;
8129 
8130   // The overall lvalue result is the result of evaluating the LHS.
8131   if (!this->Visit(CAO->getLHS())) {
8132     if (Info.noteFailure())
8133       Evaluate(RHS, this->Info, CAO->getRHS());
8134     return false;
8135   }
8136 
8137   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
8138     return false;
8139 
8140   return handleCompoundAssignment(
8141       this->Info, CAO,
8142       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8143       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8144 }
8145 
8146 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8147   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8148     return Error(E);
8149 
8150   APValue NewVal;
8151 
8152   if (!this->Visit(E->getLHS())) {
8153     if (Info.noteFailure())
8154       Evaluate(NewVal, this->Info, E->getRHS());
8155     return false;
8156   }
8157 
8158   if (!Evaluate(NewVal, this->Info, E->getRHS()))
8159     return false;
8160 
8161   if (Info.getLangOpts().CPlusPlus20 &&
8162       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8163     return false;
8164 
8165   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8166                           NewVal);
8167 }
8168 
8169 //===----------------------------------------------------------------------===//
8170 // Pointer Evaluation
8171 //===----------------------------------------------------------------------===//
8172 
8173 /// Attempts to compute the number of bytes available at the pointer
8174 /// returned by a function with the alloc_size attribute. Returns true if we
8175 /// were successful. Places an unsigned number into `Result`.
8176 ///
8177 /// This expects the given CallExpr to be a call to a function with an
8178 /// alloc_size attribute.
8179 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8180                                             const CallExpr *Call,
8181                                             llvm::APInt &Result) {
8182   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8183 
8184   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8185   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8186   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8187   if (Call->getNumArgs() <= SizeArgNo)
8188     return false;
8189 
8190   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8191     Expr::EvalResult ExprResult;
8192     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8193       return false;
8194     Into = ExprResult.Val.getInt();
8195     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8196       return false;
8197     Into = Into.zextOrSelf(BitsInSizeT);
8198     return true;
8199   };
8200 
8201   APSInt SizeOfElem;
8202   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8203     return false;
8204 
8205   if (!AllocSize->getNumElemsParam().isValid()) {
8206     Result = std::move(SizeOfElem);
8207     return true;
8208   }
8209 
8210   APSInt NumberOfElems;
8211   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8212   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8213     return false;
8214 
8215   bool Overflow;
8216   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8217   if (Overflow)
8218     return false;
8219 
8220   Result = std::move(BytesAvailable);
8221   return true;
8222 }
8223 
8224 /// Convenience function. LVal's base must be a call to an alloc_size
8225 /// function.
8226 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8227                                             const LValue &LVal,
8228                                             llvm::APInt &Result) {
8229   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8230          "Can't get the size of a non alloc_size function");
8231   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8232   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8233   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8234 }
8235 
8236 /// Attempts to evaluate the given LValueBase as the result of a call to
8237 /// a function with the alloc_size attribute. If it was possible to do so, this
8238 /// function will return true, make Result's Base point to said function call,
8239 /// and mark Result's Base as invalid.
8240 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8241                                       LValue &Result) {
8242   if (Base.isNull())
8243     return false;
8244 
8245   // Because we do no form of static analysis, we only support const variables.
8246   //
8247   // Additionally, we can't support parameters, nor can we support static
8248   // variables (in the latter case, use-before-assign isn't UB; in the former,
8249   // we have no clue what they'll be assigned to).
8250   const auto *VD =
8251       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8252   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8253     return false;
8254 
8255   const Expr *Init = VD->getAnyInitializer();
8256   if (!Init)
8257     return false;
8258 
8259   const Expr *E = Init->IgnoreParens();
8260   if (!tryUnwrapAllocSizeCall(E))
8261     return false;
8262 
8263   // Store E instead of E unwrapped so that the type of the LValue's base is
8264   // what the user wanted.
8265   Result.setInvalid(E);
8266 
8267   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8268   Result.addUnsizedArray(Info, E, Pointee);
8269   return true;
8270 }
8271 
8272 namespace {
8273 class PointerExprEvaluator
8274   : public ExprEvaluatorBase<PointerExprEvaluator> {
8275   LValue &Result;
8276   bool InvalidBaseOK;
8277 
8278   bool Success(const Expr *E) {
8279     Result.set(E);
8280     return true;
8281   }
8282 
8283   bool evaluateLValue(const Expr *E, LValue &Result) {
8284     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8285   }
8286 
8287   bool evaluatePointer(const Expr *E, LValue &Result) {
8288     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8289   }
8290 
8291   bool visitNonBuiltinCallExpr(const CallExpr *E);
8292 public:
8293 
8294   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8295       : ExprEvaluatorBaseTy(info), Result(Result),
8296         InvalidBaseOK(InvalidBaseOK) {}
8297 
8298   bool Success(const APValue &V, const Expr *E) {
8299     Result.setFrom(Info.Ctx, V);
8300     return true;
8301   }
8302   bool ZeroInitialization(const Expr *E) {
8303     Result.setNull(Info.Ctx, E->getType());
8304     return true;
8305   }
8306 
8307   bool VisitBinaryOperator(const BinaryOperator *E);
8308   bool VisitCastExpr(const CastExpr* E);
8309   bool VisitUnaryAddrOf(const UnaryOperator *E);
8310   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8311       { return Success(E); }
8312   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8313     if (E->isExpressibleAsConstantInitializer())
8314       return Success(E);
8315     if (Info.noteFailure())
8316       EvaluateIgnoredValue(Info, E->getSubExpr());
8317     return Error(E);
8318   }
8319   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8320       { return Success(E); }
8321   bool VisitCallExpr(const CallExpr *E);
8322   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8323   bool VisitBlockExpr(const BlockExpr *E) {
8324     if (!E->getBlockDecl()->hasCaptures())
8325       return Success(E);
8326     return Error(E);
8327   }
8328   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8329     // Can't look at 'this' when checking a potential constant expression.
8330     if (Info.checkingPotentialConstantExpression())
8331       return false;
8332     if (!Info.CurrentCall->This) {
8333       if (Info.getLangOpts().CPlusPlus11)
8334         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8335       else
8336         Info.FFDiag(E);
8337       return false;
8338     }
8339     Result = *Info.CurrentCall->This;
8340     // If we are inside a lambda's call operator, the 'this' expression refers
8341     // to the enclosing '*this' object (either by value or reference) which is
8342     // either copied into the closure object's field that represents the '*this'
8343     // or refers to '*this'.
8344     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8345       // Ensure we actually have captured 'this'. (an error will have
8346       // been previously reported if not).
8347       if (!Info.CurrentCall->LambdaThisCaptureField)
8348         return false;
8349 
8350       // Update 'Result' to refer to the data member/field of the closure object
8351       // that represents the '*this' capture.
8352       if (!HandleLValueMember(Info, E, Result,
8353                              Info.CurrentCall->LambdaThisCaptureField))
8354         return false;
8355       // If we captured '*this' by reference, replace the field with its referent.
8356       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8357               ->isPointerType()) {
8358         APValue RVal;
8359         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8360                                             RVal))
8361           return false;
8362 
8363         Result.setFrom(Info.Ctx, RVal);
8364       }
8365     }
8366     return true;
8367   }
8368 
8369   bool VisitCXXNewExpr(const CXXNewExpr *E);
8370 
8371   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8372     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8373     APValue LValResult = E->EvaluateInContext(
8374         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8375     Result.setFrom(Info.Ctx, LValResult);
8376     return true;
8377   }
8378 
8379   // FIXME: Missing: @protocol, @selector
8380 };
8381 } // end anonymous namespace
8382 
8383 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8384                             bool InvalidBaseOK) {
8385   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8386   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8387 }
8388 
8389 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8390   if (E->getOpcode() != BO_Add &&
8391       E->getOpcode() != BO_Sub)
8392     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8393 
8394   const Expr *PExp = E->getLHS();
8395   const Expr *IExp = E->getRHS();
8396   if (IExp->getType()->isPointerType())
8397     std::swap(PExp, IExp);
8398 
8399   bool EvalPtrOK = evaluatePointer(PExp, Result);
8400   if (!EvalPtrOK && !Info.noteFailure())
8401     return false;
8402 
8403   llvm::APSInt Offset;
8404   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8405     return false;
8406 
8407   if (E->getOpcode() == BO_Sub)
8408     negateAsSigned(Offset);
8409 
8410   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8411   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8412 }
8413 
8414 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8415   return evaluateLValue(E->getSubExpr(), Result);
8416 }
8417 
8418 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8419   const Expr *SubExpr = E->getSubExpr();
8420 
8421   switch (E->getCastKind()) {
8422   default:
8423     break;
8424   case CK_BitCast:
8425   case CK_CPointerToObjCPointerCast:
8426   case CK_BlockPointerToObjCPointerCast:
8427   case CK_AnyPointerToBlockPointerCast:
8428   case CK_AddressSpaceConversion:
8429     if (!Visit(SubExpr))
8430       return false;
8431     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8432     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8433     // also static_casts, but we disallow them as a resolution to DR1312.
8434     if (!E->getType()->isVoidPointerType()) {
8435       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8436           !Result.IsNullPtr &&
8437           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8438                                           E->getType()->getPointeeType()) &&
8439           Info.getStdAllocatorCaller("allocate")) {
8440         // Inside a call to std::allocator::allocate and friends, we permit
8441         // casting from void* back to cv1 T* for a pointer that points to a
8442         // cv2 T.
8443       } else {
8444         Result.Designator.setInvalid();
8445         if (SubExpr->getType()->isVoidPointerType())
8446           CCEDiag(E, diag::note_constexpr_invalid_cast)
8447             << 3 << SubExpr->getType();
8448         else
8449           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8450       }
8451     }
8452     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8453       ZeroInitialization(E);
8454     return true;
8455 
8456   case CK_DerivedToBase:
8457   case CK_UncheckedDerivedToBase:
8458     if (!evaluatePointer(E->getSubExpr(), Result))
8459       return false;
8460     if (!Result.Base && Result.Offset.isZero())
8461       return true;
8462 
8463     // Now figure out the necessary offset to add to the base LV to get from
8464     // the derived class to the base class.
8465     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8466                                   castAs<PointerType>()->getPointeeType(),
8467                                 Result);
8468 
8469   case CK_BaseToDerived:
8470     if (!Visit(E->getSubExpr()))
8471       return false;
8472     if (!Result.Base && Result.Offset.isZero())
8473       return true;
8474     return HandleBaseToDerivedCast(Info, E, Result);
8475 
8476   case CK_Dynamic:
8477     if (!Visit(E->getSubExpr()))
8478       return false;
8479     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8480 
8481   case CK_NullToPointer:
8482     VisitIgnoredValue(E->getSubExpr());
8483     return ZeroInitialization(E);
8484 
8485   case CK_IntegralToPointer: {
8486     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8487 
8488     APValue Value;
8489     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8490       break;
8491 
8492     if (Value.isInt()) {
8493       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8494       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8495       Result.Base = (Expr*)nullptr;
8496       Result.InvalidBase = false;
8497       Result.Offset = CharUnits::fromQuantity(N);
8498       Result.Designator.setInvalid();
8499       Result.IsNullPtr = false;
8500       return true;
8501     } else {
8502       // Cast is of an lvalue, no need to change value.
8503       Result.setFrom(Info.Ctx, Value);
8504       return true;
8505     }
8506   }
8507 
8508   case CK_ArrayToPointerDecay: {
8509     if (SubExpr->isGLValue()) {
8510       if (!evaluateLValue(SubExpr, Result))
8511         return false;
8512     } else {
8513       APValue &Value = Info.CurrentCall->createTemporary(
8514           SubExpr, SubExpr->getType(), false, Result);
8515       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8516         return false;
8517     }
8518     // The result is a pointer to the first element of the array.
8519     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8520     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8521       Result.addArray(Info, E, CAT);
8522     else
8523       Result.addUnsizedArray(Info, E, AT->getElementType());
8524     return true;
8525   }
8526 
8527   case CK_FunctionToPointerDecay:
8528     return evaluateLValue(SubExpr, Result);
8529 
8530   case CK_LValueToRValue: {
8531     LValue LVal;
8532     if (!evaluateLValue(E->getSubExpr(), LVal))
8533       return false;
8534 
8535     APValue RVal;
8536     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8537     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8538                                         LVal, RVal))
8539       return InvalidBaseOK &&
8540              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8541     return Success(RVal, E);
8542   }
8543   }
8544 
8545   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8546 }
8547 
8548 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8549                                 UnaryExprOrTypeTrait ExprKind) {
8550   // C++ [expr.alignof]p3:
8551   //     When alignof is applied to a reference type, the result is the
8552   //     alignment of the referenced type.
8553   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8554     T = Ref->getPointeeType();
8555 
8556   if (T.getQualifiers().hasUnaligned())
8557     return CharUnits::One();
8558 
8559   const bool AlignOfReturnsPreferred =
8560       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8561 
8562   // __alignof is defined to return the preferred alignment.
8563   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8564   // as well.
8565   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8566     return Info.Ctx.toCharUnitsFromBits(
8567       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8568   // alignof and _Alignof are defined to return the ABI alignment.
8569   else if (ExprKind == UETT_AlignOf)
8570     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8571   else
8572     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8573 }
8574 
8575 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8576                                 UnaryExprOrTypeTrait ExprKind) {
8577   E = E->IgnoreParens();
8578 
8579   // The kinds of expressions that we have special-case logic here for
8580   // should be kept up to date with the special checks for those
8581   // expressions in Sema.
8582 
8583   // alignof decl is always accepted, even if it doesn't make sense: we default
8584   // to 1 in those cases.
8585   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8586     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8587                                  /*RefAsPointee*/true);
8588 
8589   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8590     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8591                                  /*RefAsPointee*/true);
8592 
8593   return GetAlignOfType(Info, E->getType(), ExprKind);
8594 }
8595 
8596 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8597   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8598     return Info.Ctx.getDeclAlign(VD);
8599   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8600     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8601   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8602 }
8603 
8604 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8605 /// __builtin_is_aligned and __builtin_assume_aligned.
8606 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8607                                  EvalInfo &Info, APSInt &Alignment) {
8608   if (!EvaluateInteger(E, Alignment, Info))
8609     return false;
8610   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8611     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8612     return false;
8613   }
8614   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8615   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8616   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8617     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8618         << MaxValue << ForType << Alignment;
8619     return false;
8620   }
8621   // Ensure both alignment and source value have the same bit width so that we
8622   // don't assert when computing the resulting value.
8623   APSInt ExtAlignment =
8624       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8625   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8626          "Alignment should not be changed by ext/trunc");
8627   Alignment = ExtAlignment;
8628   assert(Alignment.getBitWidth() == SrcWidth);
8629   return true;
8630 }
8631 
8632 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8633 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8634   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8635     return true;
8636 
8637   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8638     return false;
8639 
8640   Result.setInvalid(E);
8641   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8642   Result.addUnsizedArray(Info, E, PointeeTy);
8643   return true;
8644 }
8645 
8646 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8647   if (IsStringLiteralCall(E))
8648     return Success(E);
8649 
8650   if (unsigned BuiltinOp = E->getBuiltinCallee())
8651     return VisitBuiltinCallExpr(E, BuiltinOp);
8652 
8653   return visitNonBuiltinCallExpr(E);
8654 }
8655 
8656 // Determine if T is a character type for which we guarantee that
8657 // sizeof(T) == 1.
8658 static bool isOneByteCharacterType(QualType T) {
8659   return T->isCharType() || T->isChar8Type();
8660 }
8661 
8662 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8663                                                 unsigned BuiltinOp) {
8664   switch (BuiltinOp) {
8665   case Builtin::BI__builtin_addressof:
8666     return evaluateLValue(E->getArg(0), Result);
8667   case Builtin::BI__builtin_assume_aligned: {
8668     // We need to be very careful here because: if the pointer does not have the
8669     // asserted alignment, then the behavior is undefined, and undefined
8670     // behavior is non-constant.
8671     if (!evaluatePointer(E->getArg(0), Result))
8672       return false;
8673 
8674     LValue OffsetResult(Result);
8675     APSInt Alignment;
8676     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8677                               Alignment))
8678       return false;
8679     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8680 
8681     if (E->getNumArgs() > 2) {
8682       APSInt Offset;
8683       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8684         return false;
8685 
8686       int64_t AdditionalOffset = -Offset.getZExtValue();
8687       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8688     }
8689 
8690     // If there is a base object, then it must have the correct alignment.
8691     if (OffsetResult.Base) {
8692       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8693 
8694       if (BaseAlignment < Align) {
8695         Result.Designator.setInvalid();
8696         // FIXME: Add support to Diagnostic for long / long long.
8697         CCEDiag(E->getArg(0),
8698                 diag::note_constexpr_baa_insufficient_alignment) << 0
8699           << (unsigned)BaseAlignment.getQuantity()
8700           << (unsigned)Align.getQuantity();
8701         return false;
8702       }
8703     }
8704 
8705     // The offset must also have the correct alignment.
8706     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8707       Result.Designator.setInvalid();
8708 
8709       (OffsetResult.Base
8710            ? CCEDiag(E->getArg(0),
8711                      diag::note_constexpr_baa_insufficient_alignment) << 1
8712            : CCEDiag(E->getArg(0),
8713                      diag::note_constexpr_baa_value_insufficient_alignment))
8714         << (int)OffsetResult.Offset.getQuantity()
8715         << (unsigned)Align.getQuantity();
8716       return false;
8717     }
8718 
8719     return true;
8720   }
8721   case Builtin::BI__builtin_align_up:
8722   case Builtin::BI__builtin_align_down: {
8723     if (!evaluatePointer(E->getArg(0), Result))
8724       return false;
8725     APSInt Alignment;
8726     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8727                               Alignment))
8728       return false;
8729     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8730     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8731     // For align_up/align_down, we can return the same value if the alignment
8732     // is known to be greater or equal to the requested value.
8733     if (PtrAlign.getQuantity() >= Alignment)
8734       return true;
8735 
8736     // The alignment could be greater than the minimum at run-time, so we cannot
8737     // infer much about the resulting pointer value. One case is possible:
8738     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8739     // can infer the correct index if the requested alignment is smaller than
8740     // the base alignment so we can perform the computation on the offset.
8741     if (BaseAlignment.getQuantity() >= Alignment) {
8742       assert(Alignment.getBitWidth() <= 64 &&
8743              "Cannot handle > 64-bit address-space");
8744       uint64_t Alignment64 = Alignment.getZExtValue();
8745       CharUnits NewOffset = CharUnits::fromQuantity(
8746           BuiltinOp == Builtin::BI__builtin_align_down
8747               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8748               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8749       Result.adjustOffset(NewOffset - Result.Offset);
8750       // TODO: diagnose out-of-bounds values/only allow for arrays?
8751       return true;
8752     }
8753     // Otherwise, we cannot constant-evaluate the result.
8754     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8755         << Alignment;
8756     return false;
8757   }
8758   case Builtin::BI__builtin_operator_new:
8759     return HandleOperatorNewCall(Info, E, Result);
8760   case Builtin::BI__builtin_launder:
8761     return evaluatePointer(E->getArg(0), Result);
8762   case Builtin::BIstrchr:
8763   case Builtin::BIwcschr:
8764   case Builtin::BImemchr:
8765   case Builtin::BIwmemchr:
8766     if (Info.getLangOpts().CPlusPlus11)
8767       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8768         << /*isConstexpr*/0 << /*isConstructor*/0
8769         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8770     else
8771       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8772     LLVM_FALLTHROUGH;
8773   case Builtin::BI__builtin_strchr:
8774   case Builtin::BI__builtin_wcschr:
8775   case Builtin::BI__builtin_memchr:
8776   case Builtin::BI__builtin_char_memchr:
8777   case Builtin::BI__builtin_wmemchr: {
8778     if (!Visit(E->getArg(0)))
8779       return false;
8780     APSInt Desired;
8781     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8782       return false;
8783     uint64_t MaxLength = uint64_t(-1);
8784     if (BuiltinOp != Builtin::BIstrchr &&
8785         BuiltinOp != Builtin::BIwcschr &&
8786         BuiltinOp != Builtin::BI__builtin_strchr &&
8787         BuiltinOp != Builtin::BI__builtin_wcschr) {
8788       APSInt N;
8789       if (!EvaluateInteger(E->getArg(2), N, Info))
8790         return false;
8791       MaxLength = N.getExtValue();
8792     }
8793     // We cannot find the value if there are no candidates to match against.
8794     if (MaxLength == 0u)
8795       return ZeroInitialization(E);
8796     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8797         Result.Designator.Invalid)
8798       return false;
8799     QualType CharTy = Result.Designator.getType(Info.Ctx);
8800     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8801                      BuiltinOp == Builtin::BI__builtin_memchr;
8802     assert(IsRawByte ||
8803            Info.Ctx.hasSameUnqualifiedType(
8804                CharTy, E->getArg(0)->getType()->getPointeeType()));
8805     // Pointers to const void may point to objects of incomplete type.
8806     if (IsRawByte && CharTy->isIncompleteType()) {
8807       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8808       return false;
8809     }
8810     // Give up on byte-oriented matching against multibyte elements.
8811     // FIXME: We can compare the bytes in the correct order.
8812     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
8813       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
8814           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
8815           << CharTy;
8816       return false;
8817     }
8818     // Figure out what value we're actually looking for (after converting to
8819     // the corresponding unsigned type if necessary).
8820     uint64_t DesiredVal;
8821     bool StopAtNull = false;
8822     switch (BuiltinOp) {
8823     case Builtin::BIstrchr:
8824     case Builtin::BI__builtin_strchr:
8825       // strchr compares directly to the passed integer, and therefore
8826       // always fails if given an int that is not a char.
8827       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8828                                                   E->getArg(1)->getType(),
8829                                                   Desired),
8830                                Desired))
8831         return ZeroInitialization(E);
8832       StopAtNull = true;
8833       LLVM_FALLTHROUGH;
8834     case Builtin::BImemchr:
8835     case Builtin::BI__builtin_memchr:
8836     case Builtin::BI__builtin_char_memchr:
8837       // memchr compares by converting both sides to unsigned char. That's also
8838       // correct for strchr if we get this far (to cope with plain char being
8839       // unsigned in the strchr case).
8840       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8841       break;
8842 
8843     case Builtin::BIwcschr:
8844     case Builtin::BI__builtin_wcschr:
8845       StopAtNull = true;
8846       LLVM_FALLTHROUGH;
8847     case Builtin::BIwmemchr:
8848     case Builtin::BI__builtin_wmemchr:
8849       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8850       DesiredVal = Desired.getZExtValue();
8851       break;
8852     }
8853 
8854     for (; MaxLength; --MaxLength) {
8855       APValue Char;
8856       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8857           !Char.isInt())
8858         return false;
8859       if (Char.getInt().getZExtValue() == DesiredVal)
8860         return true;
8861       if (StopAtNull && !Char.getInt())
8862         break;
8863       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8864         return false;
8865     }
8866     // Not found: return nullptr.
8867     return ZeroInitialization(E);
8868   }
8869 
8870   case Builtin::BImemcpy:
8871   case Builtin::BImemmove:
8872   case Builtin::BIwmemcpy:
8873   case Builtin::BIwmemmove:
8874     if (Info.getLangOpts().CPlusPlus11)
8875       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8876         << /*isConstexpr*/0 << /*isConstructor*/0
8877         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8878     else
8879       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8880     LLVM_FALLTHROUGH;
8881   case Builtin::BI__builtin_memcpy:
8882   case Builtin::BI__builtin_memmove:
8883   case Builtin::BI__builtin_wmemcpy:
8884   case Builtin::BI__builtin_wmemmove: {
8885     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8886                  BuiltinOp == Builtin::BIwmemmove ||
8887                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8888                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8889     bool Move = BuiltinOp == Builtin::BImemmove ||
8890                 BuiltinOp == Builtin::BIwmemmove ||
8891                 BuiltinOp == Builtin::BI__builtin_memmove ||
8892                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8893 
8894     // The result of mem* is the first argument.
8895     if (!Visit(E->getArg(0)))
8896       return false;
8897     LValue Dest = Result;
8898 
8899     LValue Src;
8900     if (!EvaluatePointer(E->getArg(1), Src, Info))
8901       return false;
8902 
8903     APSInt N;
8904     if (!EvaluateInteger(E->getArg(2), N, Info))
8905       return false;
8906     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8907 
8908     // If the size is zero, we treat this as always being a valid no-op.
8909     // (Even if one of the src and dest pointers is null.)
8910     if (!N)
8911       return true;
8912 
8913     // Otherwise, if either of the operands is null, we can't proceed. Don't
8914     // try to determine the type of the copied objects, because there aren't
8915     // any.
8916     if (!Src.Base || !Dest.Base) {
8917       APValue Val;
8918       (!Src.Base ? Src : Dest).moveInto(Val);
8919       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8920           << Move << WChar << !!Src.Base
8921           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8922       return false;
8923     }
8924     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8925       return false;
8926 
8927     // We require that Src and Dest are both pointers to arrays of
8928     // trivially-copyable type. (For the wide version, the designator will be
8929     // invalid if the designated object is not a wchar_t.)
8930     QualType T = Dest.Designator.getType(Info.Ctx);
8931     QualType SrcT = Src.Designator.getType(Info.Ctx);
8932     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8933       // FIXME: Consider using our bit_cast implementation to support this.
8934       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8935       return false;
8936     }
8937     if (T->isIncompleteType()) {
8938       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8939       return false;
8940     }
8941     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8942       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8943       return false;
8944     }
8945 
8946     // Figure out how many T's we're copying.
8947     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8948     if (!WChar) {
8949       uint64_t Remainder;
8950       llvm::APInt OrigN = N;
8951       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8952       if (Remainder) {
8953         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8954             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8955             << (unsigned)TSize;
8956         return false;
8957       }
8958     }
8959 
8960     // Check that the copying will remain within the arrays, just so that we
8961     // can give a more meaningful diagnostic. This implicitly also checks that
8962     // N fits into 64 bits.
8963     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8964     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8965     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8966       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8967           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8968           << N.toString(10, /*Signed*/false);
8969       return false;
8970     }
8971     uint64_t NElems = N.getZExtValue();
8972     uint64_t NBytes = NElems * TSize;
8973 
8974     // Check for overlap.
8975     int Direction = 1;
8976     if (HasSameBase(Src, Dest)) {
8977       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8978       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8979       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8980         // Dest is inside the source region.
8981         if (!Move) {
8982           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8983           return false;
8984         }
8985         // For memmove and friends, copy backwards.
8986         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8987             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8988           return false;
8989         Direction = -1;
8990       } else if (!Move && SrcOffset >= DestOffset &&
8991                  SrcOffset - DestOffset < NBytes) {
8992         // Src is inside the destination region for memcpy: invalid.
8993         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8994         return false;
8995       }
8996     }
8997 
8998     while (true) {
8999       APValue Val;
9000       // FIXME: Set WantObjectRepresentation to true if we're copying a
9001       // char-like type?
9002       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9003           !handleAssignment(Info, E, Dest, T, Val))
9004         return false;
9005       // Do not iterate past the last element; if we're copying backwards, that
9006       // might take us off the start of the array.
9007       if (--NElems == 0)
9008         return true;
9009       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9010           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9011         return false;
9012     }
9013   }
9014 
9015   default:
9016     break;
9017   }
9018 
9019   return visitNonBuiltinCallExpr(E);
9020 }
9021 
9022 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9023                                      APValue &Result, const InitListExpr *ILE,
9024                                      QualType AllocType);
9025 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9026                                           APValue &Result,
9027                                           const CXXConstructExpr *CCE,
9028                                           QualType AllocType);
9029 
9030 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9031   if (!Info.getLangOpts().CPlusPlus20)
9032     Info.CCEDiag(E, diag::note_constexpr_new);
9033 
9034   // We cannot speculatively evaluate a delete expression.
9035   if (Info.SpeculativeEvaluationDepth)
9036     return false;
9037 
9038   FunctionDecl *OperatorNew = E->getOperatorNew();
9039 
9040   bool IsNothrow = false;
9041   bool IsPlacement = false;
9042   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9043       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9044     // FIXME Support array placement new.
9045     assert(E->getNumPlacementArgs() == 1);
9046     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9047       return false;
9048     if (Result.Designator.Invalid)
9049       return false;
9050     IsPlacement = true;
9051   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9052     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9053         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9054     return false;
9055   } else if (E->getNumPlacementArgs()) {
9056     // The only new-placement list we support is of the form (std::nothrow).
9057     //
9058     // FIXME: There is no restriction on this, but it's not clear that any
9059     // other form makes any sense. We get here for cases such as:
9060     //
9061     //   new (std::align_val_t{N}) X(int)
9062     //
9063     // (which should presumably be valid only if N is a multiple of
9064     // alignof(int), and in any case can't be deallocated unless N is
9065     // alignof(X) and X has new-extended alignment).
9066     if (E->getNumPlacementArgs() != 1 ||
9067         !E->getPlacementArg(0)->getType()->isNothrowT())
9068       return Error(E, diag::note_constexpr_new_placement);
9069 
9070     LValue Nothrow;
9071     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9072       return false;
9073     IsNothrow = true;
9074   }
9075 
9076   const Expr *Init = E->getInitializer();
9077   const InitListExpr *ResizedArrayILE = nullptr;
9078   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9079   bool ValueInit = false;
9080 
9081   QualType AllocType = E->getAllocatedType();
9082   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9083     const Expr *Stripped = *ArraySize;
9084     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9085          Stripped = ICE->getSubExpr())
9086       if (ICE->getCastKind() != CK_NoOp &&
9087           ICE->getCastKind() != CK_IntegralCast)
9088         break;
9089 
9090     llvm::APSInt ArrayBound;
9091     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9092       return false;
9093 
9094     // C++ [expr.new]p9:
9095     //   The expression is erroneous if:
9096     //   -- [...] its value before converting to size_t [or] applying the
9097     //      second standard conversion sequence is less than zero
9098     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9099       if (IsNothrow)
9100         return ZeroInitialization(E);
9101 
9102       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9103           << ArrayBound << (*ArraySize)->getSourceRange();
9104       return false;
9105     }
9106 
9107     //   -- its value is such that the size of the allocated object would
9108     //      exceed the implementation-defined limit
9109     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9110                                                 ArrayBound) >
9111         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9112       if (IsNothrow)
9113         return ZeroInitialization(E);
9114 
9115       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9116         << ArrayBound << (*ArraySize)->getSourceRange();
9117       return false;
9118     }
9119 
9120     //   -- the new-initializer is a braced-init-list and the number of
9121     //      array elements for which initializers are provided [...]
9122     //      exceeds the number of elements to initialize
9123     if (!Init) {
9124       // No initialization is performed.
9125     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9126                isa<ImplicitValueInitExpr>(Init)) {
9127       ValueInit = true;
9128     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9129       ResizedArrayCCE = CCE;
9130     } else {
9131       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9132       assert(CAT && "unexpected type for array initializer");
9133 
9134       unsigned Bits =
9135           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9136       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9137       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9138       if (InitBound.ugt(AllocBound)) {
9139         if (IsNothrow)
9140           return ZeroInitialization(E);
9141 
9142         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9143             << AllocBound.toString(10, /*Signed=*/false)
9144             << InitBound.toString(10, /*Signed=*/false)
9145             << (*ArraySize)->getSourceRange();
9146         return false;
9147       }
9148 
9149       // If the sizes differ, we must have an initializer list, and we need
9150       // special handling for this case when we initialize.
9151       if (InitBound != AllocBound)
9152         ResizedArrayILE = cast<InitListExpr>(Init);
9153     }
9154 
9155     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9156                                               ArrayType::Normal, 0);
9157   } else {
9158     assert(!AllocType->isArrayType() &&
9159            "array allocation with non-array new");
9160   }
9161 
9162   APValue *Val;
9163   if (IsPlacement) {
9164     AccessKinds AK = AK_Construct;
9165     struct FindObjectHandler {
9166       EvalInfo &Info;
9167       const Expr *E;
9168       QualType AllocType;
9169       const AccessKinds AccessKind;
9170       APValue *Value;
9171 
9172       typedef bool result_type;
9173       bool failed() { return false; }
9174       bool found(APValue &Subobj, QualType SubobjType) {
9175         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9176         // old name of the object to be used to name the new object.
9177         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9178           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9179             SubobjType << AllocType;
9180           return false;
9181         }
9182         Value = &Subobj;
9183         return true;
9184       }
9185       bool found(APSInt &Value, QualType SubobjType) {
9186         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9187         return false;
9188       }
9189       bool found(APFloat &Value, QualType SubobjType) {
9190         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9191         return false;
9192       }
9193     } Handler = {Info, E, AllocType, AK, nullptr};
9194 
9195     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9196     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9197       return false;
9198 
9199     Val = Handler.Value;
9200 
9201     // [basic.life]p1:
9202     //   The lifetime of an object o of type T ends when [...] the storage
9203     //   which the object occupies is [...] reused by an object that is not
9204     //   nested within o (6.6.2).
9205     *Val = APValue();
9206   } else {
9207     // Perform the allocation and obtain a pointer to the resulting object.
9208     Val = Info.createHeapAlloc(E, AllocType, Result);
9209     if (!Val)
9210       return false;
9211   }
9212 
9213   if (ValueInit) {
9214     ImplicitValueInitExpr VIE(AllocType);
9215     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9216       return false;
9217   } else if (ResizedArrayILE) {
9218     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9219                                   AllocType))
9220       return false;
9221   } else if (ResizedArrayCCE) {
9222     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9223                                        AllocType))
9224       return false;
9225   } else if (Init) {
9226     if (!EvaluateInPlace(*Val, Info, Result, Init))
9227       return false;
9228   } else if (!getDefaultInitValue(AllocType, *Val)) {
9229     return false;
9230   }
9231 
9232   // Array new returns a pointer to the first element, not a pointer to the
9233   // array.
9234   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9235     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9236 
9237   return true;
9238 }
9239 //===----------------------------------------------------------------------===//
9240 // Member Pointer Evaluation
9241 //===----------------------------------------------------------------------===//
9242 
9243 namespace {
9244 class MemberPointerExprEvaluator
9245   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9246   MemberPtr &Result;
9247 
9248   bool Success(const ValueDecl *D) {
9249     Result = MemberPtr(D);
9250     return true;
9251   }
9252 public:
9253 
9254   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9255     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9256 
9257   bool Success(const APValue &V, const Expr *E) {
9258     Result.setFrom(V);
9259     return true;
9260   }
9261   bool ZeroInitialization(const Expr *E) {
9262     return Success((const ValueDecl*)nullptr);
9263   }
9264 
9265   bool VisitCastExpr(const CastExpr *E);
9266   bool VisitUnaryAddrOf(const UnaryOperator *E);
9267 };
9268 } // end anonymous namespace
9269 
9270 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9271                                   EvalInfo &Info) {
9272   assert(E->isRValue() && E->getType()->isMemberPointerType());
9273   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9274 }
9275 
9276 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9277   switch (E->getCastKind()) {
9278   default:
9279     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9280 
9281   case CK_NullToMemberPointer:
9282     VisitIgnoredValue(E->getSubExpr());
9283     return ZeroInitialization(E);
9284 
9285   case CK_BaseToDerivedMemberPointer: {
9286     if (!Visit(E->getSubExpr()))
9287       return false;
9288     if (E->path_empty())
9289       return true;
9290     // Base-to-derived member pointer casts store the path in derived-to-base
9291     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9292     // the wrong end of the derived->base arc, so stagger the path by one class.
9293     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9294     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9295          PathI != PathE; ++PathI) {
9296       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9297       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9298       if (!Result.castToDerived(Derived))
9299         return Error(E);
9300     }
9301     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9302     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9303       return Error(E);
9304     return true;
9305   }
9306 
9307   case CK_DerivedToBaseMemberPointer:
9308     if (!Visit(E->getSubExpr()))
9309       return false;
9310     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9311          PathE = E->path_end(); PathI != PathE; ++PathI) {
9312       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9313       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9314       if (!Result.castToBase(Base))
9315         return Error(E);
9316     }
9317     return true;
9318   }
9319 }
9320 
9321 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9322   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9323   // member can be formed.
9324   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9325 }
9326 
9327 //===----------------------------------------------------------------------===//
9328 // Record Evaluation
9329 //===----------------------------------------------------------------------===//
9330 
9331 namespace {
9332   class RecordExprEvaluator
9333   : public ExprEvaluatorBase<RecordExprEvaluator> {
9334     const LValue &This;
9335     APValue &Result;
9336   public:
9337 
9338     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9339       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9340 
9341     bool Success(const APValue &V, const Expr *E) {
9342       Result = V;
9343       return true;
9344     }
9345     bool ZeroInitialization(const Expr *E) {
9346       return ZeroInitialization(E, E->getType());
9347     }
9348     bool ZeroInitialization(const Expr *E, QualType T);
9349 
9350     bool VisitCallExpr(const CallExpr *E) {
9351       return handleCallExpr(E, Result, &This);
9352     }
9353     bool VisitCastExpr(const CastExpr *E);
9354     bool VisitInitListExpr(const InitListExpr *E);
9355     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9356       return VisitCXXConstructExpr(E, E->getType());
9357     }
9358     bool VisitLambdaExpr(const LambdaExpr *E);
9359     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9360     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9361     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9362     bool VisitBinCmp(const BinaryOperator *E);
9363   };
9364 }
9365 
9366 /// Perform zero-initialization on an object of non-union class type.
9367 /// C++11 [dcl.init]p5:
9368 ///  To zero-initialize an object or reference of type T means:
9369 ///    [...]
9370 ///    -- if T is a (possibly cv-qualified) non-union class type,
9371 ///       each non-static data member and each base-class subobject is
9372 ///       zero-initialized
9373 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9374                                           const RecordDecl *RD,
9375                                           const LValue &This, APValue &Result) {
9376   assert(!RD->isUnion() && "Expected non-union class type");
9377   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9378   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9379                    std::distance(RD->field_begin(), RD->field_end()));
9380 
9381   if (RD->isInvalidDecl()) return false;
9382   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9383 
9384   if (CD) {
9385     unsigned Index = 0;
9386     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9387            End = CD->bases_end(); I != End; ++I, ++Index) {
9388       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9389       LValue Subobject = This;
9390       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9391         return false;
9392       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9393                                          Result.getStructBase(Index)))
9394         return false;
9395     }
9396   }
9397 
9398   for (const auto *I : RD->fields()) {
9399     // -- if T is a reference type, no initialization is performed.
9400     if (I->getType()->isReferenceType())
9401       continue;
9402 
9403     LValue Subobject = This;
9404     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9405       return false;
9406 
9407     ImplicitValueInitExpr VIE(I->getType());
9408     if (!EvaluateInPlace(
9409           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9410       return false;
9411   }
9412 
9413   return true;
9414 }
9415 
9416 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9417   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9418   if (RD->isInvalidDecl()) return false;
9419   if (RD->isUnion()) {
9420     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9421     // object's first non-static named data member is zero-initialized
9422     RecordDecl::field_iterator I = RD->field_begin();
9423     if (I == RD->field_end()) {
9424       Result = APValue((const FieldDecl*)nullptr);
9425       return true;
9426     }
9427 
9428     LValue Subobject = This;
9429     if (!HandleLValueMember(Info, E, Subobject, *I))
9430       return false;
9431     Result = APValue(*I);
9432     ImplicitValueInitExpr VIE(I->getType());
9433     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9434   }
9435 
9436   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9437     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9438     return false;
9439   }
9440 
9441   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9442 }
9443 
9444 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9445   switch (E->getCastKind()) {
9446   default:
9447     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9448 
9449   case CK_ConstructorConversion:
9450     return Visit(E->getSubExpr());
9451 
9452   case CK_DerivedToBase:
9453   case CK_UncheckedDerivedToBase: {
9454     APValue DerivedObject;
9455     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9456       return false;
9457     if (!DerivedObject.isStruct())
9458       return Error(E->getSubExpr());
9459 
9460     // Derived-to-base rvalue conversion: just slice off the derived part.
9461     APValue *Value = &DerivedObject;
9462     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9463     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9464          PathE = E->path_end(); PathI != PathE; ++PathI) {
9465       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9466       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9467       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9468       RD = Base;
9469     }
9470     Result = *Value;
9471     return true;
9472   }
9473   }
9474 }
9475 
9476 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9477   if (E->isTransparent())
9478     return Visit(E->getInit(0));
9479 
9480   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9481   if (RD->isInvalidDecl()) return false;
9482   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9483   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9484 
9485   EvalInfo::EvaluatingConstructorRAII EvalObj(
9486       Info,
9487       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9488       CXXRD && CXXRD->getNumBases());
9489 
9490   if (RD->isUnion()) {
9491     const FieldDecl *Field = E->getInitializedFieldInUnion();
9492     Result = APValue(Field);
9493     if (!Field)
9494       return true;
9495 
9496     // If the initializer list for a union does not contain any elements, the
9497     // first element of the union is value-initialized.
9498     // FIXME: The element should be initialized from an initializer list.
9499     //        Is this difference ever observable for initializer lists which
9500     //        we don't build?
9501     ImplicitValueInitExpr VIE(Field->getType());
9502     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9503 
9504     LValue Subobject = This;
9505     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9506       return false;
9507 
9508     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9509     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9510                                   isa<CXXDefaultInitExpr>(InitExpr));
9511 
9512     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9513   }
9514 
9515   if (!Result.hasValue())
9516     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9517                      std::distance(RD->field_begin(), RD->field_end()));
9518   unsigned ElementNo = 0;
9519   bool Success = true;
9520 
9521   // Initialize base classes.
9522   if (CXXRD && CXXRD->getNumBases()) {
9523     for (const auto &Base : CXXRD->bases()) {
9524       assert(ElementNo < E->getNumInits() && "missing init for base class");
9525       const Expr *Init = E->getInit(ElementNo);
9526 
9527       LValue Subobject = This;
9528       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9529         return false;
9530 
9531       APValue &FieldVal = Result.getStructBase(ElementNo);
9532       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9533         if (!Info.noteFailure())
9534           return false;
9535         Success = false;
9536       }
9537       ++ElementNo;
9538     }
9539 
9540     EvalObj.finishedConstructingBases();
9541   }
9542 
9543   // Initialize members.
9544   for (const auto *Field : RD->fields()) {
9545     // Anonymous bit-fields are not considered members of the class for
9546     // purposes of aggregate initialization.
9547     if (Field->isUnnamedBitfield())
9548       continue;
9549 
9550     LValue Subobject = This;
9551 
9552     bool HaveInit = ElementNo < E->getNumInits();
9553 
9554     // FIXME: Diagnostics here should point to the end of the initializer
9555     // list, not the start.
9556     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9557                             Subobject, Field, &Layout))
9558       return false;
9559 
9560     // Perform an implicit value-initialization for members beyond the end of
9561     // the initializer list.
9562     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9563     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9564 
9565     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9566     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9567                                   isa<CXXDefaultInitExpr>(Init));
9568 
9569     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9570     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9571         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9572                                                        FieldVal, Field))) {
9573       if (!Info.noteFailure())
9574         return false;
9575       Success = false;
9576     }
9577   }
9578 
9579   EvalObj.finishedConstructingFields();
9580 
9581   return Success;
9582 }
9583 
9584 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9585                                                 QualType T) {
9586   // Note that E's type is not necessarily the type of our class here; we might
9587   // be initializing an array element instead.
9588   const CXXConstructorDecl *FD = E->getConstructor();
9589   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9590 
9591   bool ZeroInit = E->requiresZeroInitialization();
9592   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9593     // If we've already performed zero-initialization, we're already done.
9594     if (Result.hasValue())
9595       return true;
9596 
9597     if (ZeroInit)
9598       return ZeroInitialization(E, T);
9599 
9600     return getDefaultInitValue(T, Result);
9601   }
9602 
9603   const FunctionDecl *Definition = nullptr;
9604   auto Body = FD->getBody(Definition);
9605 
9606   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9607     return false;
9608 
9609   // Avoid materializing a temporary for an elidable copy/move constructor.
9610   if (E->isElidable() && !ZeroInit)
9611     if (const MaterializeTemporaryExpr *ME
9612           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9613       return Visit(ME->getSubExpr());
9614 
9615   if (ZeroInit && !ZeroInitialization(E, T))
9616     return false;
9617 
9618   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9619   return HandleConstructorCall(E, This, Args,
9620                                cast<CXXConstructorDecl>(Definition), Info,
9621                                Result);
9622 }
9623 
9624 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9625     const CXXInheritedCtorInitExpr *E) {
9626   if (!Info.CurrentCall) {
9627     assert(Info.checkingPotentialConstantExpression());
9628     return false;
9629   }
9630 
9631   const CXXConstructorDecl *FD = E->getConstructor();
9632   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9633     return false;
9634 
9635   const FunctionDecl *Definition = nullptr;
9636   auto Body = FD->getBody(Definition);
9637 
9638   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9639     return false;
9640 
9641   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9642                                cast<CXXConstructorDecl>(Definition), Info,
9643                                Result);
9644 }
9645 
9646 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9647     const CXXStdInitializerListExpr *E) {
9648   const ConstantArrayType *ArrayType =
9649       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9650 
9651   LValue Array;
9652   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9653     return false;
9654 
9655   // Get a pointer to the first element of the array.
9656   Array.addArray(Info, E, ArrayType);
9657 
9658   auto InvalidType = [&] {
9659     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9660       << E->getType();
9661     return false;
9662   };
9663 
9664   // FIXME: Perform the checks on the field types in SemaInit.
9665   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9666   RecordDecl::field_iterator Field = Record->field_begin();
9667   if (Field == Record->field_end())
9668     return InvalidType();
9669 
9670   // Start pointer.
9671   if (!Field->getType()->isPointerType() ||
9672       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9673                             ArrayType->getElementType()))
9674     return InvalidType();
9675 
9676   // FIXME: What if the initializer_list type has base classes, etc?
9677   Result = APValue(APValue::UninitStruct(), 0, 2);
9678   Array.moveInto(Result.getStructField(0));
9679 
9680   if (++Field == Record->field_end())
9681     return InvalidType();
9682 
9683   if (Field->getType()->isPointerType() &&
9684       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9685                            ArrayType->getElementType())) {
9686     // End pointer.
9687     if (!HandleLValueArrayAdjustment(Info, E, Array,
9688                                      ArrayType->getElementType(),
9689                                      ArrayType->getSize().getZExtValue()))
9690       return false;
9691     Array.moveInto(Result.getStructField(1));
9692   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9693     // Length.
9694     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9695   else
9696     return InvalidType();
9697 
9698   if (++Field != Record->field_end())
9699     return InvalidType();
9700 
9701   return true;
9702 }
9703 
9704 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9705   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9706   if (ClosureClass->isInvalidDecl())
9707     return false;
9708 
9709   const size_t NumFields =
9710       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9711 
9712   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9713                                             E->capture_init_end()) &&
9714          "The number of lambda capture initializers should equal the number of "
9715          "fields within the closure type");
9716 
9717   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9718   // Iterate through all the lambda's closure object's fields and initialize
9719   // them.
9720   auto *CaptureInitIt = E->capture_init_begin();
9721   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9722   bool Success = true;
9723   for (const auto *Field : ClosureClass->fields()) {
9724     assert(CaptureInitIt != E->capture_init_end());
9725     // Get the initializer for this field
9726     Expr *const CurFieldInit = *CaptureInitIt++;
9727 
9728     // If there is no initializer, either this is a VLA or an error has
9729     // occurred.
9730     if (!CurFieldInit)
9731       return Error(E);
9732 
9733     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9734     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9735       if (!Info.keepEvaluatingAfterFailure())
9736         return false;
9737       Success = false;
9738     }
9739     ++CaptureIt;
9740   }
9741   return Success;
9742 }
9743 
9744 static bool EvaluateRecord(const Expr *E, const LValue &This,
9745                            APValue &Result, EvalInfo &Info) {
9746   assert(E->isRValue() && E->getType()->isRecordType() &&
9747          "can't evaluate expression as a record rvalue");
9748   return RecordExprEvaluator(Info, This, Result).Visit(E);
9749 }
9750 
9751 //===----------------------------------------------------------------------===//
9752 // Temporary Evaluation
9753 //
9754 // Temporaries are represented in the AST as rvalues, but generally behave like
9755 // lvalues. The full-object of which the temporary is a subobject is implicitly
9756 // materialized so that a reference can bind to it.
9757 //===----------------------------------------------------------------------===//
9758 namespace {
9759 class TemporaryExprEvaluator
9760   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9761 public:
9762   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9763     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9764 
9765   /// Visit an expression which constructs the value of this temporary.
9766   bool VisitConstructExpr(const Expr *E) {
9767     APValue &Value =
9768         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9769     return EvaluateInPlace(Value, Info, Result, E);
9770   }
9771 
9772   bool VisitCastExpr(const CastExpr *E) {
9773     switch (E->getCastKind()) {
9774     default:
9775       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9776 
9777     case CK_ConstructorConversion:
9778       return VisitConstructExpr(E->getSubExpr());
9779     }
9780   }
9781   bool VisitInitListExpr(const InitListExpr *E) {
9782     return VisitConstructExpr(E);
9783   }
9784   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9785     return VisitConstructExpr(E);
9786   }
9787   bool VisitCallExpr(const CallExpr *E) {
9788     return VisitConstructExpr(E);
9789   }
9790   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9791     return VisitConstructExpr(E);
9792   }
9793   bool VisitLambdaExpr(const LambdaExpr *E) {
9794     return VisitConstructExpr(E);
9795   }
9796 };
9797 } // end anonymous namespace
9798 
9799 /// Evaluate an expression of record type as a temporary.
9800 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9801   assert(E->isRValue() && E->getType()->isRecordType());
9802   return TemporaryExprEvaluator(Info, Result).Visit(E);
9803 }
9804 
9805 //===----------------------------------------------------------------------===//
9806 // Vector Evaluation
9807 //===----------------------------------------------------------------------===//
9808 
9809 namespace {
9810   class VectorExprEvaluator
9811   : public ExprEvaluatorBase<VectorExprEvaluator> {
9812     APValue &Result;
9813   public:
9814 
9815     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9816       : ExprEvaluatorBaseTy(info), Result(Result) {}
9817 
9818     bool Success(ArrayRef<APValue> V, const Expr *E) {
9819       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9820       // FIXME: remove this APValue copy.
9821       Result = APValue(V.data(), V.size());
9822       return true;
9823     }
9824     bool Success(const APValue &V, const Expr *E) {
9825       assert(V.isVector());
9826       Result = V;
9827       return true;
9828     }
9829     bool ZeroInitialization(const Expr *E);
9830 
9831     bool VisitUnaryReal(const UnaryOperator *E)
9832       { return Visit(E->getSubExpr()); }
9833     bool VisitCastExpr(const CastExpr* E);
9834     bool VisitInitListExpr(const InitListExpr *E);
9835     bool VisitUnaryImag(const UnaryOperator *E);
9836     bool VisitBinaryOperator(const BinaryOperator *E);
9837     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
9838     //                 conditional select), shufflevector, ExtVectorElementExpr
9839   };
9840 } // end anonymous namespace
9841 
9842 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9843   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9844   return VectorExprEvaluator(Info, Result).Visit(E);
9845 }
9846 
9847 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9848   const VectorType *VTy = E->getType()->castAs<VectorType>();
9849   unsigned NElts = VTy->getNumElements();
9850 
9851   const Expr *SE = E->getSubExpr();
9852   QualType SETy = SE->getType();
9853 
9854   switch (E->getCastKind()) {
9855   case CK_VectorSplat: {
9856     APValue Val = APValue();
9857     if (SETy->isIntegerType()) {
9858       APSInt IntResult;
9859       if (!EvaluateInteger(SE, IntResult, Info))
9860         return false;
9861       Val = APValue(std::move(IntResult));
9862     } else if (SETy->isRealFloatingType()) {
9863       APFloat FloatResult(0.0);
9864       if (!EvaluateFloat(SE, FloatResult, Info))
9865         return false;
9866       Val = APValue(std::move(FloatResult));
9867     } else {
9868       return Error(E);
9869     }
9870 
9871     // Splat and create vector APValue.
9872     SmallVector<APValue, 4> Elts(NElts, Val);
9873     return Success(Elts, E);
9874   }
9875   case CK_BitCast: {
9876     // Evaluate the operand into an APInt we can extract from.
9877     llvm::APInt SValInt;
9878     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9879       return false;
9880     // Extract the elements
9881     QualType EltTy = VTy->getElementType();
9882     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9883     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9884     SmallVector<APValue, 4> Elts;
9885     if (EltTy->isRealFloatingType()) {
9886       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9887       unsigned FloatEltSize = EltSize;
9888       if (&Sem == &APFloat::x87DoubleExtended())
9889         FloatEltSize = 80;
9890       for (unsigned i = 0; i < NElts; i++) {
9891         llvm::APInt Elt;
9892         if (BigEndian)
9893           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9894         else
9895           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9896         Elts.push_back(APValue(APFloat(Sem, Elt)));
9897       }
9898     } else if (EltTy->isIntegerType()) {
9899       for (unsigned i = 0; i < NElts; i++) {
9900         llvm::APInt Elt;
9901         if (BigEndian)
9902           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9903         else
9904           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9905         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9906       }
9907     } else {
9908       return Error(E);
9909     }
9910     return Success(Elts, E);
9911   }
9912   default:
9913     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9914   }
9915 }
9916 
9917 bool
9918 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9919   const VectorType *VT = E->getType()->castAs<VectorType>();
9920   unsigned NumInits = E->getNumInits();
9921   unsigned NumElements = VT->getNumElements();
9922 
9923   QualType EltTy = VT->getElementType();
9924   SmallVector<APValue, 4> Elements;
9925 
9926   // The number of initializers can be less than the number of
9927   // vector elements. For OpenCL, this can be due to nested vector
9928   // initialization. For GCC compatibility, missing trailing elements
9929   // should be initialized with zeroes.
9930   unsigned CountInits = 0, CountElts = 0;
9931   while (CountElts < NumElements) {
9932     // Handle nested vector initialization.
9933     if (CountInits < NumInits
9934         && E->getInit(CountInits)->getType()->isVectorType()) {
9935       APValue v;
9936       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9937         return Error(E);
9938       unsigned vlen = v.getVectorLength();
9939       for (unsigned j = 0; j < vlen; j++)
9940         Elements.push_back(v.getVectorElt(j));
9941       CountElts += vlen;
9942     } else if (EltTy->isIntegerType()) {
9943       llvm::APSInt sInt(32);
9944       if (CountInits < NumInits) {
9945         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9946           return false;
9947       } else // trailing integer zero.
9948         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9949       Elements.push_back(APValue(sInt));
9950       CountElts++;
9951     } else {
9952       llvm::APFloat f(0.0);
9953       if (CountInits < NumInits) {
9954         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9955           return false;
9956       } else // trailing float zero.
9957         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9958       Elements.push_back(APValue(f));
9959       CountElts++;
9960     }
9961     CountInits++;
9962   }
9963   return Success(Elements, E);
9964 }
9965 
9966 bool
9967 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9968   const auto *VT = E->getType()->castAs<VectorType>();
9969   QualType EltTy = VT->getElementType();
9970   APValue ZeroElement;
9971   if (EltTy->isIntegerType())
9972     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9973   else
9974     ZeroElement =
9975         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9976 
9977   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9978   return Success(Elements, E);
9979 }
9980 
9981 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9982   VisitIgnoredValue(E->getSubExpr());
9983   return ZeroInitialization(E);
9984 }
9985 
9986 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9987   BinaryOperatorKind Op = E->getOpcode();
9988   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
9989          "Operation not supported on vector types");
9990 
9991   if (Op == BO_Comma)
9992     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9993 
9994   Expr *LHS = E->getLHS();
9995   Expr *RHS = E->getRHS();
9996 
9997   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
9998          "Must both be vector types");
9999   // Checking JUST the types are the same would be fine, except shifts don't
10000   // need to have their types be the same (since you always shift by an int).
10001   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10002              E->getType()->getAs<VectorType>()->getNumElements() &&
10003          RHS->getType()->getAs<VectorType>()->getNumElements() ==
10004              E->getType()->getAs<VectorType>()->getNumElements() &&
10005          "All operands must be the same size.");
10006 
10007   APValue LHSValue;
10008   APValue RHSValue;
10009   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10010   if (!LHSOK && !Info.noteFailure())
10011     return false;
10012   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10013     return false;
10014 
10015   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10016     return false;
10017 
10018   return Success(LHSValue, E);
10019 }
10020 
10021 //===----------------------------------------------------------------------===//
10022 // Array Evaluation
10023 //===----------------------------------------------------------------------===//
10024 
10025 namespace {
10026   class ArrayExprEvaluator
10027   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10028     const LValue &This;
10029     APValue &Result;
10030   public:
10031 
10032     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10033       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10034 
10035     bool Success(const APValue &V, const Expr *E) {
10036       assert(V.isArray() && "expected array");
10037       Result = V;
10038       return true;
10039     }
10040 
10041     bool ZeroInitialization(const Expr *E) {
10042       const ConstantArrayType *CAT =
10043           Info.Ctx.getAsConstantArrayType(E->getType());
10044       if (!CAT) {
10045         if (E->getType()->isIncompleteArrayType()) {
10046           // We can be asked to zero-initialize a flexible array member; this
10047           // is represented as an ImplicitValueInitExpr of incomplete array
10048           // type. In this case, the array has zero elements.
10049           Result = APValue(APValue::UninitArray(), 0, 0);
10050           return true;
10051         }
10052         // FIXME: We could handle VLAs here.
10053         return Error(E);
10054       }
10055 
10056       Result = APValue(APValue::UninitArray(), 0,
10057                        CAT->getSize().getZExtValue());
10058       if (!Result.hasArrayFiller()) return true;
10059 
10060       // Zero-initialize all elements.
10061       LValue Subobject = This;
10062       Subobject.addArray(Info, E, CAT);
10063       ImplicitValueInitExpr VIE(CAT->getElementType());
10064       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10065     }
10066 
10067     bool VisitCallExpr(const CallExpr *E) {
10068       return handleCallExpr(E, Result, &This);
10069     }
10070     bool VisitInitListExpr(const InitListExpr *E,
10071                            QualType AllocType = QualType());
10072     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10073     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10074     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10075                                const LValue &Subobject,
10076                                APValue *Value, QualType Type);
10077     bool VisitStringLiteral(const StringLiteral *E,
10078                             QualType AllocType = QualType()) {
10079       expandStringLiteral(Info, E, Result, AllocType);
10080       return true;
10081     }
10082   };
10083 } // end anonymous namespace
10084 
10085 static bool EvaluateArray(const Expr *E, const LValue &This,
10086                           APValue &Result, EvalInfo &Info) {
10087   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10088   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10089 }
10090 
10091 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10092                                      APValue &Result, const InitListExpr *ILE,
10093                                      QualType AllocType) {
10094   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10095          "not an array rvalue");
10096   return ArrayExprEvaluator(Info, This, Result)
10097       .VisitInitListExpr(ILE, AllocType);
10098 }
10099 
10100 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10101                                           APValue &Result,
10102                                           const CXXConstructExpr *CCE,
10103                                           QualType AllocType) {
10104   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10105          "not an array rvalue");
10106   return ArrayExprEvaluator(Info, This, Result)
10107       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10108 }
10109 
10110 // Return true iff the given array filler may depend on the element index.
10111 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10112   // For now, just allow non-class value-initialization and initialization
10113   // lists comprised of them.
10114   if (isa<ImplicitValueInitExpr>(FillerExpr))
10115     return false;
10116   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10117     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10118       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10119         return true;
10120     }
10121     return false;
10122   }
10123   return true;
10124 }
10125 
10126 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10127                                            QualType AllocType) {
10128   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10129       AllocType.isNull() ? E->getType() : AllocType);
10130   if (!CAT)
10131     return Error(E);
10132 
10133   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10134   // an appropriately-typed string literal enclosed in braces.
10135   if (E->isStringLiteralInit()) {
10136     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10137     // FIXME: Support ObjCEncodeExpr here once we support it in
10138     // ArrayExprEvaluator generally.
10139     if (!SL)
10140       return Error(E);
10141     return VisitStringLiteral(SL, AllocType);
10142   }
10143 
10144   bool Success = true;
10145 
10146   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10147          "zero-initialized array shouldn't have any initialized elts");
10148   APValue Filler;
10149   if (Result.isArray() && Result.hasArrayFiller())
10150     Filler = Result.getArrayFiller();
10151 
10152   unsigned NumEltsToInit = E->getNumInits();
10153   unsigned NumElts = CAT->getSize().getZExtValue();
10154   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10155 
10156   // If the initializer might depend on the array index, run it for each
10157   // array element.
10158   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10159     NumEltsToInit = NumElts;
10160 
10161   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10162                           << NumEltsToInit << ".\n");
10163 
10164   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10165 
10166   // If the array was previously zero-initialized, preserve the
10167   // zero-initialized values.
10168   if (Filler.hasValue()) {
10169     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10170       Result.getArrayInitializedElt(I) = Filler;
10171     if (Result.hasArrayFiller())
10172       Result.getArrayFiller() = Filler;
10173   }
10174 
10175   LValue Subobject = This;
10176   Subobject.addArray(Info, E, CAT);
10177   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10178     const Expr *Init =
10179         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10180     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10181                          Info, Subobject, Init) ||
10182         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10183                                      CAT->getElementType(), 1)) {
10184       if (!Info.noteFailure())
10185         return false;
10186       Success = false;
10187     }
10188   }
10189 
10190   if (!Result.hasArrayFiller())
10191     return Success;
10192 
10193   // If we get here, we have a trivial filler, which we can just evaluate
10194   // once and splat over the rest of the array elements.
10195   assert(FillerExpr && "no array filler for incomplete init list");
10196   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10197                          FillerExpr) && Success;
10198 }
10199 
10200 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10201   LValue CommonLV;
10202   if (E->getCommonExpr() &&
10203       !Evaluate(Info.CurrentCall->createTemporary(
10204                     E->getCommonExpr(),
10205                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
10206                     CommonLV),
10207                 Info, E->getCommonExpr()->getSourceExpr()))
10208     return false;
10209 
10210   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10211 
10212   uint64_t Elements = CAT->getSize().getZExtValue();
10213   Result = APValue(APValue::UninitArray(), Elements, Elements);
10214 
10215   LValue Subobject = This;
10216   Subobject.addArray(Info, E, CAT);
10217 
10218   bool Success = true;
10219   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10220     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10221                          Info, Subobject, E->getSubExpr()) ||
10222         !HandleLValueArrayAdjustment(Info, E, Subobject,
10223                                      CAT->getElementType(), 1)) {
10224       if (!Info.noteFailure())
10225         return false;
10226       Success = false;
10227     }
10228   }
10229 
10230   return Success;
10231 }
10232 
10233 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10234   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10235 }
10236 
10237 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10238                                                const LValue &Subobject,
10239                                                APValue *Value,
10240                                                QualType Type) {
10241   bool HadZeroInit = Value->hasValue();
10242 
10243   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10244     unsigned N = CAT->getSize().getZExtValue();
10245 
10246     // Preserve the array filler if we had prior zero-initialization.
10247     APValue Filler =
10248       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10249                                              : APValue();
10250 
10251     *Value = APValue(APValue::UninitArray(), N, N);
10252 
10253     if (HadZeroInit)
10254       for (unsigned I = 0; I != N; ++I)
10255         Value->getArrayInitializedElt(I) = Filler;
10256 
10257     // Initialize the elements.
10258     LValue ArrayElt = Subobject;
10259     ArrayElt.addArray(Info, E, CAT);
10260     for (unsigned I = 0; I != N; ++I)
10261       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10262                                  CAT->getElementType()) ||
10263           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10264                                        CAT->getElementType(), 1))
10265         return false;
10266 
10267     return true;
10268   }
10269 
10270   if (!Type->isRecordType())
10271     return Error(E);
10272 
10273   return RecordExprEvaluator(Info, Subobject, *Value)
10274              .VisitCXXConstructExpr(E, Type);
10275 }
10276 
10277 //===----------------------------------------------------------------------===//
10278 // Integer Evaluation
10279 //
10280 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10281 // types and back in constant folding. Integer values are thus represented
10282 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10283 //===----------------------------------------------------------------------===//
10284 
10285 namespace {
10286 class IntExprEvaluator
10287         : public ExprEvaluatorBase<IntExprEvaluator> {
10288   APValue &Result;
10289 public:
10290   IntExprEvaluator(EvalInfo &info, APValue &result)
10291       : ExprEvaluatorBaseTy(info), Result(result) {}
10292 
10293   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10294     assert(E->getType()->isIntegralOrEnumerationType() &&
10295            "Invalid evaluation result.");
10296     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10297            "Invalid evaluation result.");
10298     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10299            "Invalid evaluation result.");
10300     Result = APValue(SI);
10301     return true;
10302   }
10303   bool Success(const llvm::APSInt &SI, const Expr *E) {
10304     return Success(SI, E, Result);
10305   }
10306 
10307   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10308     assert(E->getType()->isIntegralOrEnumerationType() &&
10309            "Invalid evaluation result.");
10310     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10311            "Invalid evaluation result.");
10312     Result = APValue(APSInt(I));
10313     Result.getInt().setIsUnsigned(
10314                             E->getType()->isUnsignedIntegerOrEnumerationType());
10315     return true;
10316   }
10317   bool Success(const llvm::APInt &I, const Expr *E) {
10318     return Success(I, E, Result);
10319   }
10320 
10321   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10322     assert(E->getType()->isIntegralOrEnumerationType() &&
10323            "Invalid evaluation result.");
10324     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10325     return true;
10326   }
10327   bool Success(uint64_t Value, const Expr *E) {
10328     return Success(Value, E, Result);
10329   }
10330 
10331   bool Success(CharUnits Size, const Expr *E) {
10332     return Success(Size.getQuantity(), E);
10333   }
10334 
10335   bool Success(const APValue &V, const Expr *E) {
10336     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10337       Result = V;
10338       return true;
10339     }
10340     return Success(V.getInt(), E);
10341   }
10342 
10343   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10344 
10345   //===--------------------------------------------------------------------===//
10346   //                            Visitor Methods
10347   //===--------------------------------------------------------------------===//
10348 
10349   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10350     return Success(E->getValue(), E);
10351   }
10352   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10353     return Success(E->getValue(), E);
10354   }
10355 
10356   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10357   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10358     if (CheckReferencedDecl(E, E->getDecl()))
10359       return true;
10360 
10361     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10362   }
10363   bool VisitMemberExpr(const MemberExpr *E) {
10364     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10365       VisitIgnoredBaseExpression(E->getBase());
10366       return true;
10367     }
10368 
10369     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10370   }
10371 
10372   bool VisitCallExpr(const CallExpr *E);
10373   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10374   bool VisitBinaryOperator(const BinaryOperator *E);
10375   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10376   bool VisitUnaryOperator(const UnaryOperator *E);
10377 
10378   bool VisitCastExpr(const CastExpr* E);
10379   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10380 
10381   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10382     return Success(E->getValue(), E);
10383   }
10384 
10385   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10386     return Success(E->getValue(), E);
10387   }
10388 
10389   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10390     if (Info.ArrayInitIndex == uint64_t(-1)) {
10391       // We were asked to evaluate this subexpression independent of the
10392       // enclosing ArrayInitLoopExpr. We can't do that.
10393       Info.FFDiag(E);
10394       return false;
10395     }
10396     return Success(Info.ArrayInitIndex, E);
10397   }
10398 
10399   // Note, GNU defines __null as an integer, not a pointer.
10400   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10401     return ZeroInitialization(E);
10402   }
10403 
10404   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10405     return Success(E->getValue(), E);
10406   }
10407 
10408   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10409     return Success(E->getValue(), E);
10410   }
10411 
10412   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10413     return Success(E->getValue(), E);
10414   }
10415 
10416   bool VisitUnaryReal(const UnaryOperator *E);
10417   bool VisitUnaryImag(const UnaryOperator *E);
10418 
10419   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10420   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10421   bool VisitSourceLocExpr(const SourceLocExpr *E);
10422   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10423   bool VisitRequiresExpr(const RequiresExpr *E);
10424   // FIXME: Missing: array subscript of vector, member of vector
10425 };
10426 
10427 class FixedPointExprEvaluator
10428     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10429   APValue &Result;
10430 
10431  public:
10432   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10433       : ExprEvaluatorBaseTy(info), Result(result) {}
10434 
10435   bool Success(const llvm::APInt &I, const Expr *E) {
10436     return Success(
10437         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10438   }
10439 
10440   bool Success(uint64_t Value, const Expr *E) {
10441     return Success(
10442         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10443   }
10444 
10445   bool Success(const APValue &V, const Expr *E) {
10446     return Success(V.getFixedPoint(), E);
10447   }
10448 
10449   bool Success(const APFixedPoint &V, const Expr *E) {
10450     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10451     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10452            "Invalid evaluation result.");
10453     Result = APValue(V);
10454     return true;
10455   }
10456 
10457   //===--------------------------------------------------------------------===//
10458   //                            Visitor Methods
10459   //===--------------------------------------------------------------------===//
10460 
10461   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10462     return Success(E->getValue(), E);
10463   }
10464 
10465   bool VisitCastExpr(const CastExpr *E);
10466   bool VisitUnaryOperator(const UnaryOperator *E);
10467   bool VisitBinaryOperator(const BinaryOperator *E);
10468 };
10469 } // end anonymous namespace
10470 
10471 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10472 /// produce either the integer value or a pointer.
10473 ///
10474 /// GCC has a heinous extension which folds casts between pointer types and
10475 /// pointer-sized integral types. We support this by allowing the evaluation of
10476 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10477 /// Some simple arithmetic on such values is supported (they are treated much
10478 /// like char*).
10479 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10480                                     EvalInfo &Info) {
10481   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10482   return IntExprEvaluator(Info, Result).Visit(E);
10483 }
10484 
10485 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10486   APValue Val;
10487   if (!EvaluateIntegerOrLValue(E, Val, Info))
10488     return false;
10489   if (!Val.isInt()) {
10490     // FIXME: It would be better to produce the diagnostic for casting
10491     //        a pointer to an integer.
10492     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10493     return false;
10494   }
10495   Result = Val.getInt();
10496   return true;
10497 }
10498 
10499 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10500   APValue Evaluated = E->EvaluateInContext(
10501       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10502   return Success(Evaluated, E);
10503 }
10504 
10505 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10506                                EvalInfo &Info) {
10507   if (E->getType()->isFixedPointType()) {
10508     APValue Val;
10509     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10510       return false;
10511     if (!Val.isFixedPoint())
10512       return false;
10513 
10514     Result = Val.getFixedPoint();
10515     return true;
10516   }
10517   return false;
10518 }
10519 
10520 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10521                                         EvalInfo &Info) {
10522   if (E->getType()->isIntegerType()) {
10523     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10524     APSInt Val;
10525     if (!EvaluateInteger(E, Val, Info))
10526       return false;
10527     Result = APFixedPoint(Val, FXSema);
10528     return true;
10529   } else if (E->getType()->isFixedPointType()) {
10530     return EvaluateFixedPoint(E, Result, Info);
10531   }
10532   return false;
10533 }
10534 
10535 /// Check whether the given declaration can be directly converted to an integral
10536 /// rvalue. If not, no diagnostic is produced; there are other things we can
10537 /// try.
10538 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10539   // Enums are integer constant exprs.
10540   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10541     // Check for signedness/width mismatches between E type and ECD value.
10542     bool SameSign = (ECD->getInitVal().isSigned()
10543                      == E->getType()->isSignedIntegerOrEnumerationType());
10544     bool SameWidth = (ECD->getInitVal().getBitWidth()
10545                       == Info.Ctx.getIntWidth(E->getType()));
10546     if (SameSign && SameWidth)
10547       return Success(ECD->getInitVal(), E);
10548     else {
10549       // Get rid of mismatch (otherwise Success assertions will fail)
10550       // by computing a new value matching the type of E.
10551       llvm::APSInt Val = ECD->getInitVal();
10552       if (!SameSign)
10553         Val.setIsSigned(!ECD->getInitVal().isSigned());
10554       if (!SameWidth)
10555         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10556       return Success(Val, E);
10557     }
10558   }
10559   return false;
10560 }
10561 
10562 /// Values returned by __builtin_classify_type, chosen to match the values
10563 /// produced by GCC's builtin.
10564 enum class GCCTypeClass {
10565   None = -1,
10566   Void = 0,
10567   Integer = 1,
10568   // GCC reserves 2 for character types, but instead classifies them as
10569   // integers.
10570   Enum = 3,
10571   Bool = 4,
10572   Pointer = 5,
10573   // GCC reserves 6 for references, but appears to never use it (because
10574   // expressions never have reference type, presumably).
10575   PointerToDataMember = 7,
10576   RealFloat = 8,
10577   Complex = 9,
10578   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10579   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10580   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10581   // uses 12 for that purpose, same as for a class or struct. Maybe it
10582   // internally implements a pointer to member as a struct?  Who knows.
10583   PointerToMemberFunction = 12, // Not a bug, see above.
10584   ClassOrStruct = 12,
10585   Union = 13,
10586   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10587   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10588   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10589   // literals.
10590 };
10591 
10592 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10593 /// as GCC.
10594 static GCCTypeClass
10595 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10596   assert(!T->isDependentType() && "unexpected dependent type");
10597 
10598   QualType CanTy = T.getCanonicalType();
10599   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10600 
10601   switch (CanTy->getTypeClass()) {
10602 #define TYPE(ID, BASE)
10603 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10604 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10605 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10606 #include "clang/AST/TypeNodes.inc"
10607   case Type::Auto:
10608   case Type::DeducedTemplateSpecialization:
10609       llvm_unreachable("unexpected non-canonical or dependent type");
10610 
10611   case Type::Builtin:
10612     switch (BT->getKind()) {
10613 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10614 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10615     case BuiltinType::ID: return GCCTypeClass::Integer;
10616 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10617     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10618 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10619     case BuiltinType::ID: break;
10620 #include "clang/AST/BuiltinTypes.def"
10621     case BuiltinType::Void:
10622       return GCCTypeClass::Void;
10623 
10624     case BuiltinType::Bool:
10625       return GCCTypeClass::Bool;
10626 
10627     case BuiltinType::Char_U:
10628     case BuiltinType::UChar:
10629     case BuiltinType::WChar_U:
10630     case BuiltinType::Char8:
10631     case BuiltinType::Char16:
10632     case BuiltinType::Char32:
10633     case BuiltinType::UShort:
10634     case BuiltinType::UInt:
10635     case BuiltinType::ULong:
10636     case BuiltinType::ULongLong:
10637     case BuiltinType::UInt128:
10638       return GCCTypeClass::Integer;
10639 
10640     case BuiltinType::UShortAccum:
10641     case BuiltinType::UAccum:
10642     case BuiltinType::ULongAccum:
10643     case BuiltinType::UShortFract:
10644     case BuiltinType::UFract:
10645     case BuiltinType::ULongFract:
10646     case BuiltinType::SatUShortAccum:
10647     case BuiltinType::SatUAccum:
10648     case BuiltinType::SatULongAccum:
10649     case BuiltinType::SatUShortFract:
10650     case BuiltinType::SatUFract:
10651     case BuiltinType::SatULongFract:
10652       return GCCTypeClass::None;
10653 
10654     case BuiltinType::NullPtr:
10655 
10656     case BuiltinType::ObjCId:
10657     case BuiltinType::ObjCClass:
10658     case BuiltinType::ObjCSel:
10659 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10660     case BuiltinType::Id:
10661 #include "clang/Basic/OpenCLImageTypes.def"
10662 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10663     case BuiltinType::Id:
10664 #include "clang/Basic/OpenCLExtensionTypes.def"
10665     case BuiltinType::OCLSampler:
10666     case BuiltinType::OCLEvent:
10667     case BuiltinType::OCLClkEvent:
10668     case BuiltinType::OCLQueue:
10669     case BuiltinType::OCLReserveID:
10670 #define SVE_TYPE(Name, Id, SingletonId) \
10671     case BuiltinType::Id:
10672 #include "clang/Basic/AArch64SVEACLETypes.def"
10673       return GCCTypeClass::None;
10674 
10675     case BuiltinType::Dependent:
10676       llvm_unreachable("unexpected dependent type");
10677     };
10678     llvm_unreachable("unexpected placeholder type");
10679 
10680   case Type::Enum:
10681     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10682 
10683   case Type::Pointer:
10684   case Type::ConstantArray:
10685   case Type::VariableArray:
10686   case Type::IncompleteArray:
10687   case Type::FunctionNoProto:
10688   case Type::FunctionProto:
10689     return GCCTypeClass::Pointer;
10690 
10691   case Type::MemberPointer:
10692     return CanTy->isMemberDataPointerType()
10693                ? GCCTypeClass::PointerToDataMember
10694                : GCCTypeClass::PointerToMemberFunction;
10695 
10696   case Type::Complex:
10697     return GCCTypeClass::Complex;
10698 
10699   case Type::Record:
10700     return CanTy->isUnionType() ? GCCTypeClass::Union
10701                                 : GCCTypeClass::ClassOrStruct;
10702 
10703   case Type::Atomic:
10704     // GCC classifies _Atomic T the same as T.
10705     return EvaluateBuiltinClassifyType(
10706         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10707 
10708   case Type::BlockPointer:
10709   case Type::Vector:
10710   case Type::ExtVector:
10711   case Type::ConstantMatrix:
10712   case Type::ObjCObject:
10713   case Type::ObjCInterface:
10714   case Type::ObjCObjectPointer:
10715   case Type::Pipe:
10716   case Type::ExtInt:
10717     // GCC classifies vectors as None. We follow its lead and classify all
10718     // other types that don't fit into the regular classification the same way.
10719     return GCCTypeClass::None;
10720 
10721   case Type::LValueReference:
10722   case Type::RValueReference:
10723     llvm_unreachable("invalid type for expression");
10724   }
10725 
10726   llvm_unreachable("unexpected type class");
10727 }
10728 
10729 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10730 /// as GCC.
10731 static GCCTypeClass
10732 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10733   // If no argument was supplied, default to None. This isn't
10734   // ideal, however it is what gcc does.
10735   if (E->getNumArgs() == 0)
10736     return GCCTypeClass::None;
10737 
10738   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10739   // being an ICE, but still folds it to a constant using the type of the first
10740   // argument.
10741   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10742 }
10743 
10744 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10745 /// __builtin_constant_p when applied to the given pointer.
10746 ///
10747 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10748 /// or it points to the first character of a string literal.
10749 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10750   APValue::LValueBase Base = LV.getLValueBase();
10751   if (Base.isNull()) {
10752     // A null base is acceptable.
10753     return true;
10754   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10755     if (!isa<StringLiteral>(E))
10756       return false;
10757     return LV.getLValueOffset().isZero();
10758   } else if (Base.is<TypeInfoLValue>()) {
10759     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10760     // evaluate to true.
10761     return true;
10762   } else {
10763     // Any other base is not constant enough for GCC.
10764     return false;
10765   }
10766 }
10767 
10768 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10769 /// GCC as we can manage.
10770 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10771   // This evaluation is not permitted to have side-effects, so evaluate it in
10772   // a speculative evaluation context.
10773   SpeculativeEvaluationRAII SpeculativeEval(Info);
10774 
10775   // Constant-folding is always enabled for the operand of __builtin_constant_p
10776   // (even when the enclosing evaluation context otherwise requires a strict
10777   // language-specific constant expression).
10778   FoldConstant Fold(Info, true);
10779 
10780   QualType ArgType = Arg->getType();
10781 
10782   // __builtin_constant_p always has one operand. The rules which gcc follows
10783   // are not precisely documented, but are as follows:
10784   //
10785   //  - If the operand is of integral, floating, complex or enumeration type,
10786   //    and can be folded to a known value of that type, it returns 1.
10787   //  - If the operand can be folded to a pointer to the first character
10788   //    of a string literal (or such a pointer cast to an integral type)
10789   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10790   //
10791   // Otherwise, it returns 0.
10792   //
10793   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10794   // its support for this did not work prior to GCC 9 and is not yet well
10795   // understood.
10796   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10797       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10798       ArgType->isNullPtrType()) {
10799     APValue V;
10800     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
10801       Fold.keepDiagnostics();
10802       return false;
10803     }
10804 
10805     // For a pointer (possibly cast to integer), there are special rules.
10806     if (V.getKind() == APValue::LValue)
10807       return EvaluateBuiltinConstantPForLValue(V);
10808 
10809     // Otherwise, any constant value is good enough.
10810     return V.hasValue();
10811   }
10812 
10813   // Anything else isn't considered to be sufficiently constant.
10814   return false;
10815 }
10816 
10817 /// Retrieves the "underlying object type" of the given expression,
10818 /// as used by __builtin_object_size.
10819 static QualType getObjectType(APValue::LValueBase B) {
10820   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10821     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10822       return VD->getType();
10823   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10824     if (isa<CompoundLiteralExpr>(E))
10825       return E->getType();
10826   } else if (B.is<TypeInfoLValue>()) {
10827     return B.getTypeInfoType();
10828   } else if (B.is<DynamicAllocLValue>()) {
10829     return B.getDynamicAllocType();
10830   }
10831 
10832   return QualType();
10833 }
10834 
10835 /// A more selective version of E->IgnoreParenCasts for
10836 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10837 /// to change the type of E.
10838 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10839 ///
10840 /// Always returns an RValue with a pointer representation.
10841 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10842   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10843 
10844   auto *NoParens = E->IgnoreParens();
10845   auto *Cast = dyn_cast<CastExpr>(NoParens);
10846   if (Cast == nullptr)
10847     return NoParens;
10848 
10849   // We only conservatively allow a few kinds of casts, because this code is
10850   // inherently a simple solution that seeks to support the common case.
10851   auto CastKind = Cast->getCastKind();
10852   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10853       CastKind != CK_AddressSpaceConversion)
10854     return NoParens;
10855 
10856   auto *SubExpr = Cast->getSubExpr();
10857   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10858     return NoParens;
10859   return ignorePointerCastsAndParens(SubExpr);
10860 }
10861 
10862 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10863 /// record layout. e.g.
10864 ///   struct { struct { int a, b; } fst, snd; } obj;
10865 ///   obj.fst   // no
10866 ///   obj.snd   // yes
10867 ///   obj.fst.a // no
10868 ///   obj.fst.b // no
10869 ///   obj.snd.a // no
10870 ///   obj.snd.b // yes
10871 ///
10872 /// Please note: this function is specialized for how __builtin_object_size
10873 /// views "objects".
10874 ///
10875 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10876 /// correct result, it will always return true.
10877 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10878   assert(!LVal.Designator.Invalid);
10879 
10880   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10881     const RecordDecl *Parent = FD->getParent();
10882     Invalid = Parent->isInvalidDecl();
10883     if (Invalid || Parent->isUnion())
10884       return true;
10885     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10886     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10887   };
10888 
10889   auto &Base = LVal.getLValueBase();
10890   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10891     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10892       bool Invalid;
10893       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10894         return Invalid;
10895     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10896       for (auto *FD : IFD->chain()) {
10897         bool Invalid;
10898         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10899           return Invalid;
10900       }
10901     }
10902   }
10903 
10904   unsigned I = 0;
10905   QualType BaseType = getType(Base);
10906   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10907     // If we don't know the array bound, conservatively assume we're looking at
10908     // the final array element.
10909     ++I;
10910     if (BaseType->isIncompleteArrayType())
10911       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10912     else
10913       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10914   }
10915 
10916   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10917     const auto &Entry = LVal.Designator.Entries[I];
10918     if (BaseType->isArrayType()) {
10919       // Because __builtin_object_size treats arrays as objects, we can ignore
10920       // the index iff this is the last array in the Designator.
10921       if (I + 1 == E)
10922         return true;
10923       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10924       uint64_t Index = Entry.getAsArrayIndex();
10925       if (Index + 1 != CAT->getSize())
10926         return false;
10927       BaseType = CAT->getElementType();
10928     } else if (BaseType->isAnyComplexType()) {
10929       const auto *CT = BaseType->castAs<ComplexType>();
10930       uint64_t Index = Entry.getAsArrayIndex();
10931       if (Index != 1)
10932         return false;
10933       BaseType = CT->getElementType();
10934     } else if (auto *FD = getAsField(Entry)) {
10935       bool Invalid;
10936       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10937         return Invalid;
10938       BaseType = FD->getType();
10939     } else {
10940       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10941       return false;
10942     }
10943   }
10944   return true;
10945 }
10946 
10947 /// Tests to see if the LValue has a user-specified designator (that isn't
10948 /// necessarily valid). Note that this always returns 'true' if the LValue has
10949 /// an unsized array as its first designator entry, because there's currently no
10950 /// way to tell if the user typed *foo or foo[0].
10951 static bool refersToCompleteObject(const LValue &LVal) {
10952   if (LVal.Designator.Invalid)
10953     return false;
10954 
10955   if (!LVal.Designator.Entries.empty())
10956     return LVal.Designator.isMostDerivedAnUnsizedArray();
10957 
10958   if (!LVal.InvalidBase)
10959     return true;
10960 
10961   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10962   // the LValueBase.
10963   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10964   return !E || !isa<MemberExpr>(E);
10965 }
10966 
10967 /// Attempts to detect a user writing into a piece of memory that's impossible
10968 /// to figure out the size of by just using types.
10969 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10970   const SubobjectDesignator &Designator = LVal.Designator;
10971   // Notes:
10972   // - Users can only write off of the end when we have an invalid base. Invalid
10973   //   bases imply we don't know where the memory came from.
10974   // - We used to be a bit more aggressive here; we'd only be conservative if
10975   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10976   //   broke some common standard library extensions (PR30346), but was
10977   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10978   //   with some sort of list. OTOH, it seems that GCC is always
10979   //   conservative with the last element in structs (if it's an array), so our
10980   //   current behavior is more compatible than an explicit list approach would
10981   //   be.
10982   return LVal.InvalidBase &&
10983          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10984          Designator.MostDerivedIsArrayElement &&
10985          isDesignatorAtObjectEnd(Ctx, LVal);
10986 }
10987 
10988 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10989 /// Fails if the conversion would cause loss of precision.
10990 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10991                                             CharUnits &Result) {
10992   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10993   if (Int.ugt(CharUnitsMax))
10994     return false;
10995   Result = CharUnits::fromQuantity(Int.getZExtValue());
10996   return true;
10997 }
10998 
10999 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11000 /// determine how many bytes exist from the beginning of the object to either
11001 /// the end of the current subobject, or the end of the object itself, depending
11002 /// on what the LValue looks like + the value of Type.
11003 ///
11004 /// If this returns false, the value of Result is undefined.
11005 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11006                                unsigned Type, const LValue &LVal,
11007                                CharUnits &EndOffset) {
11008   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11009 
11010   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11011     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11012       return false;
11013     return HandleSizeof(Info, ExprLoc, Ty, Result);
11014   };
11015 
11016   // We want to evaluate the size of the entire object. This is a valid fallback
11017   // for when Type=1 and the designator is invalid, because we're asked for an
11018   // upper-bound.
11019   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11020     // Type=3 wants a lower bound, so we can't fall back to this.
11021     if (Type == 3 && !DetermineForCompleteObject)
11022       return false;
11023 
11024     llvm::APInt APEndOffset;
11025     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11026         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11027       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11028 
11029     if (LVal.InvalidBase)
11030       return false;
11031 
11032     QualType BaseTy = getObjectType(LVal.getLValueBase());
11033     return CheckedHandleSizeof(BaseTy, EndOffset);
11034   }
11035 
11036   // We want to evaluate the size of a subobject.
11037   const SubobjectDesignator &Designator = LVal.Designator;
11038 
11039   // The following is a moderately common idiom in C:
11040   //
11041   // struct Foo { int a; char c[1]; };
11042   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11043   // strcpy(&F->c[0], Bar);
11044   //
11045   // In order to not break too much legacy code, we need to support it.
11046   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11047     // If we can resolve this to an alloc_size call, we can hand that back,
11048     // because we know for certain how many bytes there are to write to.
11049     llvm::APInt APEndOffset;
11050     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11051         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11052       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11053 
11054     // If we cannot determine the size of the initial allocation, then we can't
11055     // given an accurate upper-bound. However, we are still able to give
11056     // conservative lower-bounds for Type=3.
11057     if (Type == 1)
11058       return false;
11059   }
11060 
11061   CharUnits BytesPerElem;
11062   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11063     return false;
11064 
11065   // According to the GCC documentation, we want the size of the subobject
11066   // denoted by the pointer. But that's not quite right -- what we actually
11067   // want is the size of the immediately-enclosing array, if there is one.
11068   int64_t ElemsRemaining;
11069   if (Designator.MostDerivedIsArrayElement &&
11070       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11071     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11072     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11073     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11074   } else {
11075     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11076   }
11077 
11078   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11079   return true;
11080 }
11081 
11082 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11083 /// returns true and stores the result in @p Size.
11084 ///
11085 /// If @p WasError is non-null, this will report whether the failure to evaluate
11086 /// is to be treated as an Error in IntExprEvaluator.
11087 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11088                                          EvalInfo &Info, uint64_t &Size) {
11089   // Determine the denoted object.
11090   LValue LVal;
11091   {
11092     // The operand of __builtin_object_size is never evaluated for side-effects.
11093     // If there are any, but we can determine the pointed-to object anyway, then
11094     // ignore the side-effects.
11095     SpeculativeEvaluationRAII SpeculativeEval(Info);
11096     IgnoreSideEffectsRAII Fold(Info);
11097 
11098     if (E->isGLValue()) {
11099       // It's possible for us to be given GLValues if we're called via
11100       // Expr::tryEvaluateObjectSize.
11101       APValue RVal;
11102       if (!EvaluateAsRValue(Info, E, RVal))
11103         return false;
11104       LVal.setFrom(Info.Ctx, RVal);
11105     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11106                                 /*InvalidBaseOK=*/true))
11107       return false;
11108   }
11109 
11110   // If we point to before the start of the object, there are no accessible
11111   // bytes.
11112   if (LVal.getLValueOffset().isNegative()) {
11113     Size = 0;
11114     return true;
11115   }
11116 
11117   CharUnits EndOffset;
11118   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11119     return false;
11120 
11121   // If we've fallen outside of the end offset, just pretend there's nothing to
11122   // write to/read from.
11123   if (EndOffset <= LVal.getLValueOffset())
11124     Size = 0;
11125   else
11126     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11127   return true;
11128 }
11129 
11130 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11131   if (unsigned BuiltinOp = E->getBuiltinCallee())
11132     return VisitBuiltinCallExpr(E, BuiltinOp);
11133 
11134   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11135 }
11136 
11137 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11138                                      APValue &Val, APSInt &Alignment) {
11139   QualType SrcTy = E->getArg(0)->getType();
11140   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11141     return false;
11142   // Even though we are evaluating integer expressions we could get a pointer
11143   // argument for the __builtin_is_aligned() case.
11144   if (SrcTy->isPointerType()) {
11145     LValue Ptr;
11146     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11147       return false;
11148     Ptr.moveInto(Val);
11149   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11150     Info.FFDiag(E->getArg(0));
11151     return false;
11152   } else {
11153     APSInt SrcInt;
11154     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11155       return false;
11156     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11157            "Bit widths must be the same");
11158     Val = APValue(SrcInt);
11159   }
11160   assert(Val.hasValue());
11161   return true;
11162 }
11163 
11164 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11165                                             unsigned BuiltinOp) {
11166   switch (BuiltinOp) {
11167   default:
11168     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11169 
11170   case Builtin::BI__builtin_dynamic_object_size:
11171   case Builtin::BI__builtin_object_size: {
11172     // The type was checked when we built the expression.
11173     unsigned Type =
11174         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11175     assert(Type <= 3 && "unexpected type");
11176 
11177     uint64_t Size;
11178     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11179       return Success(Size, E);
11180 
11181     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11182       return Success((Type & 2) ? 0 : -1, E);
11183 
11184     // Expression had no side effects, but we couldn't statically determine the
11185     // size of the referenced object.
11186     switch (Info.EvalMode) {
11187     case EvalInfo::EM_ConstantExpression:
11188     case EvalInfo::EM_ConstantFold:
11189     case EvalInfo::EM_IgnoreSideEffects:
11190       // Leave it to IR generation.
11191       return Error(E);
11192     case EvalInfo::EM_ConstantExpressionUnevaluated:
11193       // Reduce it to a constant now.
11194       return Success((Type & 2) ? 0 : -1, E);
11195     }
11196 
11197     llvm_unreachable("unexpected EvalMode");
11198   }
11199 
11200   case Builtin::BI__builtin_os_log_format_buffer_size: {
11201     analyze_os_log::OSLogBufferLayout Layout;
11202     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11203     return Success(Layout.size().getQuantity(), E);
11204   }
11205 
11206   case Builtin::BI__builtin_is_aligned: {
11207     APValue Src;
11208     APSInt Alignment;
11209     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11210       return false;
11211     if (Src.isLValue()) {
11212       // If we evaluated a pointer, check the minimum known alignment.
11213       LValue Ptr;
11214       Ptr.setFrom(Info.Ctx, Src);
11215       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11216       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11217       // We can return true if the known alignment at the computed offset is
11218       // greater than the requested alignment.
11219       assert(PtrAlign.isPowerOfTwo());
11220       assert(Alignment.isPowerOf2());
11221       if (PtrAlign.getQuantity() >= Alignment)
11222         return Success(1, E);
11223       // If the alignment is not known to be sufficient, some cases could still
11224       // be aligned at run time. However, if the requested alignment is less or
11225       // equal to the base alignment and the offset is not aligned, we know that
11226       // the run-time value can never be aligned.
11227       if (BaseAlignment.getQuantity() >= Alignment &&
11228           PtrAlign.getQuantity() < Alignment)
11229         return Success(0, E);
11230       // Otherwise we can't infer whether the value is sufficiently aligned.
11231       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11232       //  in cases where we can't fully evaluate the pointer.
11233       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11234           << Alignment;
11235       return false;
11236     }
11237     assert(Src.isInt());
11238     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11239   }
11240   case Builtin::BI__builtin_align_up: {
11241     APValue Src;
11242     APSInt Alignment;
11243     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11244       return false;
11245     if (!Src.isInt())
11246       return Error(E);
11247     APSInt AlignedVal =
11248         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11249                Src.getInt().isUnsigned());
11250     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11251     return Success(AlignedVal, E);
11252   }
11253   case Builtin::BI__builtin_align_down: {
11254     APValue Src;
11255     APSInt Alignment;
11256     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11257       return false;
11258     if (!Src.isInt())
11259       return Error(E);
11260     APSInt AlignedVal =
11261         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11262     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11263     return Success(AlignedVal, E);
11264   }
11265 
11266   case Builtin::BI__builtin_bitreverse8:
11267   case Builtin::BI__builtin_bitreverse16:
11268   case Builtin::BI__builtin_bitreverse32:
11269   case Builtin::BI__builtin_bitreverse64: {
11270     APSInt Val;
11271     if (!EvaluateInteger(E->getArg(0), Val, Info))
11272       return false;
11273 
11274     return Success(Val.reverseBits(), E);
11275   }
11276 
11277   case Builtin::BI__builtin_bswap16:
11278   case Builtin::BI__builtin_bswap32:
11279   case Builtin::BI__builtin_bswap64: {
11280     APSInt Val;
11281     if (!EvaluateInteger(E->getArg(0), Val, Info))
11282       return false;
11283 
11284     return Success(Val.byteSwap(), E);
11285   }
11286 
11287   case Builtin::BI__builtin_classify_type:
11288     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11289 
11290   case Builtin::BI__builtin_clrsb:
11291   case Builtin::BI__builtin_clrsbl:
11292   case Builtin::BI__builtin_clrsbll: {
11293     APSInt Val;
11294     if (!EvaluateInteger(E->getArg(0), Val, Info))
11295       return false;
11296 
11297     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11298   }
11299 
11300   case Builtin::BI__builtin_clz:
11301   case Builtin::BI__builtin_clzl:
11302   case Builtin::BI__builtin_clzll:
11303   case Builtin::BI__builtin_clzs: {
11304     APSInt Val;
11305     if (!EvaluateInteger(E->getArg(0), Val, Info))
11306       return false;
11307     if (!Val)
11308       return Error(E);
11309 
11310     return Success(Val.countLeadingZeros(), E);
11311   }
11312 
11313   case Builtin::BI__builtin_constant_p: {
11314     const Expr *Arg = E->getArg(0);
11315     if (EvaluateBuiltinConstantP(Info, Arg))
11316       return Success(true, E);
11317     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11318       // Outside a constant context, eagerly evaluate to false in the presence
11319       // of side-effects in order to avoid -Wunsequenced false-positives in
11320       // a branch on __builtin_constant_p(expr).
11321       return Success(false, E);
11322     }
11323     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11324     return false;
11325   }
11326 
11327   case Builtin::BI__builtin_is_constant_evaluated: {
11328     const auto *Callee = Info.CurrentCall->getCallee();
11329     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11330         (Info.CallStackDepth == 1 ||
11331          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11332           Callee->getIdentifier() &&
11333           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11334       // FIXME: Find a better way to avoid duplicated diagnostics.
11335       if (Info.EvalStatus.Diag)
11336         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11337                                                : Info.CurrentCall->CallLoc,
11338                     diag::warn_is_constant_evaluated_always_true_constexpr)
11339             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11340                                          : "std::is_constant_evaluated");
11341     }
11342 
11343     return Success(Info.InConstantContext, E);
11344   }
11345 
11346   case Builtin::BI__builtin_ctz:
11347   case Builtin::BI__builtin_ctzl:
11348   case Builtin::BI__builtin_ctzll:
11349   case Builtin::BI__builtin_ctzs: {
11350     APSInt Val;
11351     if (!EvaluateInteger(E->getArg(0), Val, Info))
11352       return false;
11353     if (!Val)
11354       return Error(E);
11355 
11356     return Success(Val.countTrailingZeros(), E);
11357   }
11358 
11359   case Builtin::BI__builtin_eh_return_data_regno: {
11360     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11361     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11362     return Success(Operand, E);
11363   }
11364 
11365   case Builtin::BI__builtin_expect:
11366   case Builtin::BI__builtin_expect_with_probability:
11367     return Visit(E->getArg(0));
11368 
11369   case Builtin::BI__builtin_ffs:
11370   case Builtin::BI__builtin_ffsl:
11371   case Builtin::BI__builtin_ffsll: {
11372     APSInt Val;
11373     if (!EvaluateInteger(E->getArg(0), Val, Info))
11374       return false;
11375 
11376     unsigned N = Val.countTrailingZeros();
11377     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11378   }
11379 
11380   case Builtin::BI__builtin_fpclassify: {
11381     APFloat Val(0.0);
11382     if (!EvaluateFloat(E->getArg(5), Val, Info))
11383       return false;
11384     unsigned Arg;
11385     switch (Val.getCategory()) {
11386     case APFloat::fcNaN: Arg = 0; break;
11387     case APFloat::fcInfinity: Arg = 1; break;
11388     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11389     case APFloat::fcZero: Arg = 4; break;
11390     }
11391     return Visit(E->getArg(Arg));
11392   }
11393 
11394   case Builtin::BI__builtin_isinf_sign: {
11395     APFloat Val(0.0);
11396     return EvaluateFloat(E->getArg(0), Val, Info) &&
11397            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11398   }
11399 
11400   case Builtin::BI__builtin_isinf: {
11401     APFloat Val(0.0);
11402     return EvaluateFloat(E->getArg(0), Val, Info) &&
11403            Success(Val.isInfinity() ? 1 : 0, E);
11404   }
11405 
11406   case Builtin::BI__builtin_isfinite: {
11407     APFloat Val(0.0);
11408     return EvaluateFloat(E->getArg(0), Val, Info) &&
11409            Success(Val.isFinite() ? 1 : 0, E);
11410   }
11411 
11412   case Builtin::BI__builtin_isnan: {
11413     APFloat Val(0.0);
11414     return EvaluateFloat(E->getArg(0), Val, Info) &&
11415            Success(Val.isNaN() ? 1 : 0, E);
11416   }
11417 
11418   case Builtin::BI__builtin_isnormal: {
11419     APFloat Val(0.0);
11420     return EvaluateFloat(E->getArg(0), Val, Info) &&
11421            Success(Val.isNormal() ? 1 : 0, E);
11422   }
11423 
11424   case Builtin::BI__builtin_parity:
11425   case Builtin::BI__builtin_parityl:
11426   case Builtin::BI__builtin_parityll: {
11427     APSInt Val;
11428     if (!EvaluateInteger(E->getArg(0), Val, Info))
11429       return false;
11430 
11431     return Success(Val.countPopulation() % 2, E);
11432   }
11433 
11434   case Builtin::BI__builtin_popcount:
11435   case Builtin::BI__builtin_popcountl:
11436   case Builtin::BI__builtin_popcountll: {
11437     APSInt Val;
11438     if (!EvaluateInteger(E->getArg(0), Val, Info))
11439       return false;
11440 
11441     return Success(Val.countPopulation(), E);
11442   }
11443 
11444   case Builtin::BI__builtin_rotateleft8:
11445   case Builtin::BI__builtin_rotateleft16:
11446   case Builtin::BI__builtin_rotateleft32:
11447   case Builtin::BI__builtin_rotateleft64:
11448   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11449   case Builtin::BI_rotl16:
11450   case Builtin::BI_rotl:
11451   case Builtin::BI_lrotl:
11452   case Builtin::BI_rotl64: {
11453     APSInt Val, Amt;
11454     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11455         !EvaluateInteger(E->getArg(1), Amt, Info))
11456       return false;
11457 
11458     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11459   }
11460 
11461   case Builtin::BI__builtin_rotateright8:
11462   case Builtin::BI__builtin_rotateright16:
11463   case Builtin::BI__builtin_rotateright32:
11464   case Builtin::BI__builtin_rotateright64:
11465   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11466   case Builtin::BI_rotr16:
11467   case Builtin::BI_rotr:
11468   case Builtin::BI_lrotr:
11469   case Builtin::BI_rotr64: {
11470     APSInt Val, Amt;
11471     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11472         !EvaluateInteger(E->getArg(1), Amt, Info))
11473       return false;
11474 
11475     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11476   }
11477 
11478   case Builtin::BIstrlen:
11479   case Builtin::BIwcslen:
11480     // A call to strlen is not a constant expression.
11481     if (Info.getLangOpts().CPlusPlus11)
11482       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11483         << /*isConstexpr*/0 << /*isConstructor*/0
11484         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11485     else
11486       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11487     LLVM_FALLTHROUGH;
11488   case Builtin::BI__builtin_strlen:
11489   case Builtin::BI__builtin_wcslen: {
11490     // As an extension, we support __builtin_strlen() as a constant expression,
11491     // and support folding strlen() to a constant.
11492     LValue String;
11493     if (!EvaluatePointer(E->getArg(0), String, Info))
11494       return false;
11495 
11496     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11497 
11498     // Fast path: if it's a string literal, search the string value.
11499     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11500             String.getLValueBase().dyn_cast<const Expr *>())) {
11501       // The string literal may have embedded null characters. Find the first
11502       // one and truncate there.
11503       StringRef Str = S->getBytes();
11504       int64_t Off = String.Offset.getQuantity();
11505       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11506           S->getCharByteWidth() == 1 &&
11507           // FIXME: Add fast-path for wchar_t too.
11508           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11509         Str = Str.substr(Off);
11510 
11511         StringRef::size_type Pos = Str.find(0);
11512         if (Pos != StringRef::npos)
11513           Str = Str.substr(0, Pos);
11514 
11515         return Success(Str.size(), E);
11516       }
11517 
11518       // Fall through to slow path to issue appropriate diagnostic.
11519     }
11520 
11521     // Slow path: scan the bytes of the string looking for the terminating 0.
11522     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11523       APValue Char;
11524       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11525           !Char.isInt())
11526         return false;
11527       if (!Char.getInt())
11528         return Success(Strlen, E);
11529       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11530         return false;
11531     }
11532   }
11533 
11534   case Builtin::BIstrcmp:
11535   case Builtin::BIwcscmp:
11536   case Builtin::BIstrncmp:
11537   case Builtin::BIwcsncmp:
11538   case Builtin::BImemcmp:
11539   case Builtin::BIbcmp:
11540   case Builtin::BIwmemcmp:
11541     // A call to strlen is not a constant expression.
11542     if (Info.getLangOpts().CPlusPlus11)
11543       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11544         << /*isConstexpr*/0 << /*isConstructor*/0
11545         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11546     else
11547       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11548     LLVM_FALLTHROUGH;
11549   case Builtin::BI__builtin_strcmp:
11550   case Builtin::BI__builtin_wcscmp:
11551   case Builtin::BI__builtin_strncmp:
11552   case Builtin::BI__builtin_wcsncmp:
11553   case Builtin::BI__builtin_memcmp:
11554   case Builtin::BI__builtin_bcmp:
11555   case Builtin::BI__builtin_wmemcmp: {
11556     LValue String1, String2;
11557     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11558         !EvaluatePointer(E->getArg(1), String2, Info))
11559       return false;
11560 
11561     uint64_t MaxLength = uint64_t(-1);
11562     if (BuiltinOp != Builtin::BIstrcmp &&
11563         BuiltinOp != Builtin::BIwcscmp &&
11564         BuiltinOp != Builtin::BI__builtin_strcmp &&
11565         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11566       APSInt N;
11567       if (!EvaluateInteger(E->getArg(2), N, Info))
11568         return false;
11569       MaxLength = N.getExtValue();
11570     }
11571 
11572     // Empty substrings compare equal by definition.
11573     if (MaxLength == 0u)
11574       return Success(0, E);
11575 
11576     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11577         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11578         String1.Designator.Invalid || String2.Designator.Invalid)
11579       return false;
11580 
11581     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11582     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11583 
11584     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11585                      BuiltinOp == Builtin::BIbcmp ||
11586                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11587                      BuiltinOp == Builtin::BI__builtin_bcmp;
11588 
11589     assert(IsRawByte ||
11590            (Info.Ctx.hasSameUnqualifiedType(
11591                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11592             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11593 
11594     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11595     // 'char8_t', but no other types.
11596     if (IsRawByte &&
11597         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11598       // FIXME: Consider using our bit_cast implementation to support this.
11599       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11600           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11601           << CharTy1 << CharTy2;
11602       return false;
11603     }
11604 
11605     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11606       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11607              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11608              Char1.isInt() && Char2.isInt();
11609     };
11610     const auto &AdvanceElems = [&] {
11611       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11612              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11613     };
11614 
11615     bool StopAtNull =
11616         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11617          BuiltinOp != Builtin::BIwmemcmp &&
11618          BuiltinOp != Builtin::BI__builtin_memcmp &&
11619          BuiltinOp != Builtin::BI__builtin_bcmp &&
11620          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11621     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11622                   BuiltinOp == Builtin::BIwcsncmp ||
11623                   BuiltinOp == Builtin::BIwmemcmp ||
11624                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11625                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11626                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11627 
11628     for (; MaxLength; --MaxLength) {
11629       APValue Char1, Char2;
11630       if (!ReadCurElems(Char1, Char2))
11631         return false;
11632       if (Char1.getInt().ne(Char2.getInt())) {
11633         if (IsWide) // wmemcmp compares with wchar_t signedness.
11634           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11635         // memcmp always compares unsigned chars.
11636         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11637       }
11638       if (StopAtNull && !Char1.getInt())
11639         return Success(0, E);
11640       assert(!(StopAtNull && !Char2.getInt()));
11641       if (!AdvanceElems())
11642         return false;
11643     }
11644     // We hit the strncmp / memcmp limit.
11645     return Success(0, E);
11646   }
11647 
11648   case Builtin::BI__atomic_always_lock_free:
11649   case Builtin::BI__atomic_is_lock_free:
11650   case Builtin::BI__c11_atomic_is_lock_free: {
11651     APSInt SizeVal;
11652     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11653       return false;
11654 
11655     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11656     // of two less than or equal to the maximum inline atomic width, we know it
11657     // is lock-free.  If the size isn't a power of two, or greater than the
11658     // maximum alignment where we promote atomics, we know it is not lock-free
11659     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11660     // the answer can only be determined at runtime; for example, 16-byte
11661     // atomics have lock-free implementations on some, but not all,
11662     // x86-64 processors.
11663 
11664     // Check power-of-two.
11665     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11666     if (Size.isPowerOfTwo()) {
11667       // Check against inlining width.
11668       unsigned InlineWidthBits =
11669           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11670       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11671         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11672             Size == CharUnits::One() ||
11673             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11674                                                 Expr::NPC_NeverValueDependent))
11675           // OK, we will inline appropriately-aligned operations of this size,
11676           // and _Atomic(T) is appropriately-aligned.
11677           return Success(1, E);
11678 
11679         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11680           castAs<PointerType>()->getPointeeType();
11681         if (!PointeeType->isIncompleteType() &&
11682             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11683           // OK, we will inline operations on this object.
11684           return Success(1, E);
11685         }
11686       }
11687     }
11688 
11689     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11690         Success(0, E) : Error(E);
11691   }
11692   case Builtin::BIomp_is_initial_device:
11693     // We can decide statically which value the runtime would return if called.
11694     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11695   case Builtin::BI__builtin_add_overflow:
11696   case Builtin::BI__builtin_sub_overflow:
11697   case Builtin::BI__builtin_mul_overflow:
11698   case Builtin::BI__builtin_sadd_overflow:
11699   case Builtin::BI__builtin_uadd_overflow:
11700   case Builtin::BI__builtin_uaddl_overflow:
11701   case Builtin::BI__builtin_uaddll_overflow:
11702   case Builtin::BI__builtin_usub_overflow:
11703   case Builtin::BI__builtin_usubl_overflow:
11704   case Builtin::BI__builtin_usubll_overflow:
11705   case Builtin::BI__builtin_umul_overflow:
11706   case Builtin::BI__builtin_umull_overflow:
11707   case Builtin::BI__builtin_umulll_overflow:
11708   case Builtin::BI__builtin_saddl_overflow:
11709   case Builtin::BI__builtin_saddll_overflow:
11710   case Builtin::BI__builtin_ssub_overflow:
11711   case Builtin::BI__builtin_ssubl_overflow:
11712   case Builtin::BI__builtin_ssubll_overflow:
11713   case Builtin::BI__builtin_smul_overflow:
11714   case Builtin::BI__builtin_smull_overflow:
11715   case Builtin::BI__builtin_smulll_overflow: {
11716     LValue ResultLValue;
11717     APSInt LHS, RHS;
11718 
11719     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11720     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11721         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11722         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11723       return false;
11724 
11725     APSInt Result;
11726     bool DidOverflow = false;
11727 
11728     // If the types don't have to match, enlarge all 3 to the largest of them.
11729     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11730         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11731         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11732       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11733                       ResultType->isSignedIntegerOrEnumerationType();
11734       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11735                       ResultType->isSignedIntegerOrEnumerationType();
11736       uint64_t LHSSize = LHS.getBitWidth();
11737       uint64_t RHSSize = RHS.getBitWidth();
11738       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11739       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11740 
11741       // Add an additional bit if the signedness isn't uniformly agreed to. We
11742       // could do this ONLY if there is a signed and an unsigned that both have
11743       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11744       // caught in the shrink-to-result later anyway.
11745       if (IsSigned && !AllSigned)
11746         ++MaxBits;
11747 
11748       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11749       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11750       Result = APSInt(MaxBits, !IsSigned);
11751     }
11752 
11753     // Find largest int.
11754     switch (BuiltinOp) {
11755     default:
11756       llvm_unreachable("Invalid value for BuiltinOp");
11757     case Builtin::BI__builtin_add_overflow:
11758     case Builtin::BI__builtin_sadd_overflow:
11759     case Builtin::BI__builtin_saddl_overflow:
11760     case Builtin::BI__builtin_saddll_overflow:
11761     case Builtin::BI__builtin_uadd_overflow:
11762     case Builtin::BI__builtin_uaddl_overflow:
11763     case Builtin::BI__builtin_uaddll_overflow:
11764       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11765                               : LHS.uadd_ov(RHS, DidOverflow);
11766       break;
11767     case Builtin::BI__builtin_sub_overflow:
11768     case Builtin::BI__builtin_ssub_overflow:
11769     case Builtin::BI__builtin_ssubl_overflow:
11770     case Builtin::BI__builtin_ssubll_overflow:
11771     case Builtin::BI__builtin_usub_overflow:
11772     case Builtin::BI__builtin_usubl_overflow:
11773     case Builtin::BI__builtin_usubll_overflow:
11774       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11775                               : LHS.usub_ov(RHS, DidOverflow);
11776       break;
11777     case Builtin::BI__builtin_mul_overflow:
11778     case Builtin::BI__builtin_smul_overflow:
11779     case Builtin::BI__builtin_smull_overflow:
11780     case Builtin::BI__builtin_smulll_overflow:
11781     case Builtin::BI__builtin_umul_overflow:
11782     case Builtin::BI__builtin_umull_overflow:
11783     case Builtin::BI__builtin_umulll_overflow:
11784       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11785                               : LHS.umul_ov(RHS, DidOverflow);
11786       break;
11787     }
11788 
11789     // In the case where multiple sizes are allowed, truncate and see if
11790     // the values are the same.
11791     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11792         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11793         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11794       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11795       // since it will give us the behavior of a TruncOrSelf in the case where
11796       // its parameter <= its size.  We previously set Result to be at least the
11797       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11798       // will work exactly like TruncOrSelf.
11799       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11800       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11801 
11802       if (!APSInt::isSameValue(Temp, Result))
11803         DidOverflow = true;
11804       Result = Temp;
11805     }
11806 
11807     APValue APV{Result};
11808     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11809       return false;
11810     return Success(DidOverflow, E);
11811   }
11812   }
11813 }
11814 
11815 /// Determine whether this is a pointer past the end of the complete
11816 /// object referred to by the lvalue.
11817 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11818                                             const LValue &LV) {
11819   // A null pointer can be viewed as being "past the end" but we don't
11820   // choose to look at it that way here.
11821   if (!LV.getLValueBase())
11822     return false;
11823 
11824   // If the designator is valid and refers to a subobject, we're not pointing
11825   // past the end.
11826   if (!LV.getLValueDesignator().Invalid &&
11827       !LV.getLValueDesignator().isOnePastTheEnd())
11828     return false;
11829 
11830   // A pointer to an incomplete type might be past-the-end if the type's size is
11831   // zero.  We cannot tell because the type is incomplete.
11832   QualType Ty = getType(LV.getLValueBase());
11833   if (Ty->isIncompleteType())
11834     return true;
11835 
11836   // We're a past-the-end pointer if we point to the byte after the object,
11837   // no matter what our type or path is.
11838   auto Size = Ctx.getTypeSizeInChars(Ty);
11839   return LV.getLValueOffset() == Size;
11840 }
11841 
11842 namespace {
11843 
11844 /// Data recursive integer evaluator of certain binary operators.
11845 ///
11846 /// We use a data recursive algorithm for binary operators so that we are able
11847 /// to handle extreme cases of chained binary operators without causing stack
11848 /// overflow.
11849 class DataRecursiveIntBinOpEvaluator {
11850   struct EvalResult {
11851     APValue Val;
11852     bool Failed;
11853 
11854     EvalResult() : Failed(false) { }
11855 
11856     void swap(EvalResult &RHS) {
11857       Val.swap(RHS.Val);
11858       Failed = RHS.Failed;
11859       RHS.Failed = false;
11860     }
11861   };
11862 
11863   struct Job {
11864     const Expr *E;
11865     EvalResult LHSResult; // meaningful only for binary operator expression.
11866     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11867 
11868     Job() = default;
11869     Job(Job &&) = default;
11870 
11871     void startSpeculativeEval(EvalInfo &Info) {
11872       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11873     }
11874 
11875   private:
11876     SpeculativeEvaluationRAII SpecEvalRAII;
11877   };
11878 
11879   SmallVector<Job, 16> Queue;
11880 
11881   IntExprEvaluator &IntEval;
11882   EvalInfo &Info;
11883   APValue &FinalResult;
11884 
11885 public:
11886   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11887     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11888 
11889   /// True if \param E is a binary operator that we are going to handle
11890   /// data recursively.
11891   /// We handle binary operators that are comma, logical, or that have operands
11892   /// with integral or enumeration type.
11893   static bool shouldEnqueue(const BinaryOperator *E) {
11894     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11895            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11896             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11897             E->getRHS()->getType()->isIntegralOrEnumerationType());
11898   }
11899 
11900   bool Traverse(const BinaryOperator *E) {
11901     enqueue(E);
11902     EvalResult PrevResult;
11903     while (!Queue.empty())
11904       process(PrevResult);
11905 
11906     if (PrevResult.Failed) return false;
11907 
11908     FinalResult.swap(PrevResult.Val);
11909     return true;
11910   }
11911 
11912 private:
11913   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11914     return IntEval.Success(Value, E, Result);
11915   }
11916   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11917     return IntEval.Success(Value, E, Result);
11918   }
11919   bool Error(const Expr *E) {
11920     return IntEval.Error(E);
11921   }
11922   bool Error(const Expr *E, diag::kind D) {
11923     return IntEval.Error(E, D);
11924   }
11925 
11926   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11927     return Info.CCEDiag(E, D);
11928   }
11929 
11930   // Returns true if visiting the RHS is necessary, false otherwise.
11931   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11932                          bool &SuppressRHSDiags);
11933 
11934   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11935                   const BinaryOperator *E, APValue &Result);
11936 
11937   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11938     Result.Failed = !Evaluate(Result.Val, Info, E);
11939     if (Result.Failed)
11940       Result.Val = APValue();
11941   }
11942 
11943   void process(EvalResult &Result);
11944 
11945   void enqueue(const Expr *E) {
11946     E = E->IgnoreParens();
11947     Queue.resize(Queue.size()+1);
11948     Queue.back().E = E;
11949     Queue.back().Kind = Job::AnyExprKind;
11950   }
11951 };
11952 
11953 }
11954 
11955 bool DataRecursiveIntBinOpEvaluator::
11956        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11957                          bool &SuppressRHSDiags) {
11958   if (E->getOpcode() == BO_Comma) {
11959     // Ignore LHS but note if we could not evaluate it.
11960     if (LHSResult.Failed)
11961       return Info.noteSideEffect();
11962     return true;
11963   }
11964 
11965   if (E->isLogicalOp()) {
11966     bool LHSAsBool;
11967     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11968       // We were able to evaluate the LHS, see if we can get away with not
11969       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11970       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11971         Success(LHSAsBool, E, LHSResult.Val);
11972         return false; // Ignore RHS
11973       }
11974     } else {
11975       LHSResult.Failed = true;
11976 
11977       // Since we weren't able to evaluate the left hand side, it
11978       // might have had side effects.
11979       if (!Info.noteSideEffect())
11980         return false;
11981 
11982       // We can't evaluate the LHS; however, sometimes the result
11983       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11984       // Don't ignore RHS and suppress diagnostics from this arm.
11985       SuppressRHSDiags = true;
11986     }
11987 
11988     return true;
11989   }
11990 
11991   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11992          E->getRHS()->getType()->isIntegralOrEnumerationType());
11993 
11994   if (LHSResult.Failed && !Info.noteFailure())
11995     return false; // Ignore RHS;
11996 
11997   return true;
11998 }
11999 
12000 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12001                                     bool IsSub) {
12002   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12003   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12004   // offsets.
12005   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12006   CharUnits &Offset = LVal.getLValueOffset();
12007   uint64_t Offset64 = Offset.getQuantity();
12008   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12009   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12010                                          : Offset64 + Index64);
12011 }
12012 
12013 bool DataRecursiveIntBinOpEvaluator::
12014        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12015                   const BinaryOperator *E, APValue &Result) {
12016   if (E->getOpcode() == BO_Comma) {
12017     if (RHSResult.Failed)
12018       return false;
12019     Result = RHSResult.Val;
12020     return true;
12021   }
12022 
12023   if (E->isLogicalOp()) {
12024     bool lhsResult, rhsResult;
12025     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12026     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12027 
12028     if (LHSIsOK) {
12029       if (RHSIsOK) {
12030         if (E->getOpcode() == BO_LOr)
12031           return Success(lhsResult || rhsResult, E, Result);
12032         else
12033           return Success(lhsResult && rhsResult, E, Result);
12034       }
12035     } else {
12036       if (RHSIsOK) {
12037         // We can't evaluate the LHS; however, sometimes the result
12038         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12039         if (rhsResult == (E->getOpcode() == BO_LOr))
12040           return Success(rhsResult, E, Result);
12041       }
12042     }
12043 
12044     return false;
12045   }
12046 
12047   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12048          E->getRHS()->getType()->isIntegralOrEnumerationType());
12049 
12050   if (LHSResult.Failed || RHSResult.Failed)
12051     return false;
12052 
12053   const APValue &LHSVal = LHSResult.Val;
12054   const APValue &RHSVal = RHSResult.Val;
12055 
12056   // Handle cases like (unsigned long)&a + 4.
12057   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12058     Result = LHSVal;
12059     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12060     return true;
12061   }
12062 
12063   // Handle cases like 4 + (unsigned long)&a
12064   if (E->getOpcode() == BO_Add &&
12065       RHSVal.isLValue() && LHSVal.isInt()) {
12066     Result = RHSVal;
12067     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12068     return true;
12069   }
12070 
12071   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12072     // Handle (intptr_t)&&A - (intptr_t)&&B.
12073     if (!LHSVal.getLValueOffset().isZero() ||
12074         !RHSVal.getLValueOffset().isZero())
12075       return false;
12076     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12077     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12078     if (!LHSExpr || !RHSExpr)
12079       return false;
12080     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12081     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12082     if (!LHSAddrExpr || !RHSAddrExpr)
12083       return false;
12084     // Make sure both labels come from the same function.
12085     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12086         RHSAddrExpr->getLabel()->getDeclContext())
12087       return false;
12088     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12089     return true;
12090   }
12091 
12092   // All the remaining cases expect both operands to be an integer
12093   if (!LHSVal.isInt() || !RHSVal.isInt())
12094     return Error(E);
12095 
12096   // Set up the width and signedness manually, in case it can't be deduced
12097   // from the operation we're performing.
12098   // FIXME: Don't do this in the cases where we can deduce it.
12099   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12100                E->getType()->isUnsignedIntegerOrEnumerationType());
12101   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12102                          RHSVal.getInt(), Value))
12103     return false;
12104   return Success(Value, E, Result);
12105 }
12106 
12107 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12108   Job &job = Queue.back();
12109 
12110   switch (job.Kind) {
12111     case Job::AnyExprKind: {
12112       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12113         if (shouldEnqueue(Bop)) {
12114           job.Kind = Job::BinOpKind;
12115           enqueue(Bop->getLHS());
12116           return;
12117         }
12118       }
12119 
12120       EvaluateExpr(job.E, Result);
12121       Queue.pop_back();
12122       return;
12123     }
12124 
12125     case Job::BinOpKind: {
12126       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12127       bool SuppressRHSDiags = false;
12128       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12129         Queue.pop_back();
12130         return;
12131       }
12132       if (SuppressRHSDiags)
12133         job.startSpeculativeEval(Info);
12134       job.LHSResult.swap(Result);
12135       job.Kind = Job::BinOpVisitedLHSKind;
12136       enqueue(Bop->getRHS());
12137       return;
12138     }
12139 
12140     case Job::BinOpVisitedLHSKind: {
12141       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12142       EvalResult RHS;
12143       RHS.swap(Result);
12144       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12145       Queue.pop_back();
12146       return;
12147     }
12148   }
12149 
12150   llvm_unreachable("Invalid Job::Kind!");
12151 }
12152 
12153 namespace {
12154 /// Used when we determine that we should fail, but can keep evaluating prior to
12155 /// noting that we had a failure.
12156 class DelayedNoteFailureRAII {
12157   EvalInfo &Info;
12158   bool NoteFailure;
12159 
12160 public:
12161   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12162       : Info(Info), NoteFailure(NoteFailure) {}
12163   ~DelayedNoteFailureRAII() {
12164     if (NoteFailure) {
12165       bool ContinueAfterFailure = Info.noteFailure();
12166       (void)ContinueAfterFailure;
12167       assert(ContinueAfterFailure &&
12168              "Shouldn't have kept evaluating on failure.");
12169     }
12170   }
12171 };
12172 
12173 enum class CmpResult {
12174   Unequal,
12175   Less,
12176   Equal,
12177   Greater,
12178   Unordered,
12179 };
12180 }
12181 
12182 template <class SuccessCB, class AfterCB>
12183 static bool
12184 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12185                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12186   assert(E->isComparisonOp() && "expected comparison operator");
12187   assert((E->getOpcode() == BO_Cmp ||
12188           E->getType()->isIntegralOrEnumerationType()) &&
12189          "unsupported binary expression evaluation");
12190   auto Error = [&](const Expr *E) {
12191     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12192     return false;
12193   };
12194 
12195   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12196   bool IsEquality = E->isEqualityOp();
12197 
12198   QualType LHSTy = E->getLHS()->getType();
12199   QualType RHSTy = E->getRHS()->getType();
12200 
12201   if (LHSTy->isIntegralOrEnumerationType() &&
12202       RHSTy->isIntegralOrEnumerationType()) {
12203     APSInt LHS, RHS;
12204     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12205     if (!LHSOK && !Info.noteFailure())
12206       return false;
12207     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12208       return false;
12209     if (LHS < RHS)
12210       return Success(CmpResult::Less, E);
12211     if (LHS > RHS)
12212       return Success(CmpResult::Greater, E);
12213     return Success(CmpResult::Equal, E);
12214   }
12215 
12216   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12217     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12218     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12219 
12220     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12221     if (!LHSOK && !Info.noteFailure())
12222       return false;
12223     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12224       return false;
12225     if (LHSFX < RHSFX)
12226       return Success(CmpResult::Less, E);
12227     if (LHSFX > RHSFX)
12228       return Success(CmpResult::Greater, E);
12229     return Success(CmpResult::Equal, E);
12230   }
12231 
12232   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12233     ComplexValue LHS, RHS;
12234     bool LHSOK;
12235     if (E->isAssignmentOp()) {
12236       LValue LV;
12237       EvaluateLValue(E->getLHS(), LV, Info);
12238       LHSOK = false;
12239     } else if (LHSTy->isRealFloatingType()) {
12240       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12241       if (LHSOK) {
12242         LHS.makeComplexFloat();
12243         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12244       }
12245     } else {
12246       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12247     }
12248     if (!LHSOK && !Info.noteFailure())
12249       return false;
12250 
12251     if (E->getRHS()->getType()->isRealFloatingType()) {
12252       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12253         return false;
12254       RHS.makeComplexFloat();
12255       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12256     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12257       return false;
12258 
12259     if (LHS.isComplexFloat()) {
12260       APFloat::cmpResult CR_r =
12261         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12262       APFloat::cmpResult CR_i =
12263         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12264       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12265       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12266     } else {
12267       assert(IsEquality && "invalid complex comparison");
12268       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12269                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12270       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12271     }
12272   }
12273 
12274   if (LHSTy->isRealFloatingType() &&
12275       RHSTy->isRealFloatingType()) {
12276     APFloat RHS(0.0), LHS(0.0);
12277 
12278     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12279     if (!LHSOK && !Info.noteFailure())
12280       return false;
12281 
12282     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12283       return false;
12284 
12285     assert(E->isComparisonOp() && "Invalid binary operator!");
12286     auto GetCmpRes = [&]() {
12287       switch (LHS.compare(RHS)) {
12288       case APFloat::cmpEqual:
12289         return CmpResult::Equal;
12290       case APFloat::cmpLessThan:
12291         return CmpResult::Less;
12292       case APFloat::cmpGreaterThan:
12293         return CmpResult::Greater;
12294       case APFloat::cmpUnordered:
12295         return CmpResult::Unordered;
12296       }
12297       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12298     };
12299     return Success(GetCmpRes(), E);
12300   }
12301 
12302   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12303     LValue LHSValue, RHSValue;
12304 
12305     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12306     if (!LHSOK && !Info.noteFailure())
12307       return false;
12308 
12309     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12310       return false;
12311 
12312     // Reject differing bases from the normal codepath; we special-case
12313     // comparisons to null.
12314     if (!HasSameBase(LHSValue, RHSValue)) {
12315       // Inequalities and subtractions between unrelated pointers have
12316       // unspecified or undefined behavior.
12317       if (!IsEquality) {
12318         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12319         return false;
12320       }
12321       // A constant address may compare equal to the address of a symbol.
12322       // The one exception is that address of an object cannot compare equal
12323       // to a null pointer constant.
12324       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12325           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12326         return Error(E);
12327       // It's implementation-defined whether distinct literals will have
12328       // distinct addresses. In clang, the result of such a comparison is
12329       // unspecified, so it is not a constant expression. However, we do know
12330       // that the address of a literal will be non-null.
12331       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12332           LHSValue.Base && RHSValue.Base)
12333         return Error(E);
12334       // We can't tell whether weak symbols will end up pointing to the same
12335       // object.
12336       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12337         return Error(E);
12338       // We can't compare the address of the start of one object with the
12339       // past-the-end address of another object, per C++ DR1652.
12340       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12341            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12342           (RHSValue.Base && RHSValue.Offset.isZero() &&
12343            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12344         return Error(E);
12345       // We can't tell whether an object is at the same address as another
12346       // zero sized object.
12347       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12348           (LHSValue.Base && isZeroSized(RHSValue)))
12349         return Error(E);
12350       return Success(CmpResult::Unequal, E);
12351     }
12352 
12353     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12354     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12355 
12356     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12357     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12358 
12359     // C++11 [expr.rel]p3:
12360     //   Pointers to void (after pointer conversions) can be compared, with a
12361     //   result defined as follows: If both pointers represent the same
12362     //   address or are both the null pointer value, the result is true if the
12363     //   operator is <= or >= and false otherwise; otherwise the result is
12364     //   unspecified.
12365     // We interpret this as applying to pointers to *cv* void.
12366     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12367       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12368 
12369     // C++11 [expr.rel]p2:
12370     // - If two pointers point to non-static data members of the same object,
12371     //   or to subobjects or array elements fo such members, recursively, the
12372     //   pointer to the later declared member compares greater provided the
12373     //   two members have the same access control and provided their class is
12374     //   not a union.
12375     //   [...]
12376     // - Otherwise pointer comparisons are unspecified.
12377     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12378       bool WasArrayIndex;
12379       unsigned Mismatch = FindDesignatorMismatch(
12380           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12381       // At the point where the designators diverge, the comparison has a
12382       // specified value if:
12383       //  - we are comparing array indices
12384       //  - we are comparing fields of a union, or fields with the same access
12385       // Otherwise, the result is unspecified and thus the comparison is not a
12386       // constant expression.
12387       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12388           Mismatch < RHSDesignator.Entries.size()) {
12389         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12390         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12391         if (!LF && !RF)
12392           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12393         else if (!LF)
12394           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12395               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12396               << RF->getParent() << RF;
12397         else if (!RF)
12398           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12399               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12400               << LF->getParent() << LF;
12401         else if (!LF->getParent()->isUnion() &&
12402                  LF->getAccess() != RF->getAccess())
12403           Info.CCEDiag(E,
12404                        diag::note_constexpr_pointer_comparison_differing_access)
12405               << LF << LF->getAccess() << RF << RF->getAccess()
12406               << LF->getParent();
12407       }
12408     }
12409 
12410     // The comparison here must be unsigned, and performed with the same
12411     // width as the pointer.
12412     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12413     uint64_t CompareLHS = LHSOffset.getQuantity();
12414     uint64_t CompareRHS = RHSOffset.getQuantity();
12415     assert(PtrSize <= 64 && "Unexpected pointer width");
12416     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12417     CompareLHS &= Mask;
12418     CompareRHS &= Mask;
12419 
12420     // If there is a base and this is a relational operator, we can only
12421     // compare pointers within the object in question; otherwise, the result
12422     // depends on where the object is located in memory.
12423     if (!LHSValue.Base.isNull() && IsRelational) {
12424       QualType BaseTy = getType(LHSValue.Base);
12425       if (BaseTy->isIncompleteType())
12426         return Error(E);
12427       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12428       uint64_t OffsetLimit = Size.getQuantity();
12429       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12430         return Error(E);
12431     }
12432 
12433     if (CompareLHS < CompareRHS)
12434       return Success(CmpResult::Less, E);
12435     if (CompareLHS > CompareRHS)
12436       return Success(CmpResult::Greater, E);
12437     return Success(CmpResult::Equal, E);
12438   }
12439 
12440   if (LHSTy->isMemberPointerType()) {
12441     assert(IsEquality && "unexpected member pointer operation");
12442     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12443 
12444     MemberPtr LHSValue, RHSValue;
12445 
12446     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12447     if (!LHSOK && !Info.noteFailure())
12448       return false;
12449 
12450     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12451       return false;
12452 
12453     // C++11 [expr.eq]p2:
12454     //   If both operands are null, they compare equal. Otherwise if only one is
12455     //   null, they compare unequal.
12456     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12457       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12458       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12459     }
12460 
12461     //   Otherwise if either is a pointer to a virtual member function, the
12462     //   result is unspecified.
12463     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12464       if (MD->isVirtual())
12465         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12466     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12467       if (MD->isVirtual())
12468         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12469 
12470     //   Otherwise they compare equal if and only if they would refer to the
12471     //   same member of the same most derived object or the same subobject if
12472     //   they were dereferenced with a hypothetical object of the associated
12473     //   class type.
12474     bool Equal = LHSValue == RHSValue;
12475     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12476   }
12477 
12478   if (LHSTy->isNullPtrType()) {
12479     assert(E->isComparisonOp() && "unexpected nullptr operation");
12480     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12481     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12482     // are compared, the result is true of the operator is <=, >= or ==, and
12483     // false otherwise.
12484     return Success(CmpResult::Equal, E);
12485   }
12486 
12487   return DoAfter();
12488 }
12489 
12490 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12491   if (!CheckLiteralType(Info, E))
12492     return false;
12493 
12494   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12495     ComparisonCategoryResult CCR;
12496     switch (CR) {
12497     case CmpResult::Unequal:
12498       llvm_unreachable("should never produce Unequal for three-way comparison");
12499     case CmpResult::Less:
12500       CCR = ComparisonCategoryResult::Less;
12501       break;
12502     case CmpResult::Equal:
12503       CCR = ComparisonCategoryResult::Equal;
12504       break;
12505     case CmpResult::Greater:
12506       CCR = ComparisonCategoryResult::Greater;
12507       break;
12508     case CmpResult::Unordered:
12509       CCR = ComparisonCategoryResult::Unordered;
12510       break;
12511     }
12512     // Evaluation succeeded. Lookup the information for the comparison category
12513     // type and fetch the VarDecl for the result.
12514     const ComparisonCategoryInfo &CmpInfo =
12515         Info.Ctx.CompCategories.getInfoForType(E->getType());
12516     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12517     // Check and evaluate the result as a constant expression.
12518     LValue LV;
12519     LV.set(VD);
12520     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12521       return false;
12522     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12523   };
12524   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12525     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12526   });
12527 }
12528 
12529 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12530   // We don't call noteFailure immediately because the assignment happens after
12531   // we evaluate LHS and RHS.
12532   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12533     return Error(E);
12534 
12535   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12536   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12537     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12538 
12539   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12540           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12541          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12542 
12543   if (E->isComparisonOp()) {
12544     // Evaluate builtin binary comparisons by evaluating them as three-way
12545     // comparisons and then translating the result.
12546     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12547       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12548              "should only produce Unequal for equality comparisons");
12549       bool IsEqual   = CR == CmpResult::Equal,
12550            IsLess    = CR == CmpResult::Less,
12551            IsGreater = CR == CmpResult::Greater;
12552       auto Op = E->getOpcode();
12553       switch (Op) {
12554       default:
12555         llvm_unreachable("unsupported binary operator");
12556       case BO_EQ:
12557       case BO_NE:
12558         return Success(IsEqual == (Op == BO_EQ), E);
12559       case BO_LT:
12560         return Success(IsLess, E);
12561       case BO_GT:
12562         return Success(IsGreater, E);
12563       case BO_LE:
12564         return Success(IsEqual || IsLess, E);
12565       case BO_GE:
12566         return Success(IsEqual || IsGreater, E);
12567       }
12568     };
12569     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12570       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12571     });
12572   }
12573 
12574   QualType LHSTy = E->getLHS()->getType();
12575   QualType RHSTy = E->getRHS()->getType();
12576 
12577   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12578       E->getOpcode() == BO_Sub) {
12579     LValue LHSValue, RHSValue;
12580 
12581     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12582     if (!LHSOK && !Info.noteFailure())
12583       return false;
12584 
12585     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12586       return false;
12587 
12588     // Reject differing bases from the normal codepath; we special-case
12589     // comparisons to null.
12590     if (!HasSameBase(LHSValue, RHSValue)) {
12591       // Handle &&A - &&B.
12592       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12593         return Error(E);
12594       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12595       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12596       if (!LHSExpr || !RHSExpr)
12597         return Error(E);
12598       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12599       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12600       if (!LHSAddrExpr || !RHSAddrExpr)
12601         return Error(E);
12602       // Make sure both labels come from the same function.
12603       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12604           RHSAddrExpr->getLabel()->getDeclContext())
12605         return Error(E);
12606       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12607     }
12608     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12609     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12610 
12611     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12612     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12613 
12614     // C++11 [expr.add]p6:
12615     //   Unless both pointers point to elements of the same array object, or
12616     //   one past the last element of the array object, the behavior is
12617     //   undefined.
12618     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12619         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12620                                 RHSDesignator))
12621       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12622 
12623     QualType Type = E->getLHS()->getType();
12624     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12625 
12626     CharUnits ElementSize;
12627     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12628       return false;
12629 
12630     // As an extension, a type may have zero size (empty struct or union in
12631     // C, array of zero length). Pointer subtraction in such cases has
12632     // undefined behavior, so is not constant.
12633     if (ElementSize.isZero()) {
12634       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12635           << ElementType;
12636       return false;
12637     }
12638 
12639     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12640     // and produce incorrect results when it overflows. Such behavior
12641     // appears to be non-conforming, but is common, so perhaps we should
12642     // assume the standard intended for such cases to be undefined behavior
12643     // and check for them.
12644 
12645     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12646     // overflow in the final conversion to ptrdiff_t.
12647     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12648     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12649     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12650                     false);
12651     APSInt TrueResult = (LHS - RHS) / ElemSize;
12652     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12653 
12654     if (Result.extend(65) != TrueResult &&
12655         !HandleOverflow(Info, E, TrueResult, E->getType()))
12656       return false;
12657     return Success(Result, E);
12658   }
12659 
12660   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12661 }
12662 
12663 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12664 /// a result as the expression's type.
12665 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12666                                     const UnaryExprOrTypeTraitExpr *E) {
12667   switch(E->getKind()) {
12668   case UETT_PreferredAlignOf:
12669   case UETT_AlignOf: {
12670     if (E->isArgumentType())
12671       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12672                      E);
12673     else
12674       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12675                      E);
12676   }
12677 
12678   case UETT_VecStep: {
12679     QualType Ty = E->getTypeOfArgument();
12680 
12681     if (Ty->isVectorType()) {
12682       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12683 
12684       // The vec_step built-in functions that take a 3-component
12685       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12686       if (n == 3)
12687         n = 4;
12688 
12689       return Success(n, E);
12690     } else
12691       return Success(1, E);
12692   }
12693 
12694   case UETT_SizeOf: {
12695     QualType SrcTy = E->getTypeOfArgument();
12696     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12697     //   the result is the size of the referenced type."
12698     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12699       SrcTy = Ref->getPointeeType();
12700 
12701     CharUnits Sizeof;
12702     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12703       return false;
12704     return Success(Sizeof, E);
12705   }
12706   case UETT_OpenMPRequiredSimdAlign:
12707     assert(E->isArgumentType());
12708     return Success(
12709         Info.Ctx.toCharUnitsFromBits(
12710                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12711             .getQuantity(),
12712         E);
12713   }
12714 
12715   llvm_unreachable("unknown expr/type trait");
12716 }
12717 
12718 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12719   CharUnits Result;
12720   unsigned n = OOE->getNumComponents();
12721   if (n == 0)
12722     return Error(OOE);
12723   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12724   for (unsigned i = 0; i != n; ++i) {
12725     OffsetOfNode ON = OOE->getComponent(i);
12726     switch (ON.getKind()) {
12727     case OffsetOfNode::Array: {
12728       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12729       APSInt IdxResult;
12730       if (!EvaluateInteger(Idx, IdxResult, Info))
12731         return false;
12732       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12733       if (!AT)
12734         return Error(OOE);
12735       CurrentType = AT->getElementType();
12736       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12737       Result += IdxResult.getSExtValue() * ElementSize;
12738       break;
12739     }
12740 
12741     case OffsetOfNode::Field: {
12742       FieldDecl *MemberDecl = ON.getField();
12743       const RecordType *RT = CurrentType->getAs<RecordType>();
12744       if (!RT)
12745         return Error(OOE);
12746       RecordDecl *RD = RT->getDecl();
12747       if (RD->isInvalidDecl()) return false;
12748       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12749       unsigned i = MemberDecl->getFieldIndex();
12750       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12751       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12752       CurrentType = MemberDecl->getType().getNonReferenceType();
12753       break;
12754     }
12755 
12756     case OffsetOfNode::Identifier:
12757       llvm_unreachable("dependent __builtin_offsetof");
12758 
12759     case OffsetOfNode::Base: {
12760       CXXBaseSpecifier *BaseSpec = ON.getBase();
12761       if (BaseSpec->isVirtual())
12762         return Error(OOE);
12763 
12764       // Find the layout of the class whose base we are looking into.
12765       const RecordType *RT = CurrentType->getAs<RecordType>();
12766       if (!RT)
12767         return Error(OOE);
12768       RecordDecl *RD = RT->getDecl();
12769       if (RD->isInvalidDecl()) return false;
12770       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12771 
12772       // Find the base class itself.
12773       CurrentType = BaseSpec->getType();
12774       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12775       if (!BaseRT)
12776         return Error(OOE);
12777 
12778       // Add the offset to the base.
12779       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12780       break;
12781     }
12782     }
12783   }
12784   return Success(Result, OOE);
12785 }
12786 
12787 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12788   switch (E->getOpcode()) {
12789   default:
12790     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12791     // See C99 6.6p3.
12792     return Error(E);
12793   case UO_Extension:
12794     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12795     // If so, we could clear the diagnostic ID.
12796     return Visit(E->getSubExpr());
12797   case UO_Plus:
12798     // The result is just the value.
12799     return Visit(E->getSubExpr());
12800   case UO_Minus: {
12801     if (!Visit(E->getSubExpr()))
12802       return false;
12803     if (!Result.isInt()) return Error(E);
12804     const APSInt &Value = Result.getInt();
12805     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12806         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12807                         E->getType()))
12808       return false;
12809     return Success(-Value, E);
12810   }
12811   case UO_Not: {
12812     if (!Visit(E->getSubExpr()))
12813       return false;
12814     if (!Result.isInt()) return Error(E);
12815     return Success(~Result.getInt(), E);
12816   }
12817   case UO_LNot: {
12818     bool bres;
12819     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12820       return false;
12821     return Success(!bres, E);
12822   }
12823   }
12824 }
12825 
12826 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12827 /// result type is integer.
12828 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12829   const Expr *SubExpr = E->getSubExpr();
12830   QualType DestType = E->getType();
12831   QualType SrcType = SubExpr->getType();
12832 
12833   switch (E->getCastKind()) {
12834   case CK_BaseToDerived:
12835   case CK_DerivedToBase:
12836   case CK_UncheckedDerivedToBase:
12837   case CK_Dynamic:
12838   case CK_ToUnion:
12839   case CK_ArrayToPointerDecay:
12840   case CK_FunctionToPointerDecay:
12841   case CK_NullToPointer:
12842   case CK_NullToMemberPointer:
12843   case CK_BaseToDerivedMemberPointer:
12844   case CK_DerivedToBaseMemberPointer:
12845   case CK_ReinterpretMemberPointer:
12846   case CK_ConstructorConversion:
12847   case CK_IntegralToPointer:
12848   case CK_ToVoid:
12849   case CK_VectorSplat:
12850   case CK_IntegralToFloating:
12851   case CK_FloatingCast:
12852   case CK_CPointerToObjCPointerCast:
12853   case CK_BlockPointerToObjCPointerCast:
12854   case CK_AnyPointerToBlockPointerCast:
12855   case CK_ObjCObjectLValueCast:
12856   case CK_FloatingRealToComplex:
12857   case CK_FloatingComplexToReal:
12858   case CK_FloatingComplexCast:
12859   case CK_FloatingComplexToIntegralComplex:
12860   case CK_IntegralRealToComplex:
12861   case CK_IntegralComplexCast:
12862   case CK_IntegralComplexToFloatingComplex:
12863   case CK_BuiltinFnToFnPtr:
12864   case CK_ZeroToOCLOpaqueType:
12865   case CK_NonAtomicToAtomic:
12866   case CK_AddressSpaceConversion:
12867   case CK_IntToOCLSampler:
12868   case CK_FixedPointCast:
12869   case CK_IntegralToFixedPoint:
12870     llvm_unreachable("invalid cast kind for integral value");
12871 
12872   case CK_BitCast:
12873   case CK_Dependent:
12874   case CK_LValueBitCast:
12875   case CK_ARCProduceObject:
12876   case CK_ARCConsumeObject:
12877   case CK_ARCReclaimReturnedObject:
12878   case CK_ARCExtendBlockObject:
12879   case CK_CopyAndAutoreleaseBlockObject:
12880     return Error(E);
12881 
12882   case CK_UserDefinedConversion:
12883   case CK_LValueToRValue:
12884   case CK_AtomicToNonAtomic:
12885   case CK_NoOp:
12886   case CK_LValueToRValueBitCast:
12887     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12888 
12889   case CK_MemberPointerToBoolean:
12890   case CK_PointerToBoolean:
12891   case CK_IntegralToBoolean:
12892   case CK_FloatingToBoolean:
12893   case CK_BooleanToSignedIntegral:
12894   case CK_FloatingComplexToBoolean:
12895   case CK_IntegralComplexToBoolean: {
12896     bool BoolResult;
12897     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12898       return false;
12899     uint64_t IntResult = BoolResult;
12900     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12901       IntResult = (uint64_t)-1;
12902     return Success(IntResult, E);
12903   }
12904 
12905   case CK_FixedPointToIntegral: {
12906     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12907     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12908       return false;
12909     bool Overflowed;
12910     llvm::APSInt Result = Src.convertToInt(
12911         Info.Ctx.getIntWidth(DestType),
12912         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12913     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12914       return false;
12915     return Success(Result, E);
12916   }
12917 
12918   case CK_FixedPointToBoolean: {
12919     // Unsigned padding does not affect this.
12920     APValue Val;
12921     if (!Evaluate(Val, Info, SubExpr))
12922       return false;
12923     return Success(Val.getFixedPoint().getBoolValue(), E);
12924   }
12925 
12926   case CK_IntegralCast: {
12927     if (!Visit(SubExpr))
12928       return false;
12929 
12930     if (!Result.isInt()) {
12931       // Allow casts of address-of-label differences if they are no-ops
12932       // or narrowing.  (The narrowing case isn't actually guaranteed to
12933       // be constant-evaluatable except in some narrow cases which are hard
12934       // to detect here.  We let it through on the assumption the user knows
12935       // what they are doing.)
12936       if (Result.isAddrLabelDiff())
12937         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12938       // Only allow casts of lvalues if they are lossless.
12939       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12940     }
12941 
12942     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12943                                       Result.getInt()), E);
12944   }
12945 
12946   case CK_PointerToIntegral: {
12947     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12948 
12949     LValue LV;
12950     if (!EvaluatePointer(SubExpr, LV, Info))
12951       return false;
12952 
12953     if (LV.getLValueBase()) {
12954       // Only allow based lvalue casts if they are lossless.
12955       // FIXME: Allow a larger integer size than the pointer size, and allow
12956       // narrowing back down to pointer width in subsequent integral casts.
12957       // FIXME: Check integer type's active bits, not its type size.
12958       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12959         return Error(E);
12960 
12961       LV.Designator.setInvalid();
12962       LV.moveInto(Result);
12963       return true;
12964     }
12965 
12966     APSInt AsInt;
12967     APValue V;
12968     LV.moveInto(V);
12969     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12970       llvm_unreachable("Can't cast this!");
12971 
12972     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12973   }
12974 
12975   case CK_IntegralComplexToReal: {
12976     ComplexValue C;
12977     if (!EvaluateComplex(SubExpr, C, Info))
12978       return false;
12979     return Success(C.getComplexIntReal(), E);
12980   }
12981 
12982   case CK_FloatingToIntegral: {
12983     APFloat F(0.0);
12984     if (!EvaluateFloat(SubExpr, F, Info))
12985       return false;
12986 
12987     APSInt Value;
12988     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12989       return false;
12990     return Success(Value, E);
12991   }
12992   }
12993 
12994   llvm_unreachable("unknown cast resulting in integral value");
12995 }
12996 
12997 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12998   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12999     ComplexValue LV;
13000     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13001       return false;
13002     if (!LV.isComplexInt())
13003       return Error(E);
13004     return Success(LV.getComplexIntReal(), E);
13005   }
13006 
13007   return Visit(E->getSubExpr());
13008 }
13009 
13010 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13011   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13012     ComplexValue LV;
13013     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13014       return false;
13015     if (!LV.isComplexInt())
13016       return Error(E);
13017     return Success(LV.getComplexIntImag(), E);
13018   }
13019 
13020   VisitIgnoredValue(E->getSubExpr());
13021   return Success(0, E);
13022 }
13023 
13024 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13025   return Success(E->getPackLength(), E);
13026 }
13027 
13028 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13029   return Success(E->getValue(), E);
13030 }
13031 
13032 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13033        const ConceptSpecializationExpr *E) {
13034   return Success(E->isSatisfied(), E);
13035 }
13036 
13037 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13038   return Success(E->isSatisfied(), E);
13039 }
13040 
13041 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13042   switch (E->getOpcode()) {
13043     default:
13044       // Invalid unary operators
13045       return Error(E);
13046     case UO_Plus:
13047       // The result is just the value.
13048       return Visit(E->getSubExpr());
13049     case UO_Minus: {
13050       if (!Visit(E->getSubExpr())) return false;
13051       if (!Result.isFixedPoint())
13052         return Error(E);
13053       bool Overflowed;
13054       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13055       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13056         return false;
13057       return Success(Negated, E);
13058     }
13059     case UO_LNot: {
13060       bool bres;
13061       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13062         return false;
13063       return Success(!bres, E);
13064     }
13065   }
13066 }
13067 
13068 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13069   const Expr *SubExpr = E->getSubExpr();
13070   QualType DestType = E->getType();
13071   assert(DestType->isFixedPointType() &&
13072          "Expected destination type to be a fixed point type");
13073   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13074 
13075   switch (E->getCastKind()) {
13076   case CK_FixedPointCast: {
13077     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13078     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13079       return false;
13080     bool Overflowed;
13081     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13082     if (Overflowed) {
13083       if (Info.checkingForUndefinedBehavior())
13084         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13085                                          diag::warn_fixedpoint_constant_overflow)
13086           << Result.toString() << E->getType();
13087       else if (!HandleOverflow(Info, E, Result, E->getType()))
13088         return false;
13089     }
13090     return Success(Result, E);
13091   }
13092   case CK_IntegralToFixedPoint: {
13093     APSInt Src;
13094     if (!EvaluateInteger(SubExpr, Src, Info))
13095       return false;
13096 
13097     bool Overflowed;
13098     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13099         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13100 
13101     if (Overflowed) {
13102       if (Info.checkingForUndefinedBehavior())
13103         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13104                                          diag::warn_fixedpoint_constant_overflow)
13105           << IntResult.toString() << E->getType();
13106       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13107         return false;
13108     }
13109 
13110     return Success(IntResult, E);
13111   }
13112   case CK_NoOp:
13113   case CK_LValueToRValue:
13114     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13115   default:
13116     return Error(E);
13117   }
13118 }
13119 
13120 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13121   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13122     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13123 
13124   const Expr *LHS = E->getLHS();
13125   const Expr *RHS = E->getRHS();
13126   FixedPointSemantics ResultFXSema =
13127       Info.Ctx.getFixedPointSemantics(E->getType());
13128 
13129   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13130   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13131     return false;
13132   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13133   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13134     return false;
13135 
13136   bool OpOverflow = false, ConversionOverflow = false;
13137   APFixedPoint Result(LHSFX.getSemantics());
13138   switch (E->getOpcode()) {
13139   case BO_Add: {
13140     Result = LHSFX.add(RHSFX, &OpOverflow)
13141                   .convert(ResultFXSema, &ConversionOverflow);
13142     break;
13143   }
13144   case BO_Sub: {
13145     Result = LHSFX.sub(RHSFX, &OpOverflow)
13146                   .convert(ResultFXSema, &ConversionOverflow);
13147     break;
13148   }
13149   case BO_Mul: {
13150     Result = LHSFX.mul(RHSFX, &OpOverflow)
13151                   .convert(ResultFXSema, &ConversionOverflow);
13152     break;
13153   }
13154   case BO_Div: {
13155     if (RHSFX.getValue() == 0) {
13156       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13157       return false;
13158     }
13159     Result = LHSFX.div(RHSFX, &OpOverflow)
13160                   .convert(ResultFXSema, &ConversionOverflow);
13161     break;
13162   }
13163   case BO_Shl:
13164   case BO_Shr: {
13165     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13166     llvm::APSInt RHSVal = RHSFX.getValue();
13167 
13168     unsigned ShiftBW =
13169         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13170     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13171     // Embedded-C 4.1.6.2.2:
13172     //   The right operand must be nonnegative and less than the total number
13173     //   of (nonpadding) bits of the fixed-point operand ...
13174     if (RHSVal.isNegative())
13175       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13176     else if (Amt != RHSVal)
13177       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13178           << RHSVal << E->getType() << ShiftBW;
13179 
13180     if (E->getOpcode() == BO_Shl)
13181       Result = LHSFX.shl(Amt, &OpOverflow);
13182     else
13183       Result = LHSFX.shr(Amt, &OpOverflow);
13184     break;
13185   }
13186   default:
13187     return false;
13188   }
13189   if (OpOverflow || ConversionOverflow) {
13190     if (Info.checkingForUndefinedBehavior())
13191       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13192                                        diag::warn_fixedpoint_constant_overflow)
13193         << Result.toString() << E->getType();
13194     else if (!HandleOverflow(Info, E, Result, E->getType()))
13195       return false;
13196   }
13197   return Success(Result, E);
13198 }
13199 
13200 //===----------------------------------------------------------------------===//
13201 // Float Evaluation
13202 //===----------------------------------------------------------------------===//
13203 
13204 namespace {
13205 class FloatExprEvaluator
13206   : public ExprEvaluatorBase<FloatExprEvaluator> {
13207   APFloat &Result;
13208 public:
13209   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13210     : ExprEvaluatorBaseTy(info), Result(result) {}
13211 
13212   bool Success(const APValue &V, const Expr *e) {
13213     Result = V.getFloat();
13214     return true;
13215   }
13216 
13217   bool ZeroInitialization(const Expr *E) {
13218     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13219     return true;
13220   }
13221 
13222   bool VisitCallExpr(const CallExpr *E);
13223 
13224   bool VisitUnaryOperator(const UnaryOperator *E);
13225   bool VisitBinaryOperator(const BinaryOperator *E);
13226   bool VisitFloatingLiteral(const FloatingLiteral *E);
13227   bool VisitCastExpr(const CastExpr *E);
13228 
13229   bool VisitUnaryReal(const UnaryOperator *E);
13230   bool VisitUnaryImag(const UnaryOperator *E);
13231 
13232   // FIXME: Missing: array subscript of vector, member of vector
13233 };
13234 } // end anonymous namespace
13235 
13236 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13237   assert(E->isRValue() && E->getType()->isRealFloatingType());
13238   return FloatExprEvaluator(Info, Result).Visit(E);
13239 }
13240 
13241 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13242                                   QualType ResultTy,
13243                                   const Expr *Arg,
13244                                   bool SNaN,
13245                                   llvm::APFloat &Result) {
13246   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13247   if (!S) return false;
13248 
13249   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13250 
13251   llvm::APInt fill;
13252 
13253   // Treat empty strings as if they were zero.
13254   if (S->getString().empty())
13255     fill = llvm::APInt(32, 0);
13256   else if (S->getString().getAsInteger(0, fill))
13257     return false;
13258 
13259   if (Context.getTargetInfo().isNan2008()) {
13260     if (SNaN)
13261       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13262     else
13263       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13264   } else {
13265     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13266     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13267     // a different encoding to what became a standard in 2008, and for pre-
13268     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13269     // sNaN. This is now known as "legacy NaN" encoding.
13270     if (SNaN)
13271       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13272     else
13273       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13274   }
13275 
13276   return true;
13277 }
13278 
13279 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13280   switch (E->getBuiltinCallee()) {
13281   default:
13282     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13283 
13284   case Builtin::BI__builtin_huge_val:
13285   case Builtin::BI__builtin_huge_valf:
13286   case Builtin::BI__builtin_huge_vall:
13287   case Builtin::BI__builtin_huge_valf128:
13288   case Builtin::BI__builtin_inf:
13289   case Builtin::BI__builtin_inff:
13290   case Builtin::BI__builtin_infl:
13291   case Builtin::BI__builtin_inff128: {
13292     const llvm::fltSemantics &Sem =
13293       Info.Ctx.getFloatTypeSemantics(E->getType());
13294     Result = llvm::APFloat::getInf(Sem);
13295     return true;
13296   }
13297 
13298   case Builtin::BI__builtin_nans:
13299   case Builtin::BI__builtin_nansf:
13300   case Builtin::BI__builtin_nansl:
13301   case Builtin::BI__builtin_nansf128:
13302     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13303                                true, Result))
13304       return Error(E);
13305     return true;
13306 
13307   case Builtin::BI__builtin_nan:
13308   case Builtin::BI__builtin_nanf:
13309   case Builtin::BI__builtin_nanl:
13310   case Builtin::BI__builtin_nanf128:
13311     // If this is __builtin_nan() turn this into a nan, otherwise we
13312     // can't constant fold it.
13313     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13314                                false, Result))
13315       return Error(E);
13316     return true;
13317 
13318   case Builtin::BI__builtin_fabs:
13319   case Builtin::BI__builtin_fabsf:
13320   case Builtin::BI__builtin_fabsl:
13321   case Builtin::BI__builtin_fabsf128:
13322     if (!EvaluateFloat(E->getArg(0), Result, Info))
13323       return false;
13324 
13325     if (Result.isNegative())
13326       Result.changeSign();
13327     return true;
13328 
13329   // FIXME: Builtin::BI__builtin_powi
13330   // FIXME: Builtin::BI__builtin_powif
13331   // FIXME: Builtin::BI__builtin_powil
13332 
13333   case Builtin::BI__builtin_copysign:
13334   case Builtin::BI__builtin_copysignf:
13335   case Builtin::BI__builtin_copysignl:
13336   case Builtin::BI__builtin_copysignf128: {
13337     APFloat RHS(0.);
13338     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13339         !EvaluateFloat(E->getArg(1), RHS, Info))
13340       return false;
13341     Result.copySign(RHS);
13342     return true;
13343   }
13344   }
13345 }
13346 
13347 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13348   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13349     ComplexValue CV;
13350     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13351       return false;
13352     Result = CV.FloatReal;
13353     return true;
13354   }
13355 
13356   return Visit(E->getSubExpr());
13357 }
13358 
13359 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13360   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13361     ComplexValue CV;
13362     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13363       return false;
13364     Result = CV.FloatImag;
13365     return true;
13366   }
13367 
13368   VisitIgnoredValue(E->getSubExpr());
13369   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13370   Result = llvm::APFloat::getZero(Sem);
13371   return true;
13372 }
13373 
13374 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13375   switch (E->getOpcode()) {
13376   default: return Error(E);
13377   case UO_Plus:
13378     return EvaluateFloat(E->getSubExpr(), Result, Info);
13379   case UO_Minus:
13380     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13381       return false;
13382     Result.changeSign();
13383     return true;
13384   }
13385 }
13386 
13387 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13388   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13389     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13390 
13391   APFloat RHS(0.0);
13392   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13393   if (!LHSOK && !Info.noteFailure())
13394     return false;
13395   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13396          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13397 }
13398 
13399 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13400   Result = E->getValue();
13401   return true;
13402 }
13403 
13404 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13405   const Expr* SubExpr = E->getSubExpr();
13406 
13407   switch (E->getCastKind()) {
13408   default:
13409     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13410 
13411   case CK_IntegralToFloating: {
13412     APSInt IntResult;
13413     return EvaluateInteger(SubExpr, IntResult, Info) &&
13414            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
13415                                 E->getType(), Result);
13416   }
13417 
13418   case CK_FloatingCast: {
13419     if (!Visit(SubExpr))
13420       return false;
13421     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13422                                   Result);
13423   }
13424 
13425   case CK_FloatingComplexToReal: {
13426     ComplexValue V;
13427     if (!EvaluateComplex(SubExpr, V, Info))
13428       return false;
13429     Result = V.getComplexFloatReal();
13430     return true;
13431   }
13432   }
13433 }
13434 
13435 //===----------------------------------------------------------------------===//
13436 // Complex Evaluation (for float and integer)
13437 //===----------------------------------------------------------------------===//
13438 
13439 namespace {
13440 class ComplexExprEvaluator
13441   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13442   ComplexValue &Result;
13443 
13444 public:
13445   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13446     : ExprEvaluatorBaseTy(info), Result(Result) {}
13447 
13448   bool Success(const APValue &V, const Expr *e) {
13449     Result.setFrom(V);
13450     return true;
13451   }
13452 
13453   bool ZeroInitialization(const Expr *E);
13454 
13455   //===--------------------------------------------------------------------===//
13456   //                            Visitor Methods
13457   //===--------------------------------------------------------------------===//
13458 
13459   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13460   bool VisitCastExpr(const CastExpr *E);
13461   bool VisitBinaryOperator(const BinaryOperator *E);
13462   bool VisitUnaryOperator(const UnaryOperator *E);
13463   bool VisitInitListExpr(const InitListExpr *E);
13464   bool VisitCallExpr(const CallExpr *E);
13465 };
13466 } // end anonymous namespace
13467 
13468 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13469                             EvalInfo &Info) {
13470   assert(E->isRValue() && E->getType()->isAnyComplexType());
13471   return ComplexExprEvaluator(Info, Result).Visit(E);
13472 }
13473 
13474 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13475   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13476   if (ElemTy->isRealFloatingType()) {
13477     Result.makeComplexFloat();
13478     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13479     Result.FloatReal = Zero;
13480     Result.FloatImag = Zero;
13481   } else {
13482     Result.makeComplexInt();
13483     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13484     Result.IntReal = Zero;
13485     Result.IntImag = Zero;
13486   }
13487   return true;
13488 }
13489 
13490 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13491   const Expr* SubExpr = E->getSubExpr();
13492 
13493   if (SubExpr->getType()->isRealFloatingType()) {
13494     Result.makeComplexFloat();
13495     APFloat &Imag = Result.FloatImag;
13496     if (!EvaluateFloat(SubExpr, Imag, Info))
13497       return false;
13498 
13499     Result.FloatReal = APFloat(Imag.getSemantics());
13500     return true;
13501   } else {
13502     assert(SubExpr->getType()->isIntegerType() &&
13503            "Unexpected imaginary literal.");
13504 
13505     Result.makeComplexInt();
13506     APSInt &Imag = Result.IntImag;
13507     if (!EvaluateInteger(SubExpr, Imag, Info))
13508       return false;
13509 
13510     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13511     return true;
13512   }
13513 }
13514 
13515 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13516 
13517   switch (E->getCastKind()) {
13518   case CK_BitCast:
13519   case CK_BaseToDerived:
13520   case CK_DerivedToBase:
13521   case CK_UncheckedDerivedToBase:
13522   case CK_Dynamic:
13523   case CK_ToUnion:
13524   case CK_ArrayToPointerDecay:
13525   case CK_FunctionToPointerDecay:
13526   case CK_NullToPointer:
13527   case CK_NullToMemberPointer:
13528   case CK_BaseToDerivedMemberPointer:
13529   case CK_DerivedToBaseMemberPointer:
13530   case CK_MemberPointerToBoolean:
13531   case CK_ReinterpretMemberPointer:
13532   case CK_ConstructorConversion:
13533   case CK_IntegralToPointer:
13534   case CK_PointerToIntegral:
13535   case CK_PointerToBoolean:
13536   case CK_ToVoid:
13537   case CK_VectorSplat:
13538   case CK_IntegralCast:
13539   case CK_BooleanToSignedIntegral:
13540   case CK_IntegralToBoolean:
13541   case CK_IntegralToFloating:
13542   case CK_FloatingToIntegral:
13543   case CK_FloatingToBoolean:
13544   case CK_FloatingCast:
13545   case CK_CPointerToObjCPointerCast:
13546   case CK_BlockPointerToObjCPointerCast:
13547   case CK_AnyPointerToBlockPointerCast:
13548   case CK_ObjCObjectLValueCast:
13549   case CK_FloatingComplexToReal:
13550   case CK_FloatingComplexToBoolean:
13551   case CK_IntegralComplexToReal:
13552   case CK_IntegralComplexToBoolean:
13553   case CK_ARCProduceObject:
13554   case CK_ARCConsumeObject:
13555   case CK_ARCReclaimReturnedObject:
13556   case CK_ARCExtendBlockObject:
13557   case CK_CopyAndAutoreleaseBlockObject:
13558   case CK_BuiltinFnToFnPtr:
13559   case CK_ZeroToOCLOpaqueType:
13560   case CK_NonAtomicToAtomic:
13561   case CK_AddressSpaceConversion:
13562   case CK_IntToOCLSampler:
13563   case CK_FixedPointCast:
13564   case CK_FixedPointToBoolean:
13565   case CK_FixedPointToIntegral:
13566   case CK_IntegralToFixedPoint:
13567     llvm_unreachable("invalid cast kind for complex value");
13568 
13569   case CK_LValueToRValue:
13570   case CK_AtomicToNonAtomic:
13571   case CK_NoOp:
13572   case CK_LValueToRValueBitCast:
13573     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13574 
13575   case CK_Dependent:
13576   case CK_LValueBitCast:
13577   case CK_UserDefinedConversion:
13578     return Error(E);
13579 
13580   case CK_FloatingRealToComplex: {
13581     APFloat &Real = Result.FloatReal;
13582     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13583       return false;
13584 
13585     Result.makeComplexFloat();
13586     Result.FloatImag = APFloat(Real.getSemantics());
13587     return true;
13588   }
13589 
13590   case CK_FloatingComplexCast: {
13591     if (!Visit(E->getSubExpr()))
13592       return false;
13593 
13594     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13595     QualType From
13596       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13597 
13598     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13599            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13600   }
13601 
13602   case CK_FloatingComplexToIntegralComplex: {
13603     if (!Visit(E->getSubExpr()))
13604       return false;
13605 
13606     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13607     QualType From
13608       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13609     Result.makeComplexInt();
13610     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13611                                 To, Result.IntReal) &&
13612            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13613                                 To, Result.IntImag);
13614   }
13615 
13616   case CK_IntegralRealToComplex: {
13617     APSInt &Real = Result.IntReal;
13618     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13619       return false;
13620 
13621     Result.makeComplexInt();
13622     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13623     return true;
13624   }
13625 
13626   case CK_IntegralComplexCast: {
13627     if (!Visit(E->getSubExpr()))
13628       return false;
13629 
13630     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13631     QualType From
13632       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13633 
13634     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13635     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13636     return true;
13637   }
13638 
13639   case CK_IntegralComplexToFloatingComplex: {
13640     if (!Visit(E->getSubExpr()))
13641       return false;
13642 
13643     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13644     QualType From
13645       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13646     Result.makeComplexFloat();
13647     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13648                                 To, Result.FloatReal) &&
13649            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13650                                 To, Result.FloatImag);
13651   }
13652   }
13653 
13654   llvm_unreachable("unknown cast resulting in complex value");
13655 }
13656 
13657 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13658   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13659     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13660 
13661   // Track whether the LHS or RHS is real at the type system level. When this is
13662   // the case we can simplify our evaluation strategy.
13663   bool LHSReal = false, RHSReal = false;
13664 
13665   bool LHSOK;
13666   if (E->getLHS()->getType()->isRealFloatingType()) {
13667     LHSReal = true;
13668     APFloat &Real = Result.FloatReal;
13669     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13670     if (LHSOK) {
13671       Result.makeComplexFloat();
13672       Result.FloatImag = APFloat(Real.getSemantics());
13673     }
13674   } else {
13675     LHSOK = Visit(E->getLHS());
13676   }
13677   if (!LHSOK && !Info.noteFailure())
13678     return false;
13679 
13680   ComplexValue RHS;
13681   if (E->getRHS()->getType()->isRealFloatingType()) {
13682     RHSReal = true;
13683     APFloat &Real = RHS.FloatReal;
13684     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13685       return false;
13686     RHS.makeComplexFloat();
13687     RHS.FloatImag = APFloat(Real.getSemantics());
13688   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13689     return false;
13690 
13691   assert(!(LHSReal && RHSReal) &&
13692          "Cannot have both operands of a complex operation be real.");
13693   switch (E->getOpcode()) {
13694   default: return Error(E);
13695   case BO_Add:
13696     if (Result.isComplexFloat()) {
13697       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13698                                        APFloat::rmNearestTiesToEven);
13699       if (LHSReal)
13700         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13701       else if (!RHSReal)
13702         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13703                                          APFloat::rmNearestTiesToEven);
13704     } else {
13705       Result.getComplexIntReal() += RHS.getComplexIntReal();
13706       Result.getComplexIntImag() += RHS.getComplexIntImag();
13707     }
13708     break;
13709   case BO_Sub:
13710     if (Result.isComplexFloat()) {
13711       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13712                                             APFloat::rmNearestTiesToEven);
13713       if (LHSReal) {
13714         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13715         Result.getComplexFloatImag().changeSign();
13716       } else if (!RHSReal) {
13717         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13718                                               APFloat::rmNearestTiesToEven);
13719       }
13720     } else {
13721       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13722       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13723     }
13724     break;
13725   case BO_Mul:
13726     if (Result.isComplexFloat()) {
13727       // This is an implementation of complex multiplication according to the
13728       // constraints laid out in C11 Annex G. The implementation uses the
13729       // following naming scheme:
13730       //   (a + ib) * (c + id)
13731       ComplexValue LHS = Result;
13732       APFloat &A = LHS.getComplexFloatReal();
13733       APFloat &B = LHS.getComplexFloatImag();
13734       APFloat &C = RHS.getComplexFloatReal();
13735       APFloat &D = RHS.getComplexFloatImag();
13736       APFloat &ResR = Result.getComplexFloatReal();
13737       APFloat &ResI = Result.getComplexFloatImag();
13738       if (LHSReal) {
13739         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13740         ResR = A * C;
13741         ResI = A * D;
13742       } else if (RHSReal) {
13743         ResR = C * A;
13744         ResI = C * B;
13745       } else {
13746         // In the fully general case, we need to handle NaNs and infinities
13747         // robustly.
13748         APFloat AC = A * C;
13749         APFloat BD = B * D;
13750         APFloat AD = A * D;
13751         APFloat BC = B * C;
13752         ResR = AC - BD;
13753         ResI = AD + BC;
13754         if (ResR.isNaN() && ResI.isNaN()) {
13755           bool Recalc = false;
13756           if (A.isInfinity() || B.isInfinity()) {
13757             A = APFloat::copySign(
13758                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13759             B = APFloat::copySign(
13760                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13761             if (C.isNaN())
13762               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13763             if (D.isNaN())
13764               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13765             Recalc = true;
13766           }
13767           if (C.isInfinity() || D.isInfinity()) {
13768             C = APFloat::copySign(
13769                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13770             D = APFloat::copySign(
13771                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13772             if (A.isNaN())
13773               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13774             if (B.isNaN())
13775               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13776             Recalc = true;
13777           }
13778           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13779                           AD.isInfinity() || BC.isInfinity())) {
13780             if (A.isNaN())
13781               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13782             if (B.isNaN())
13783               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13784             if (C.isNaN())
13785               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13786             if (D.isNaN())
13787               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13788             Recalc = true;
13789           }
13790           if (Recalc) {
13791             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13792             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13793           }
13794         }
13795       }
13796     } else {
13797       ComplexValue LHS = Result;
13798       Result.getComplexIntReal() =
13799         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13800          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13801       Result.getComplexIntImag() =
13802         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13803          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13804     }
13805     break;
13806   case BO_Div:
13807     if (Result.isComplexFloat()) {
13808       // This is an implementation of complex division according to the
13809       // constraints laid out in C11 Annex G. The implementation uses the
13810       // following naming scheme:
13811       //   (a + ib) / (c + id)
13812       ComplexValue LHS = Result;
13813       APFloat &A = LHS.getComplexFloatReal();
13814       APFloat &B = LHS.getComplexFloatImag();
13815       APFloat &C = RHS.getComplexFloatReal();
13816       APFloat &D = RHS.getComplexFloatImag();
13817       APFloat &ResR = Result.getComplexFloatReal();
13818       APFloat &ResI = Result.getComplexFloatImag();
13819       if (RHSReal) {
13820         ResR = A / C;
13821         ResI = B / C;
13822       } else {
13823         if (LHSReal) {
13824           // No real optimizations we can do here, stub out with zero.
13825           B = APFloat::getZero(A.getSemantics());
13826         }
13827         int DenomLogB = 0;
13828         APFloat MaxCD = maxnum(abs(C), abs(D));
13829         if (MaxCD.isFinite()) {
13830           DenomLogB = ilogb(MaxCD);
13831           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13832           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13833         }
13834         APFloat Denom = C * C + D * D;
13835         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13836                       APFloat::rmNearestTiesToEven);
13837         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13838                       APFloat::rmNearestTiesToEven);
13839         if (ResR.isNaN() && ResI.isNaN()) {
13840           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13841             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13842             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13843           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13844                      D.isFinite()) {
13845             A = APFloat::copySign(
13846                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13847             B = APFloat::copySign(
13848                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13849             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13850             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13851           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13852             C = APFloat::copySign(
13853                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13854             D = APFloat::copySign(
13855                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13856             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13857             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13858           }
13859         }
13860       }
13861     } else {
13862       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13863         return Error(E, diag::note_expr_divide_by_zero);
13864 
13865       ComplexValue LHS = Result;
13866       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13867         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13868       Result.getComplexIntReal() =
13869         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13870          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13871       Result.getComplexIntImag() =
13872         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13873          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13874     }
13875     break;
13876   }
13877 
13878   return true;
13879 }
13880 
13881 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13882   // Get the operand value into 'Result'.
13883   if (!Visit(E->getSubExpr()))
13884     return false;
13885 
13886   switch (E->getOpcode()) {
13887   default:
13888     return Error(E);
13889   case UO_Extension:
13890     return true;
13891   case UO_Plus:
13892     // The result is always just the subexpr.
13893     return true;
13894   case UO_Minus:
13895     if (Result.isComplexFloat()) {
13896       Result.getComplexFloatReal().changeSign();
13897       Result.getComplexFloatImag().changeSign();
13898     }
13899     else {
13900       Result.getComplexIntReal() = -Result.getComplexIntReal();
13901       Result.getComplexIntImag() = -Result.getComplexIntImag();
13902     }
13903     return true;
13904   case UO_Not:
13905     if (Result.isComplexFloat())
13906       Result.getComplexFloatImag().changeSign();
13907     else
13908       Result.getComplexIntImag() = -Result.getComplexIntImag();
13909     return true;
13910   }
13911 }
13912 
13913 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13914   if (E->getNumInits() == 2) {
13915     if (E->getType()->isComplexType()) {
13916       Result.makeComplexFloat();
13917       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13918         return false;
13919       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13920         return false;
13921     } else {
13922       Result.makeComplexInt();
13923       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13924         return false;
13925       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13926         return false;
13927     }
13928     return true;
13929   }
13930   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13931 }
13932 
13933 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
13934   switch (E->getBuiltinCallee()) {
13935   case Builtin::BI__builtin_complex:
13936     Result.makeComplexFloat();
13937     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
13938       return false;
13939     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
13940       return false;
13941     return true;
13942 
13943   default:
13944     break;
13945   }
13946 
13947   return ExprEvaluatorBaseTy::VisitCallExpr(E);
13948 }
13949 
13950 //===----------------------------------------------------------------------===//
13951 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13952 // implicit conversion.
13953 //===----------------------------------------------------------------------===//
13954 
13955 namespace {
13956 class AtomicExprEvaluator :
13957     public ExprEvaluatorBase<AtomicExprEvaluator> {
13958   const LValue *This;
13959   APValue &Result;
13960 public:
13961   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13962       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13963 
13964   bool Success(const APValue &V, const Expr *E) {
13965     Result = V;
13966     return true;
13967   }
13968 
13969   bool ZeroInitialization(const Expr *E) {
13970     ImplicitValueInitExpr VIE(
13971         E->getType()->castAs<AtomicType>()->getValueType());
13972     // For atomic-qualified class (and array) types in C++, initialize the
13973     // _Atomic-wrapped subobject directly, in-place.
13974     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13975                 : Evaluate(Result, Info, &VIE);
13976   }
13977 
13978   bool VisitCastExpr(const CastExpr *E) {
13979     switch (E->getCastKind()) {
13980     default:
13981       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13982     case CK_NonAtomicToAtomic:
13983       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13984                   : Evaluate(Result, Info, E->getSubExpr());
13985     }
13986   }
13987 };
13988 } // end anonymous namespace
13989 
13990 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13991                            EvalInfo &Info) {
13992   assert(E->isRValue() && E->getType()->isAtomicType());
13993   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13994 }
13995 
13996 //===----------------------------------------------------------------------===//
13997 // Void expression evaluation, primarily for a cast to void on the LHS of a
13998 // comma operator
13999 //===----------------------------------------------------------------------===//
14000 
14001 namespace {
14002 class VoidExprEvaluator
14003   : public ExprEvaluatorBase<VoidExprEvaluator> {
14004 public:
14005   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14006 
14007   bool Success(const APValue &V, const Expr *e) { return true; }
14008 
14009   bool ZeroInitialization(const Expr *E) { return true; }
14010 
14011   bool VisitCastExpr(const CastExpr *E) {
14012     switch (E->getCastKind()) {
14013     default:
14014       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14015     case CK_ToVoid:
14016       VisitIgnoredValue(E->getSubExpr());
14017       return true;
14018     }
14019   }
14020 
14021   bool VisitCallExpr(const CallExpr *E) {
14022     switch (E->getBuiltinCallee()) {
14023     case Builtin::BI__assume:
14024     case Builtin::BI__builtin_assume:
14025       // The argument is not evaluated!
14026       return true;
14027 
14028     case Builtin::BI__builtin_operator_delete:
14029       return HandleOperatorDeleteCall(Info, E);
14030 
14031     default:
14032       break;
14033     }
14034 
14035     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14036   }
14037 
14038   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14039 };
14040 } // end anonymous namespace
14041 
14042 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14043   // We cannot speculatively evaluate a delete expression.
14044   if (Info.SpeculativeEvaluationDepth)
14045     return false;
14046 
14047   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14048   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14049     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14050         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14051     return false;
14052   }
14053 
14054   const Expr *Arg = E->getArgument();
14055 
14056   LValue Pointer;
14057   if (!EvaluatePointer(Arg, Pointer, Info))
14058     return false;
14059   if (Pointer.Designator.Invalid)
14060     return false;
14061 
14062   // Deleting a null pointer has no effect.
14063   if (Pointer.isNullPointer()) {
14064     // This is the only case where we need to produce an extension warning:
14065     // the only other way we can succeed is if we find a dynamic allocation,
14066     // and we will have warned when we allocated it in that case.
14067     if (!Info.getLangOpts().CPlusPlus20)
14068       Info.CCEDiag(E, diag::note_constexpr_new);
14069     return true;
14070   }
14071 
14072   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14073       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14074   if (!Alloc)
14075     return false;
14076   QualType AllocType = Pointer.Base.getDynamicAllocType();
14077 
14078   // For the non-array case, the designator must be empty if the static type
14079   // does not have a virtual destructor.
14080   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14081       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14082     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14083         << Arg->getType()->getPointeeType() << AllocType;
14084     return false;
14085   }
14086 
14087   // For a class type with a virtual destructor, the selected operator delete
14088   // is the one looked up when building the destructor.
14089   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14090     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14091     if (VirtualDelete &&
14092         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14093       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14094           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14095       return false;
14096     }
14097   }
14098 
14099   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14100                          (*Alloc)->Value, AllocType))
14101     return false;
14102 
14103   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14104     // The element was already erased. This means the destructor call also
14105     // deleted the object.
14106     // FIXME: This probably results in undefined behavior before we get this
14107     // far, and should be diagnosed elsewhere first.
14108     Info.FFDiag(E, diag::note_constexpr_double_delete);
14109     return false;
14110   }
14111 
14112   return true;
14113 }
14114 
14115 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14116   assert(E->isRValue() && E->getType()->isVoidType());
14117   return VoidExprEvaluator(Info).Visit(E);
14118 }
14119 
14120 //===----------------------------------------------------------------------===//
14121 // Top level Expr::EvaluateAsRValue method.
14122 //===----------------------------------------------------------------------===//
14123 
14124 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14125   // In C, function designators are not lvalues, but we evaluate them as if they
14126   // are.
14127   QualType T = E->getType();
14128   if (E->isGLValue() || T->isFunctionType()) {
14129     LValue LV;
14130     if (!EvaluateLValue(E, LV, Info))
14131       return false;
14132     LV.moveInto(Result);
14133   } else if (T->isVectorType()) {
14134     if (!EvaluateVector(E, Result, Info))
14135       return false;
14136   } else if (T->isIntegralOrEnumerationType()) {
14137     if (!IntExprEvaluator(Info, Result).Visit(E))
14138       return false;
14139   } else if (T->hasPointerRepresentation()) {
14140     LValue LV;
14141     if (!EvaluatePointer(E, LV, Info))
14142       return false;
14143     LV.moveInto(Result);
14144   } else if (T->isRealFloatingType()) {
14145     llvm::APFloat F(0.0);
14146     if (!EvaluateFloat(E, F, Info))
14147       return false;
14148     Result = APValue(F);
14149   } else if (T->isAnyComplexType()) {
14150     ComplexValue C;
14151     if (!EvaluateComplex(E, C, Info))
14152       return false;
14153     C.moveInto(Result);
14154   } else if (T->isFixedPointType()) {
14155     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14156   } else if (T->isMemberPointerType()) {
14157     MemberPtr P;
14158     if (!EvaluateMemberPointer(E, P, Info))
14159       return false;
14160     P.moveInto(Result);
14161     return true;
14162   } else if (T->isArrayType()) {
14163     LValue LV;
14164     APValue &Value =
14165         Info.CurrentCall->createTemporary(E, T, false, LV);
14166     if (!EvaluateArray(E, LV, Value, Info))
14167       return false;
14168     Result = Value;
14169   } else if (T->isRecordType()) {
14170     LValue LV;
14171     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
14172     if (!EvaluateRecord(E, LV, Value, Info))
14173       return false;
14174     Result = Value;
14175   } else if (T->isVoidType()) {
14176     if (!Info.getLangOpts().CPlusPlus11)
14177       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14178         << E->getType();
14179     if (!EvaluateVoid(E, Info))
14180       return false;
14181   } else if (T->isAtomicType()) {
14182     QualType Unqual = T.getAtomicUnqualifiedType();
14183     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14184       LValue LV;
14185       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
14186       if (!EvaluateAtomic(E, &LV, Value, Info))
14187         return false;
14188     } else {
14189       if (!EvaluateAtomic(E, nullptr, Result, Info))
14190         return false;
14191     }
14192   } else if (Info.getLangOpts().CPlusPlus11) {
14193     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14194     return false;
14195   } else {
14196     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14197     return false;
14198   }
14199 
14200   return true;
14201 }
14202 
14203 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14204 /// cases, the in-place evaluation is essential, since later initializers for
14205 /// an object can indirectly refer to subobjects which were initialized earlier.
14206 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14207                             const Expr *E, bool AllowNonLiteralTypes) {
14208   assert(!E->isValueDependent());
14209 
14210   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14211     return false;
14212 
14213   if (E->isRValue()) {
14214     // Evaluate arrays and record types in-place, so that later initializers can
14215     // refer to earlier-initialized members of the object.
14216     QualType T = E->getType();
14217     if (T->isArrayType())
14218       return EvaluateArray(E, This, Result, Info);
14219     else if (T->isRecordType())
14220       return EvaluateRecord(E, This, Result, Info);
14221     else if (T->isAtomicType()) {
14222       QualType Unqual = T.getAtomicUnqualifiedType();
14223       if (Unqual->isArrayType() || Unqual->isRecordType())
14224         return EvaluateAtomic(E, &This, Result, Info);
14225     }
14226   }
14227 
14228   // For any other type, in-place evaluation is unimportant.
14229   return Evaluate(Result, Info, E);
14230 }
14231 
14232 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14233 /// lvalue-to-rvalue cast if it is an lvalue.
14234 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14235   if (Info.EnableNewConstInterp) {
14236     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14237       return false;
14238   } else {
14239     if (E->getType().isNull())
14240       return false;
14241 
14242     if (!CheckLiteralType(Info, E))
14243       return false;
14244 
14245     if (!::Evaluate(Result, Info, E))
14246       return false;
14247 
14248     if (E->isGLValue()) {
14249       LValue LV;
14250       LV.setFrom(Info.Ctx, Result);
14251       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14252         return false;
14253     }
14254   }
14255 
14256   // Check this core constant expression is a constant expression.
14257   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
14258          CheckMemoryLeaks(Info);
14259 }
14260 
14261 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14262                                  const ASTContext &Ctx, bool &IsConst) {
14263   // Fast-path evaluations of integer literals, since we sometimes see files
14264   // containing vast quantities of these.
14265   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14266     Result.Val = APValue(APSInt(L->getValue(),
14267                                 L->getType()->isUnsignedIntegerType()));
14268     IsConst = true;
14269     return true;
14270   }
14271 
14272   // This case should be rare, but we need to check it before we check on
14273   // the type below.
14274   if (Exp->getType().isNull()) {
14275     IsConst = false;
14276     return true;
14277   }
14278 
14279   // FIXME: Evaluating values of large array and record types can cause
14280   // performance problems. Only do so in C++11 for now.
14281   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14282                           Exp->getType()->isRecordType()) &&
14283       !Ctx.getLangOpts().CPlusPlus11) {
14284     IsConst = false;
14285     return true;
14286   }
14287   return false;
14288 }
14289 
14290 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14291                                       Expr::SideEffectsKind SEK) {
14292   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14293          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14294 }
14295 
14296 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14297                              const ASTContext &Ctx, EvalInfo &Info) {
14298   bool IsConst;
14299   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14300     return IsConst;
14301 
14302   return EvaluateAsRValue(Info, E, Result.Val);
14303 }
14304 
14305 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14306                           const ASTContext &Ctx,
14307                           Expr::SideEffectsKind AllowSideEffects,
14308                           EvalInfo &Info) {
14309   if (!E->getType()->isIntegralOrEnumerationType())
14310     return false;
14311 
14312   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14313       !ExprResult.Val.isInt() ||
14314       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14315     return false;
14316 
14317   return true;
14318 }
14319 
14320 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14321                                  const ASTContext &Ctx,
14322                                  Expr::SideEffectsKind AllowSideEffects,
14323                                  EvalInfo &Info) {
14324   if (!E->getType()->isFixedPointType())
14325     return false;
14326 
14327   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14328     return false;
14329 
14330   if (!ExprResult.Val.isFixedPoint() ||
14331       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14332     return false;
14333 
14334   return true;
14335 }
14336 
14337 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14338 /// any crazy technique (that has nothing to do with language standards) that
14339 /// we want to.  If this function returns true, it returns the folded constant
14340 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14341 /// will be applied to the result.
14342 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14343                             bool InConstantContext) const {
14344   assert(!isValueDependent() &&
14345          "Expression evaluator can't be called on a dependent expression.");
14346   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14347   Info.InConstantContext = InConstantContext;
14348   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14349 }
14350 
14351 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14352                                       bool InConstantContext) const {
14353   assert(!isValueDependent() &&
14354          "Expression evaluator can't be called on a dependent expression.");
14355   EvalResult Scratch;
14356   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14357          HandleConversionToBool(Scratch.Val, Result);
14358 }
14359 
14360 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14361                          SideEffectsKind AllowSideEffects,
14362                          bool InConstantContext) const {
14363   assert(!isValueDependent() &&
14364          "Expression evaluator can't be called on a dependent expression.");
14365   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14366   Info.InConstantContext = InConstantContext;
14367   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14368 }
14369 
14370 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14371                                 SideEffectsKind AllowSideEffects,
14372                                 bool InConstantContext) const {
14373   assert(!isValueDependent() &&
14374          "Expression evaluator can't be called on a dependent expression.");
14375   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14376   Info.InConstantContext = InConstantContext;
14377   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14378 }
14379 
14380 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14381                            SideEffectsKind AllowSideEffects,
14382                            bool InConstantContext) const {
14383   assert(!isValueDependent() &&
14384          "Expression evaluator can't be called on a dependent expression.");
14385 
14386   if (!getType()->isRealFloatingType())
14387     return false;
14388 
14389   EvalResult ExprResult;
14390   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14391       !ExprResult.Val.isFloat() ||
14392       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14393     return false;
14394 
14395   Result = ExprResult.Val.getFloat();
14396   return true;
14397 }
14398 
14399 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14400                             bool InConstantContext) const {
14401   assert(!isValueDependent() &&
14402          "Expression evaluator can't be called on a dependent expression.");
14403 
14404   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14405   Info.InConstantContext = InConstantContext;
14406   LValue LV;
14407   CheckedTemporaries CheckedTemps;
14408   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14409       Result.HasSideEffects ||
14410       !CheckLValueConstantExpression(Info, getExprLoc(),
14411                                      Ctx.getLValueReferenceType(getType()), LV,
14412                                      Expr::EvaluateForCodeGen, CheckedTemps))
14413     return false;
14414 
14415   LV.moveInto(Result.Val);
14416   return true;
14417 }
14418 
14419 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
14420                                   const ASTContext &Ctx, bool InPlace) const {
14421   assert(!isValueDependent() &&
14422          "Expression evaluator can't be called on a dependent expression.");
14423 
14424   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14425   EvalInfo Info(Ctx, Result, EM);
14426   Info.InConstantContext = true;
14427 
14428   if (InPlace) {
14429     Info.setEvaluatingDecl(this, Result.Val);
14430     LValue LVal;
14431     LVal.set(this);
14432     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
14433         Result.HasSideEffects)
14434       return false;
14435   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
14436     return false;
14437 
14438   if (!Info.discardCleanups())
14439     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14440 
14441   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14442                                  Result.Val, Usage) &&
14443          CheckMemoryLeaks(Info);
14444 }
14445 
14446 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14447                                  const VarDecl *VD,
14448                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14449   assert(!isValueDependent() &&
14450          "Expression evaluator can't be called on a dependent expression.");
14451 
14452   // FIXME: Evaluating initializers for large array and record types can cause
14453   // performance problems. Only do so in C++11 for now.
14454   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14455       !Ctx.getLangOpts().CPlusPlus11)
14456     return false;
14457 
14458   Expr::EvalStatus EStatus;
14459   EStatus.Diag = &Notes;
14460 
14461   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
14462                                       ? EvalInfo::EM_ConstantExpression
14463                                       : EvalInfo::EM_ConstantFold);
14464   Info.setEvaluatingDecl(VD, Value);
14465   Info.InConstantContext = true;
14466 
14467   SourceLocation DeclLoc = VD->getLocation();
14468   QualType DeclTy = VD->getType();
14469 
14470   if (Info.EnableNewConstInterp) {
14471     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14472     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14473       return false;
14474   } else {
14475     LValue LVal;
14476     LVal.set(VD);
14477 
14478     if (!EvaluateInPlace(Value, Info, LVal, this,
14479                          /*AllowNonLiteralTypes=*/true) ||
14480         EStatus.HasSideEffects)
14481       return false;
14482 
14483     // At this point, any lifetime-extended temporaries are completely
14484     // initialized.
14485     Info.performLifetimeExtension();
14486 
14487     if (!Info.discardCleanups())
14488       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14489   }
14490   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
14491          CheckMemoryLeaks(Info);
14492 }
14493 
14494 bool VarDecl::evaluateDestruction(
14495     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14496   Expr::EvalStatus EStatus;
14497   EStatus.Diag = &Notes;
14498 
14499   // Make a copy of the value for the destructor to mutate, if we know it.
14500   // Otherwise, treat the value as default-initialized; if the destructor works
14501   // anyway, then the destruction is constant (and must be essentially empty).
14502   APValue DestroyedValue;
14503   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14504     DestroyedValue = *getEvaluatedValue();
14505   else if (!getDefaultInitValue(getType(), DestroyedValue))
14506     return false;
14507 
14508   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
14509   Info.setEvaluatingDecl(this, DestroyedValue,
14510                          EvalInfo::EvaluatingDeclKind::Dtor);
14511   Info.InConstantContext = true;
14512 
14513   SourceLocation DeclLoc = getLocation();
14514   QualType DeclTy = getType();
14515 
14516   LValue LVal;
14517   LVal.set(this);
14518 
14519   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14520       EStatus.HasSideEffects)
14521     return false;
14522 
14523   if (!Info.discardCleanups())
14524     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14525 
14526   ensureEvaluatedStmt()->HasConstantDestruction = true;
14527   return true;
14528 }
14529 
14530 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14531 /// constant folded, but discard the result.
14532 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14533   assert(!isValueDependent() &&
14534          "Expression evaluator can't be called on a dependent expression.");
14535 
14536   EvalResult Result;
14537   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14538          !hasUnacceptableSideEffect(Result, SEK);
14539 }
14540 
14541 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14542                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14543   assert(!isValueDependent() &&
14544          "Expression evaluator can't be called on a dependent expression.");
14545 
14546   EvalResult EVResult;
14547   EVResult.Diag = Diag;
14548   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14549   Info.InConstantContext = true;
14550 
14551   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14552   (void)Result;
14553   assert(Result && "Could not evaluate expression");
14554   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14555 
14556   return EVResult.Val.getInt();
14557 }
14558 
14559 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14560     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14561   assert(!isValueDependent() &&
14562          "Expression evaluator can't be called on a dependent expression.");
14563 
14564   EvalResult EVResult;
14565   EVResult.Diag = Diag;
14566   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14567   Info.InConstantContext = true;
14568   Info.CheckingForUndefinedBehavior = true;
14569 
14570   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14571   (void)Result;
14572   assert(Result && "Could not evaluate expression");
14573   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14574 
14575   return EVResult.Val.getInt();
14576 }
14577 
14578 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14579   assert(!isValueDependent() &&
14580          "Expression evaluator can't be called on a dependent expression.");
14581 
14582   bool IsConst;
14583   EvalResult EVResult;
14584   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14585     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14586     Info.CheckingForUndefinedBehavior = true;
14587     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14588   }
14589 }
14590 
14591 bool Expr::EvalResult::isGlobalLValue() const {
14592   assert(Val.isLValue());
14593   return IsGlobalLValue(Val.getLValueBase());
14594 }
14595 
14596 
14597 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14598 /// an integer constant expression.
14599 
14600 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14601 /// comma, etc
14602 
14603 // CheckICE - This function does the fundamental ICE checking: the returned
14604 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14605 // and a (possibly null) SourceLocation indicating the location of the problem.
14606 //
14607 // Note that to reduce code duplication, this helper does no evaluation
14608 // itself; the caller checks whether the expression is evaluatable, and
14609 // in the rare cases where CheckICE actually cares about the evaluated
14610 // value, it calls into Evaluate.
14611 
14612 namespace {
14613 
14614 enum ICEKind {
14615   /// This expression is an ICE.
14616   IK_ICE,
14617   /// This expression is not an ICE, but if it isn't evaluated, it's
14618   /// a legal subexpression for an ICE. This return value is used to handle
14619   /// the comma operator in C99 mode, and non-constant subexpressions.
14620   IK_ICEIfUnevaluated,
14621   /// This expression is not an ICE, and is not a legal subexpression for one.
14622   IK_NotICE
14623 };
14624 
14625 struct ICEDiag {
14626   ICEKind Kind;
14627   SourceLocation Loc;
14628 
14629   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14630 };
14631 
14632 }
14633 
14634 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14635 
14636 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14637 
14638 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14639   Expr::EvalResult EVResult;
14640   Expr::EvalStatus Status;
14641   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14642 
14643   Info.InConstantContext = true;
14644   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14645       !EVResult.Val.isInt())
14646     return ICEDiag(IK_NotICE, E->getBeginLoc());
14647 
14648   return NoDiag();
14649 }
14650 
14651 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14652   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14653   if (!E->getType()->isIntegralOrEnumerationType())
14654     return ICEDiag(IK_NotICE, E->getBeginLoc());
14655 
14656   switch (E->getStmtClass()) {
14657 #define ABSTRACT_STMT(Node)
14658 #define STMT(Node, Base) case Expr::Node##Class:
14659 #define EXPR(Node, Base)
14660 #include "clang/AST/StmtNodes.inc"
14661   case Expr::PredefinedExprClass:
14662   case Expr::FloatingLiteralClass:
14663   case Expr::ImaginaryLiteralClass:
14664   case Expr::StringLiteralClass:
14665   case Expr::ArraySubscriptExprClass:
14666   case Expr::MatrixSubscriptExprClass:
14667   case Expr::OMPArraySectionExprClass:
14668   case Expr::OMPArrayShapingExprClass:
14669   case Expr::OMPIteratorExprClass:
14670   case Expr::MemberExprClass:
14671   case Expr::CompoundAssignOperatorClass:
14672   case Expr::CompoundLiteralExprClass:
14673   case Expr::ExtVectorElementExprClass:
14674   case Expr::DesignatedInitExprClass:
14675   case Expr::ArrayInitLoopExprClass:
14676   case Expr::ArrayInitIndexExprClass:
14677   case Expr::NoInitExprClass:
14678   case Expr::DesignatedInitUpdateExprClass:
14679   case Expr::ImplicitValueInitExprClass:
14680   case Expr::ParenListExprClass:
14681   case Expr::VAArgExprClass:
14682   case Expr::AddrLabelExprClass:
14683   case Expr::StmtExprClass:
14684   case Expr::CXXMemberCallExprClass:
14685   case Expr::CUDAKernelCallExprClass:
14686   case Expr::CXXAddrspaceCastExprClass:
14687   case Expr::CXXDynamicCastExprClass:
14688   case Expr::CXXTypeidExprClass:
14689   case Expr::CXXUuidofExprClass:
14690   case Expr::MSPropertyRefExprClass:
14691   case Expr::MSPropertySubscriptExprClass:
14692   case Expr::CXXNullPtrLiteralExprClass:
14693   case Expr::UserDefinedLiteralClass:
14694   case Expr::CXXThisExprClass:
14695   case Expr::CXXThrowExprClass:
14696   case Expr::CXXNewExprClass:
14697   case Expr::CXXDeleteExprClass:
14698   case Expr::CXXPseudoDestructorExprClass:
14699   case Expr::UnresolvedLookupExprClass:
14700   case Expr::TypoExprClass:
14701   case Expr::RecoveryExprClass:
14702   case Expr::DependentScopeDeclRefExprClass:
14703   case Expr::CXXConstructExprClass:
14704   case Expr::CXXInheritedCtorInitExprClass:
14705   case Expr::CXXStdInitializerListExprClass:
14706   case Expr::CXXBindTemporaryExprClass:
14707   case Expr::ExprWithCleanupsClass:
14708   case Expr::CXXTemporaryObjectExprClass:
14709   case Expr::CXXUnresolvedConstructExprClass:
14710   case Expr::CXXDependentScopeMemberExprClass:
14711   case Expr::UnresolvedMemberExprClass:
14712   case Expr::ObjCStringLiteralClass:
14713   case Expr::ObjCBoxedExprClass:
14714   case Expr::ObjCArrayLiteralClass:
14715   case Expr::ObjCDictionaryLiteralClass:
14716   case Expr::ObjCEncodeExprClass:
14717   case Expr::ObjCMessageExprClass:
14718   case Expr::ObjCSelectorExprClass:
14719   case Expr::ObjCProtocolExprClass:
14720   case Expr::ObjCIvarRefExprClass:
14721   case Expr::ObjCPropertyRefExprClass:
14722   case Expr::ObjCSubscriptRefExprClass:
14723   case Expr::ObjCIsaExprClass:
14724   case Expr::ObjCAvailabilityCheckExprClass:
14725   case Expr::ShuffleVectorExprClass:
14726   case Expr::ConvertVectorExprClass:
14727   case Expr::BlockExprClass:
14728   case Expr::NoStmtClass:
14729   case Expr::OpaqueValueExprClass:
14730   case Expr::PackExpansionExprClass:
14731   case Expr::SubstNonTypeTemplateParmPackExprClass:
14732   case Expr::FunctionParmPackExprClass:
14733   case Expr::AsTypeExprClass:
14734   case Expr::ObjCIndirectCopyRestoreExprClass:
14735   case Expr::MaterializeTemporaryExprClass:
14736   case Expr::PseudoObjectExprClass:
14737   case Expr::AtomicExprClass:
14738   case Expr::LambdaExprClass:
14739   case Expr::CXXFoldExprClass:
14740   case Expr::CoawaitExprClass:
14741   case Expr::DependentCoawaitExprClass:
14742   case Expr::CoyieldExprClass:
14743     return ICEDiag(IK_NotICE, E->getBeginLoc());
14744 
14745   case Expr::InitListExprClass: {
14746     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14747     // form "T x = { a };" is equivalent to "T x = a;".
14748     // Unless we're initializing a reference, T is a scalar as it is known to be
14749     // of integral or enumeration type.
14750     if (E->isRValue())
14751       if (cast<InitListExpr>(E)->getNumInits() == 1)
14752         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14753     return ICEDiag(IK_NotICE, E->getBeginLoc());
14754   }
14755 
14756   case Expr::SizeOfPackExprClass:
14757   case Expr::GNUNullExprClass:
14758   case Expr::SourceLocExprClass:
14759     return NoDiag();
14760 
14761   case Expr::SubstNonTypeTemplateParmExprClass:
14762     return
14763       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14764 
14765   case Expr::ConstantExprClass:
14766     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14767 
14768   case Expr::ParenExprClass:
14769     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14770   case Expr::GenericSelectionExprClass:
14771     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14772   case Expr::IntegerLiteralClass:
14773   case Expr::FixedPointLiteralClass:
14774   case Expr::CharacterLiteralClass:
14775   case Expr::ObjCBoolLiteralExprClass:
14776   case Expr::CXXBoolLiteralExprClass:
14777   case Expr::CXXScalarValueInitExprClass:
14778   case Expr::TypeTraitExprClass:
14779   case Expr::ConceptSpecializationExprClass:
14780   case Expr::RequiresExprClass:
14781   case Expr::ArrayTypeTraitExprClass:
14782   case Expr::ExpressionTraitExprClass:
14783   case Expr::CXXNoexceptExprClass:
14784     return NoDiag();
14785   case Expr::CallExprClass:
14786   case Expr::CXXOperatorCallExprClass: {
14787     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14788     // constant expressions, but they can never be ICEs because an ICE cannot
14789     // contain an operand of (pointer to) function type.
14790     const CallExpr *CE = cast<CallExpr>(E);
14791     if (CE->getBuiltinCallee())
14792       return CheckEvalInICE(E, Ctx);
14793     return ICEDiag(IK_NotICE, E->getBeginLoc());
14794   }
14795   case Expr::CXXRewrittenBinaryOperatorClass:
14796     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14797                     Ctx);
14798   case Expr::DeclRefExprClass: {
14799     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14800       return NoDiag();
14801     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14802     if (Ctx.getLangOpts().CPlusPlus &&
14803         D && IsConstNonVolatile(D->getType())) {
14804       // Parameter variables are never constants.  Without this check,
14805       // getAnyInitializer() can find a default argument, which leads
14806       // to chaos.
14807       if (isa<ParmVarDecl>(D))
14808         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14809 
14810       // C++ 7.1.5.1p2
14811       //   A variable of non-volatile const-qualified integral or enumeration
14812       //   type initialized by an ICE can be used in ICEs.
14813       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14814         if (!Dcl->getType()->isIntegralOrEnumerationType())
14815           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14816 
14817         const VarDecl *VD;
14818         // Look for a declaration of this variable that has an initializer, and
14819         // check whether it is an ICE.
14820         if (Dcl->getAnyInitializer(VD) && !VD->isWeak() && VD->checkInitIsICE())
14821           return NoDiag();
14822         else
14823           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14824       }
14825     }
14826     return ICEDiag(IK_NotICE, E->getBeginLoc());
14827   }
14828   case Expr::UnaryOperatorClass: {
14829     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14830     switch (Exp->getOpcode()) {
14831     case UO_PostInc:
14832     case UO_PostDec:
14833     case UO_PreInc:
14834     case UO_PreDec:
14835     case UO_AddrOf:
14836     case UO_Deref:
14837     case UO_Coawait:
14838       // C99 6.6/3 allows increment and decrement within unevaluated
14839       // subexpressions of constant expressions, but they can never be ICEs
14840       // because an ICE cannot contain an lvalue operand.
14841       return ICEDiag(IK_NotICE, E->getBeginLoc());
14842     case UO_Extension:
14843     case UO_LNot:
14844     case UO_Plus:
14845     case UO_Minus:
14846     case UO_Not:
14847     case UO_Real:
14848     case UO_Imag:
14849       return CheckICE(Exp->getSubExpr(), Ctx);
14850     }
14851     llvm_unreachable("invalid unary operator class");
14852   }
14853   case Expr::OffsetOfExprClass: {
14854     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14855     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14856     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14857     // compliance: we should warn earlier for offsetof expressions with
14858     // array subscripts that aren't ICEs, and if the array subscripts
14859     // are ICEs, the value of the offsetof must be an integer constant.
14860     return CheckEvalInICE(E, Ctx);
14861   }
14862   case Expr::UnaryExprOrTypeTraitExprClass: {
14863     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14864     if ((Exp->getKind() ==  UETT_SizeOf) &&
14865         Exp->getTypeOfArgument()->isVariableArrayType())
14866       return ICEDiag(IK_NotICE, E->getBeginLoc());
14867     return NoDiag();
14868   }
14869   case Expr::BinaryOperatorClass: {
14870     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14871     switch (Exp->getOpcode()) {
14872     case BO_PtrMemD:
14873     case BO_PtrMemI:
14874     case BO_Assign:
14875     case BO_MulAssign:
14876     case BO_DivAssign:
14877     case BO_RemAssign:
14878     case BO_AddAssign:
14879     case BO_SubAssign:
14880     case BO_ShlAssign:
14881     case BO_ShrAssign:
14882     case BO_AndAssign:
14883     case BO_XorAssign:
14884     case BO_OrAssign:
14885       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14886       // constant expressions, but they can never be ICEs because an ICE cannot
14887       // contain an lvalue operand.
14888       return ICEDiag(IK_NotICE, E->getBeginLoc());
14889 
14890     case BO_Mul:
14891     case BO_Div:
14892     case BO_Rem:
14893     case BO_Add:
14894     case BO_Sub:
14895     case BO_Shl:
14896     case BO_Shr:
14897     case BO_LT:
14898     case BO_GT:
14899     case BO_LE:
14900     case BO_GE:
14901     case BO_EQ:
14902     case BO_NE:
14903     case BO_And:
14904     case BO_Xor:
14905     case BO_Or:
14906     case BO_Comma:
14907     case BO_Cmp: {
14908       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14909       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14910       if (Exp->getOpcode() == BO_Div ||
14911           Exp->getOpcode() == BO_Rem) {
14912         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14913         // we don't evaluate one.
14914         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14915           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14916           if (REval == 0)
14917             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14918           if (REval.isSigned() && REval.isAllOnesValue()) {
14919             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14920             if (LEval.isMinSignedValue())
14921               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14922           }
14923         }
14924       }
14925       if (Exp->getOpcode() == BO_Comma) {
14926         if (Ctx.getLangOpts().C99) {
14927           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14928           // if it isn't evaluated.
14929           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14930             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14931         } else {
14932           // In both C89 and C++, commas in ICEs are illegal.
14933           return ICEDiag(IK_NotICE, E->getBeginLoc());
14934         }
14935       }
14936       return Worst(LHSResult, RHSResult);
14937     }
14938     case BO_LAnd:
14939     case BO_LOr: {
14940       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14941       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14942       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14943         // Rare case where the RHS has a comma "side-effect"; we need
14944         // to actually check the condition to see whether the side
14945         // with the comma is evaluated.
14946         if ((Exp->getOpcode() == BO_LAnd) !=
14947             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14948           return RHSResult;
14949         return NoDiag();
14950       }
14951 
14952       return Worst(LHSResult, RHSResult);
14953     }
14954     }
14955     llvm_unreachable("invalid binary operator kind");
14956   }
14957   case Expr::ImplicitCastExprClass:
14958   case Expr::CStyleCastExprClass:
14959   case Expr::CXXFunctionalCastExprClass:
14960   case Expr::CXXStaticCastExprClass:
14961   case Expr::CXXReinterpretCastExprClass:
14962   case Expr::CXXConstCastExprClass:
14963   case Expr::ObjCBridgedCastExprClass: {
14964     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14965     if (isa<ExplicitCastExpr>(E)) {
14966       if (const FloatingLiteral *FL
14967             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14968         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14969         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14970         APSInt IgnoredVal(DestWidth, !DestSigned);
14971         bool Ignored;
14972         // If the value does not fit in the destination type, the behavior is
14973         // undefined, so we are not required to treat it as a constant
14974         // expression.
14975         if (FL->getValue().convertToInteger(IgnoredVal,
14976                                             llvm::APFloat::rmTowardZero,
14977                                             &Ignored) & APFloat::opInvalidOp)
14978           return ICEDiag(IK_NotICE, E->getBeginLoc());
14979         return NoDiag();
14980       }
14981     }
14982     switch (cast<CastExpr>(E)->getCastKind()) {
14983     case CK_LValueToRValue:
14984     case CK_AtomicToNonAtomic:
14985     case CK_NonAtomicToAtomic:
14986     case CK_NoOp:
14987     case CK_IntegralToBoolean:
14988     case CK_IntegralCast:
14989       return CheckICE(SubExpr, Ctx);
14990     default:
14991       return ICEDiag(IK_NotICE, E->getBeginLoc());
14992     }
14993   }
14994   case Expr::BinaryConditionalOperatorClass: {
14995     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14996     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14997     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14998     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14999     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15000     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15001     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15002         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15003     return FalseResult;
15004   }
15005   case Expr::ConditionalOperatorClass: {
15006     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15007     // If the condition (ignoring parens) is a __builtin_constant_p call,
15008     // then only the true side is actually considered in an integer constant
15009     // expression, and it is fully evaluated.  This is an important GNU
15010     // extension.  See GCC PR38377 for discussion.
15011     if (const CallExpr *CallCE
15012         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15013       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15014         return CheckEvalInICE(E, Ctx);
15015     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15016     if (CondResult.Kind == IK_NotICE)
15017       return CondResult;
15018 
15019     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15020     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15021 
15022     if (TrueResult.Kind == IK_NotICE)
15023       return TrueResult;
15024     if (FalseResult.Kind == IK_NotICE)
15025       return FalseResult;
15026     if (CondResult.Kind == IK_ICEIfUnevaluated)
15027       return CondResult;
15028     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15029       return NoDiag();
15030     // Rare case where the diagnostics depend on which side is evaluated
15031     // Note that if we get here, CondResult is 0, and at least one of
15032     // TrueResult and FalseResult is non-zero.
15033     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15034       return FalseResult;
15035     return TrueResult;
15036   }
15037   case Expr::CXXDefaultArgExprClass:
15038     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15039   case Expr::CXXDefaultInitExprClass:
15040     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15041   case Expr::ChooseExprClass: {
15042     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15043   }
15044   case Expr::BuiltinBitCastExprClass: {
15045     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15046       return ICEDiag(IK_NotICE, E->getBeginLoc());
15047     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15048   }
15049   }
15050 
15051   llvm_unreachable("Invalid StmtClass!");
15052 }
15053 
15054 /// Evaluate an expression as a C++11 integral constant expression.
15055 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15056                                                     const Expr *E,
15057                                                     llvm::APSInt *Value,
15058                                                     SourceLocation *Loc) {
15059   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15060     if (Loc) *Loc = E->getExprLoc();
15061     return false;
15062   }
15063 
15064   APValue Result;
15065   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15066     return false;
15067 
15068   if (!Result.isInt()) {
15069     if (Loc) *Loc = E->getExprLoc();
15070     return false;
15071   }
15072 
15073   if (Value) *Value = Result.getInt();
15074   return true;
15075 }
15076 
15077 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15078                                  SourceLocation *Loc) const {
15079   assert(!isValueDependent() &&
15080          "Expression evaluator can't be called on a dependent expression.");
15081 
15082   if (Ctx.getLangOpts().CPlusPlus11)
15083     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15084 
15085   ICEDiag D = CheckICE(this, Ctx);
15086   if (D.Kind != IK_ICE) {
15087     if (Loc) *Loc = D.Loc;
15088     return false;
15089   }
15090   return true;
15091 }
15092 
15093 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15094                                                     SourceLocation *Loc,
15095                                                     bool isEvaluated) const {
15096   assert(!isValueDependent() &&
15097          "Expression evaluator can't be called on a dependent expression.");
15098 
15099   APSInt Value;
15100 
15101   if (Ctx.getLangOpts().CPlusPlus11) {
15102     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15103       return Value;
15104     return None;
15105   }
15106 
15107   if (!isIntegerConstantExpr(Ctx, Loc))
15108     return None;
15109 
15110   // The only possible side-effects here are due to UB discovered in the
15111   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15112   // required to treat the expression as an ICE, so we produce the folded
15113   // value.
15114   EvalResult ExprResult;
15115   Expr::EvalStatus Status;
15116   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15117   Info.InConstantContext = true;
15118 
15119   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15120     llvm_unreachable("ICE cannot be evaluated!");
15121 
15122   return ExprResult.Val.getInt();
15123 }
15124 
15125 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15126   assert(!isValueDependent() &&
15127          "Expression evaluator can't be called on a dependent expression.");
15128 
15129   return CheckICE(this, Ctx).Kind == IK_ICE;
15130 }
15131 
15132 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15133                                SourceLocation *Loc) const {
15134   assert(!isValueDependent() &&
15135          "Expression evaluator can't be called on a dependent expression.");
15136 
15137   // We support this checking in C++98 mode in order to diagnose compatibility
15138   // issues.
15139   assert(Ctx.getLangOpts().CPlusPlus);
15140 
15141   // Build evaluation settings.
15142   Expr::EvalStatus Status;
15143   SmallVector<PartialDiagnosticAt, 8> Diags;
15144   Status.Diag = &Diags;
15145   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15146 
15147   APValue Scratch;
15148   bool IsConstExpr =
15149       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15150       // FIXME: We don't produce a diagnostic for this, but the callers that
15151       // call us on arbitrary full-expressions should generally not care.
15152       Info.discardCleanups() && !Status.HasSideEffects;
15153 
15154   if (!Diags.empty()) {
15155     IsConstExpr = false;
15156     if (Loc) *Loc = Diags[0].first;
15157   } else if (!IsConstExpr) {
15158     // FIXME: This shouldn't happen.
15159     if (Loc) *Loc = getExprLoc();
15160   }
15161 
15162   return IsConstExpr;
15163 }
15164 
15165 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15166                                     const FunctionDecl *Callee,
15167                                     ArrayRef<const Expr*> Args,
15168                                     const Expr *This) const {
15169   assert(!isValueDependent() &&
15170          "Expression evaluator can't be called on a dependent expression.");
15171 
15172   Expr::EvalStatus Status;
15173   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15174   Info.InConstantContext = true;
15175 
15176   LValue ThisVal;
15177   const LValue *ThisPtr = nullptr;
15178   if (This) {
15179 #ifndef NDEBUG
15180     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15181     assert(MD && "Don't provide `this` for non-methods.");
15182     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15183 #endif
15184     if (!This->isValueDependent() &&
15185         EvaluateObjectArgument(Info, This, ThisVal) &&
15186         !Info.EvalStatus.HasSideEffects)
15187       ThisPtr = &ThisVal;
15188 
15189     // Ignore any side-effects from a failed evaluation. This is safe because
15190     // they can't interfere with any other argument evaluation.
15191     Info.EvalStatus.HasSideEffects = false;
15192   }
15193 
15194   ArgVector ArgValues(Args.size());
15195   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15196        I != E; ++I) {
15197     if ((*I)->isValueDependent() ||
15198         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
15199         Info.EvalStatus.HasSideEffects)
15200       // If evaluation fails, throw away the argument entirely.
15201       ArgValues[I - Args.begin()] = APValue();
15202 
15203     // Ignore any side-effects from a failed evaluation. This is safe because
15204     // they can't interfere with any other argument evaluation.
15205     Info.EvalStatus.HasSideEffects = false;
15206   }
15207 
15208   // Parameter cleanups happen in the caller and are not part of this
15209   // evaluation.
15210   Info.discardCleanups();
15211   Info.EvalStatus.HasSideEffects = false;
15212 
15213   // Build fake call to Callee.
15214   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
15215                        ArgValues.data());
15216   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15217   FullExpressionRAII Scope(Info);
15218   return Evaluate(Value, Info, this) && Scope.destroy() &&
15219          !Info.EvalStatus.HasSideEffects;
15220 }
15221 
15222 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15223                                    SmallVectorImpl<
15224                                      PartialDiagnosticAt> &Diags) {
15225   // FIXME: It would be useful to check constexpr function templates, but at the
15226   // moment the constant expression evaluator cannot cope with the non-rigorous
15227   // ASTs which we build for dependent expressions.
15228   if (FD->isDependentContext())
15229     return true;
15230 
15231   // Bail out if a constexpr constructor has an initializer that contains an
15232   // error. We deliberately don't produce a diagnostic, as we have produced a
15233   // relevant diagnostic when parsing the error initializer.
15234   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15235     for (const auto *InitExpr : Ctor->inits()) {
15236       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
15237         return false;
15238     }
15239   }
15240   Expr::EvalStatus Status;
15241   Status.Diag = &Diags;
15242 
15243   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15244   Info.InConstantContext = true;
15245   Info.CheckingPotentialConstantExpression = true;
15246 
15247   // The constexpr VM attempts to compile all methods to bytecode here.
15248   if (Info.EnableNewConstInterp) {
15249     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15250     return Diags.empty();
15251   }
15252 
15253   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15254   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15255 
15256   // Fabricate an arbitrary expression on the stack and pretend that it
15257   // is a temporary being used as the 'this' pointer.
15258   LValue This;
15259   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15260   This.set({&VIE, Info.CurrentCall->Index});
15261 
15262   ArrayRef<const Expr*> Args;
15263 
15264   APValue Scratch;
15265   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15266     // Evaluate the call as a constant initializer, to allow the construction
15267     // of objects of non-literal types.
15268     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15269     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15270   } else {
15271     SourceLocation Loc = FD->getLocation();
15272     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15273                        Args, FD->getBody(), Info, Scratch, nullptr);
15274   }
15275 
15276   return Diags.empty();
15277 }
15278 
15279 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15280                                               const FunctionDecl *FD,
15281                                               SmallVectorImpl<
15282                                                 PartialDiagnosticAt> &Diags) {
15283   assert(!E->isValueDependent() &&
15284          "Expression evaluator can't be called on a dependent expression.");
15285 
15286   Expr::EvalStatus Status;
15287   Status.Diag = &Diags;
15288 
15289   EvalInfo Info(FD->getASTContext(), Status,
15290                 EvalInfo::EM_ConstantExpressionUnevaluated);
15291   Info.InConstantContext = true;
15292   Info.CheckingPotentialConstantExpression = true;
15293 
15294   // Fabricate a call stack frame to give the arguments a plausible cover story.
15295   ArrayRef<const Expr*> Args;
15296   ArgVector ArgValues(0);
15297   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
15298   (void)Success;
15299   assert(Success &&
15300          "Failed to set up arguments for potential constant evaluation");
15301   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
15302 
15303   APValue ResultScratch;
15304   Evaluate(ResultScratch, Info, E);
15305   return Diags.empty();
15306 }
15307 
15308 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15309                                  unsigned Type) const {
15310   if (!getType()->isPointerType())
15311     return false;
15312 
15313   Expr::EvalStatus Status;
15314   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15315   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15316 }
15317